minggu 7 sql: views and access control - ub

53
Minggu 7 SQL: Views and Access Control 1

Upload: others

Post on 16-Oct-2021

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Minggu 7 SQL: Views and Access Control - UB

Minggu 7SQL: Views and Access ControlSQL: Views and Access Control

1

Page 2: Minggu 7 SQL: Views and Access Control - UB

Learning Outcomes

Pada akhir pertemuan ini, diharapkan Mahasiswa dapat Mendemonstrasikan penggunaan views dan access control statements in SQL Standard (C3)

2

Page 3: Minggu 7 SQL: Views and Access Control - UB

Outline Materi

• Purpose of views.• How to create and delete views using SQL.• How the DBMS performs operations on

views.• Under what conditions views are updatable.• Under what conditions views are updatable.• Advantages and disadvantages of views.• How the ISO transaction model works.• How to use the GRANT and REVOKE

statements as a level of security.

3

Page 4: Minggu 7 SQL: Views and Access Control - UB

Views

ViewDynamic result of one or more relationaloperations operating on base relations toproduce another relation.

• Virtual relation that does notnecessarily actually exist in thedatabase but is produced uponrequest, at time of request.

4

Page 5: Minggu 7 SQL: Views and Access Control - UB

Views

• Contents of a view are defined as aquery on one or more base relations.

• With view resolution, any operationson view are automatically translatedinto operations on relations from whichinto operations on relations from whichit is derived.

• With view materialization, the view isstored as a temporary table, which ismaintained as the underlying basetables are updated.

5

Page 6: Minggu 7 SQL: Views and Access Control - UB

SQL - CREATE VIEW

CREATE VIEW ViewName [ (newColumnName[,...]) ]AS subselect[WITH [CASCADED | LOCAL] CHECKOPTION]

• Can assign a name to each column in view.• Can assign a name to each column in view.• If list of column names is specified, it must

have same number of items as number ofcolumns produced by subselect.

• If omitted, each column takes name ofcorresponding column in subselect.

6

Page 7: Minggu 7 SQL: Views and Access Control - UB

SQL - CREATE VIEW

• List must be specified if there is anyambiguity in a column name.

• The subselect is known as the definingquery.

• WITH CHECK OPTION ensures that if a rowfails to satisfy WHERE clause of definingfails to satisfy WHERE clause of definingquery, it is not added to underlying basetable.

• Need SELECT privilege on all tablesreferenced in subselect and USAGEprivilege on any domains used inreferenced columns.

7

Page 8: Minggu 7 SQL: Views and Access Control - UB

Example 6.3 - Create HorizontalView

Create view so that manager at branchB003 can only see details for staff whowork in his or her office.

CREATE VIEW Manager3StaffAS SELECT *AS SELECT *

FROM StaffWHERE branchNo = ‘B003’;

8

Page 9: Minggu 7 SQL: Views and Access Control - UB

Example 6.4 - Create VerticalView

Create view of staff details at branchB003 excluding salaries.

CREATE VIEW Staff3ASSELECT staffNo, fName, lName, position, sex

FROM StaffFROM StaffWHERE branchNo = ‘B003’;

9

Page 10: Minggu 7 SQL: Views and Access Control - UB

Example 6.5 - Grouped andJoined Views

Create view of staff who manageproperties for rent, including branchnumber they work at, staff number, andnumber of properties they manage.

CREATE VIEW StaffPropCnt (branchNo,CREATE VIEW StaffPropCnt (branchNo,staffNo, cnt)AS SELECT s.branchNo, s.staffNo, COUNT(*)

FROM Staff s, PropertyForRent pWHERE s.staffNo = p.staffNoGROUP BY s.branchNo, s.staffNo;

10

Page 11: Minggu 7 SQL: Views and Access Control - UB

Example 6.3 - Grouped andJoined Views

11

Page 12: Minggu 7 SQL: Views and Access Control - UB

SQL - DROP VIEW

DROP VIEW ViewName [RESTRICT | CASCADE]

• Causes definition of view to be deletedfrom database.from database.

• For example:DROP VIEW Manager3Staff;

12

Page 13: Minggu 7 SQL: Views and Access Control - UB

SQL - DROP VIEW

• With CASCADE, all related dependentobjects are deleted; i.e. any viewsdefined on view being dropped.

• With RESTRICT (default), if any other• With RESTRICT (default), if any otherobjects depend for their existence oncontinued existence of view beingdropped, command is rejected.

13

Page 14: Minggu 7 SQL: Views and Access Control - UB

View Resolution

Count number of properties managed byeach member at branch B003.

SELECT staffNo, cntSELECT staffNo, cntFROM StaffPropCntWHERE branchNo = ‘B003’ORDER BY staffNo;

14

Page 15: Minggu 7 SQL: Views and Access Control - UB

View Resolution

(a) View column names in SELECT listare translated into theircorresponding column names in thedefining query:

SELECT s.staffNo As staffNo, COUNT(*) AsSELECT s.staffNo As staffNo, COUNT(*) Ascnt

(b) View names in FROM are replacedwith corresponding FROM lists ofdefining query:

FROM Staff s, PropertyForRent p15

Page 16: Minggu 7 SQL: Views and Access Control - UB

View Resolution

(c) WHERE from user query is combined withWHERE of defining query using AND:WHERE s.staffNo = p.staffNo AND

branchNo = ‘B003’(d) GROUP BY and HAVING clauses copied

from defining query:from defining query:GROUP BY s.branchNo, s.staffNo

(e) ORDER BY copied from query with viewcolumn name translated into defining querycolumn name

ORDER BY s.staffNo16

Page 17: Minggu 7 SQL: Views and Access Control - UB

View Resolution

(f) Final merged query is now executed toproduce the result:SELECT s.staffNo, COUNT(*)FROM staff s, PropertyForRent pFROM staff s, PropertyForRent pWHERE s.staffNo = p.staffNo AND

branchNo = ‘B003’GROUP BY s.branchNo, s.staffNoORDER BY s.staffNo;

17

Page 18: Minggu 7 SQL: Views and Access Control - UB

Restrictions on Views

SQL imposes several restrictions oncreation and use of views.

(a) If column in view is based on anaggregate function:aggregate function:

– Column may appear only in SELECT andORDER BY clauses of queries that accessview.

– Column may not be used in WHERE nor bean argument to an aggregate function in anyquery based on view.

18

Page 19: Minggu 7 SQL: Views and Access Control - UB

Restrictions on Views

• For example, following query wouldfail:

SELECT COUNT(cnt)FROM StaffPropCnt;

• Similarly, following query would also• Similarly, following query would alsofail:

SELECT *FROM StaffPropCntWHERE cnt > 2;

19

Page 20: Minggu 7 SQL: Views and Access Control - UB

Restrictions on Views

(b) Grouped view may never be joinedwith a base table or a view.

• For example, StaffPropCnt view is a• For example, StaffPropCnt view is agrouped view, so any attempt to jointhis view with another table or viewfails.

20

Page 21: Minggu 7 SQL: Views and Access Control - UB

View Updatability

• All updates to base table reflected in allviews that encompass base table.

• Similarly, may expect that if view isupdated then base table(s) will reflectupdated then base table(s) will reflectchange.

21

Page 22: Minggu 7 SQL: Views and Access Control - UB

View Updatability

• However, consider again viewStaffPropCnt.

• If we tried to insert record showing that atbranch B003, SG5 manages 2 properties:

INSERT INTO StaffPropCntVALUES (‘B003’, ‘SG5’, 2);

• Have to insert 2 records intoPropertyForRent showing whichproperties SG5 manages. However, do notknow which properties they are; i.e. donot know primary keys!

22

Page 23: Minggu 7 SQL: Views and Access Control - UB

View Updatability

• If change definition of view and replacecount with actual property numbers:

CREATE VIEW StaffPropList (branchNo,staffNo, propertyNo)

AS SELECT s.branchNo, s.staffNo,AS SELECT s.branchNo, s.staffNo,p.propertyNo

FROM Staff s, PropertyForRent pWHERE s.staffNo = p.staffNo;

23

Page 24: Minggu 7 SQL: Views and Access Control - UB

View Updatability

• Now try to insert the record:INSERT INTO StaffPropListVALUES (‘B003’, ‘SG5’, ‘PG19’);

• Still problem, because inPropertyForRent all columns exceptpostcode/staffNo are not allowed nulls.

• However, have no way of givingremaining non-null columns values.

24

Page 25: Minggu 7 SQL: Views and Access Control - UB

View Updatability

• ISO specifies the views that must be updatable insystem that conforms to standard.

• A view is updatable if and only if:- DISTINCT is not specified.- Every element in SELECT list of defining query is acolumn name and no column appears more thanonce.once.- FROM clause specifies only one table, excludingany views based on a join, union, intersection ordifference.- No nested SELECT referencing outer table.- No GROUP BY or HAVING clause.- Also, every row added through view must notviolate integrity constraints of base table.

25

Page 26: Minggu 7 SQL: Views and Access Control - UB

Updatable View

For view to be updatable, DBMS mustbe able to trace any row or columnback to its row or column in the sourcetable.table.

26

Page 27: Minggu 7 SQL: Views and Access Control - UB

WITH CHECK OPTION

• Rows exist in a view because they satisfyWHERE condition of defining query.

• If a row changes and no longer satisfiescondition, it disappears from the view.

• New rows appear within view when• New rows appear within view wheninsert/update on view cause them to satisfyWHERE condition.

• Rows that enter or leave a view are calledmigrating rows.

• WITH CHECK OPTION prohibits a row migrating out of the view.

27

Page 28: Minggu 7 SQL: Views and Access Control - UB

WITH CHECK OPTION

• LOCAL/CASCADED apply to view hierarchies.• With LOCAL, any row insert/update on view

and any view directly or indirectly defined onthis view must not cause row to disappearfrom view unless row also disappears fromderived view/table.

• With CASCADED (default), any row insert/• With CASCADED (default), any row insert/update on this view and on any view directlyor indirectly defined on this view must notcause row to disappear from the view.

28

Page 29: Minggu 7 SQL: Views and Access Control - UB

Example 6.6 - WITH CHECK OPTION

CREATE VIEW Manager3StaffAS SELECT *

FROM StaffWHERE branchNo = ‘B003’

WITH CHECK OPTION;• Cannot update branch number of row• Cannot update branch number of row

B003 to B002 as this would cause rowto migrate from view.

• Also cannot insert a row into view witha branch number that does not equalB003.

29

Page 30: Minggu 7 SQL: Views and Access Control - UB

Example 6.6 - WITH CHECKOPTION• If Manager3Staff is defined not on Staff

directly but on another view of Staff:CREATE VIEW LowSalaryASSELECT * FROM Staff WHERE salary > 9000;

CREATE VIEW HighSalaryASSELECT * FROM LowSalaryASSELECT * FROM LowSalary

WHERE salary > 10000WITH LOCAL CHECK OPTION;

CREATE VIEW Manager3StaffASSELECT * FROM HighSalary

WHERE branchNo = ‘B003’;

30

Page 31: Minggu 7 SQL: Views and Access Control - UB

Example 6.6 - WITH CHECK OPTION

UPDATE Manager3StaffSET salary = 9500WHERE staffNo = ‘SG37’;

• Update would fail: although updatewould cause row to disappear fromHighSalary, row would not disappearHighSalary, row would not disappearfrom LowSalary.

• However, if update tried to set salary to8000, update would succeed as rowwould no longer be part of LowSalary.

31

Page 32: Minggu 7 SQL: Views and Access Control - UB

Example 6.6 - WITH CHECKOPTION

• If HighSalary had specified WITHCASCADED CHECK OPTION, settingsalary to 9500 or 8000 would berejected because row would disappearrejected because row would disappearfrom HighSalary.

• To prevent anomalies like this, eachview should be created using WITHCASCADED CHECK OPTION.

32

Page 33: Minggu 7 SQL: Views and Access Control - UB

Advantages of Views

• Data independence• Currency• Improved security• Reduced complexity• Convenience• Customization• Data integrity

33

Page 34: Minggu 7 SQL: Views and Access Control - UB

Disadvantages of Views

• Update restriction• Structure restriction• Performance

34

Page 35: Minggu 7 SQL: Views and Access Control - UB

View Materialization

• View resolution mechanism may be slow,particularly if view is accessed frequently.

• View materialization stores view astemporary table when view is firstqueried.

• Thereafter, queries based on materializedview can be faster than recomputing vieweach time.

• Difficulty is maintaining the currency ofview while base tables(s) are beingupdated.

35

Page 36: Minggu 7 SQL: Views and Access Control - UB

View Maintenance

• View maintenance aims to apply onlythose changes necessary to keep viewcurrent.

• Consider following view:CREATE VIEW StaffPropRent(staffNo)ASSELECT DISTINCT staffNoASSELECT DISTINCT staffNo

FROM PropertyForRentWHERE branchNo = ‘B003’ AND

rent > 400;

36

Page 37: Minggu 7 SQL: Views and Access Control - UB

View Materialization

• If insert row into PropertyForRent with rent ≤400then view would be unchanged.

• If insert row for property PG24 at branch B003with staffNo = SG19 and rent = 550, then rowwould appear in materialized view.

• If insert row for property PG54 at branch B003with staffNo = SG37 and rent = 450, then no newwith staffNo = SG37 and rent = 450, then no newrow would need to be added to materializedview.

• If delete property PG24, row should be deletedfrom materialized view.

• If delete property PG54, then row for PG37should not be deleted (because of existingproperty PG21).

37

Page 38: Minggu 7 SQL: Views and Access Control - UB

Transactions

• SQL defines transaction model based onCOMMIT and ROLLBACK.

• Transaction is logical unit of work with oneor more SQL statements guaranteed to beatomic with respect to recovery.

• An SQL transaction automatically begins• An SQL transaction automatically beginswith a transaction-initiating SQL statement(e.g., SELECT, INSERT).

• Changes made by transaction are notvisible to other concurrently executingtransactions until transaction completes.

38

Page 39: Minggu 7 SQL: Views and Access Control - UB

Transactions

• Transaction can complete in one of fourways:- COMMIT ends transaction successfully,making changes permanent.- ROLLBACK aborts transaction, backing outany changes made by transaction.any changes made by transaction.- For programmatic SQL, successful programtermination ends final transactionsuccessfully, even if COMMIT has not beenexecuted.- For programmatic SQL, abnormal programend aborts transaction.

39

Page 40: Minggu 7 SQL: Views and Access Control - UB

Transactions

• New transaction starts with nexttransaction-initiating statement.

• SQL transactions cannot be nested.• SET TRANSACTION configures

transaction:transaction:

SET TRANSACTION[READ ONLY | READ WRITE] |[ISOLATION LEVEL READ UNCOMMITTED |READ COMMITTED|REPEATABLE READ|SERIALIZABLE ]

40

Page 41: Minggu 7 SQL: Views and Access Control - UB

Immediate and Deferred Integrity Constraints

• Do not always want constraints to be checkedimmediately, but instead at transactioncommit.

• Constraint may be defined as INITIALLYIMMEDIATE or INITIALLY DEFERRED,indicating mode the constraint assumes atstart of each transaction.start of each transaction.

• In former case, also possible to specifywhether mode can be changed subsequentlyusing qualifier [NOT] DEFERRABLE.

• Default mode is INITIALLY IMMEDIATE.

41

Page 42: Minggu 7 SQL: Views and Access Control - UB

Immediate and Deferred IntegrityConstraints

• SET CONSTRAINTS statement used toset mode for specified constraints forcurrent transaction:

SET CONSTRAINTS{ALL | constraintName [, . . . ]}{DEFERRED ¦ IMMEDIATE}

42

Page 43: Minggu 7 SQL: Views and Access Control - UB

Access Control - Authorization Identifiers and Ownership

• Authorization identifier is normal SQLidentifier used to establish identity of auser. Usually has an associated password.

• Used to determine which objects user mayreference and what operations may beperformed on those objects.performed on those objects.

• Each object created in SQL has an owner,as defined in AUTHORIZATION clause ofschema to which object belongs.

• Owner is only person who may know aboutit.

43

Page 44: Minggu 7 SQL: Views and Access Control - UB

Privileges

• Actions user permitted to carry out ongiven base table or view:

SELECT Retrieve data from a table.INSERT Insert new rows into a table.UPDATE Modify rows of data in a table.UPDATE Modify rows of data in a table.DELETE Delete rows of data from a table.REFERENCES Reference columns of

named table in integrity constraints.USAGE Use domains, collations,

character sets, and translations.44

Page 45: Minggu 7 SQL: Views and Access Control - UB

Privileges

• Can restrictINSERT/UPDATE/REFERENCES tonamed columns.

• Owner of table must grant other usersthe necessary privileges using GRANTstatement.

• To create view, user must have SELECTprivilege on all tables that make up viewand REFERENCES privilege on thenamed columns.

45

Page 46: Minggu 7 SQL: Views and Access Control - UB

GRANT

GRANT {PrivilegeList | ALL PRIVILEGES}ON ObjectNameTO {AuthorizationIdList | PUBLIC}[WITH GRANT OPTION][WITH GRANT OPTION]

• PrivilegeList consists of one or more ofabove privileges separated by commas.

• ALL PRIVILEGES grants all privilegesto a user.

46

Page 47: Minggu 7 SQL: Views and Access Control - UB

GRANT

• PUBLIC allows access to be granted to all present and future authorized users.

• ObjectName can be a base table, view,domain, character set, collation ordomain, character set, collation ortranslation.

• WITH GRANT OPTION allows privilegesto be passed on.

47

Page 48: Minggu 7 SQL: Views and Access Control - UB

Example 6.7/8 - GRANT

Give Manager full privileges to Staff table.GRANT ALL PRIVILEGESON StaffTO Manager WITH GRANT OPTION;

Give users Personnel and Director SELECTGive users Personnel and Director SELECTand UPDATE on column salary of Staff.

GRANT SELECT, UPDATE (salary)ON StaffTO Personnel, Director;

48

Page 49: Minggu 7 SQL: Views and Access Control - UB

Example 6.9 - GRANT Specific Privileges to PUBLIC

Give all users SELECT on Branch table.

GRANT SELECTON BranchON BranchTO PUBLIC;

49

Page 50: Minggu 7 SQL: Views and Access Control - UB

REVOKE

• REVOKE takes away privileges granted withGRANT.

REVOKE [GRANT OPTION FOR]{PrivilegeList | ALL PRIVILEGES}

ON ObjectNameFROM {AuthorizationIdList | PUBLIC}FROM {AuthorizationIdList | PUBLIC}

[RESTRICT | CASCADE]

• ALL PRIVILEGES refers to all privilegesgranted to a user by user revoking privileges.

50

Page 51: Minggu 7 SQL: Views and Access Control - UB

REVOKE

• GRANT OPTION FOR allows privilegespassed on via WITH GRANT OPTION ofGRANT to be revoked separately fromthe privileges themselves.

• REVOKE fails if it results in anabandoned object, such as a view,unless the CASCADE keyword has beenspecified.

• Privileges granted to this user by otherusers are not affected.

51

Page 52: Minggu 7 SQL: Views and Access Control - UB

REVOKE

52

Page 53: Minggu 7 SQL: Views and Access Control - UB

Example 6.10/11 - REVOKE Specific Privileges

Revoke privilege SELECT on Branchtable from all users.

REVOKE SELECTON BranchON BranchFROM PUBLIC;

Revoke all privileges given to Directoron Staff table.

REVOKE ALL PRIVILEGESON StaffFROM Director;

53