1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen 2002-2009 Maintaining Session State in the Data.

Slides:



Advertisements
Similar presentations
Oracle Object-Relational Model. - Structures : tables, views, indexes, etc. - Operations : actions that manipulate data stored in structures - Integrity.
Advertisements

Oracle PL/SQL IV Exceptions Packages.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Organization of Large Database Applications.
Manipulating Data Schedule: Timing Topic 60 minutes Lecture
NMED 3850 A Advanced Online Design February 25, 2010 V. Mahadevan.
Triggers The different types of integrity constraints discussed so far provide a declarative mechanism to associate “simple” conditions with a table such.
Advanced Package Concepts. 2 home back first prev next last What Will I Learn? Write packages that use the overloading feature Write packages that use.
Chapter 3 An Introduction to Relational Databases.
Working with SQL and PL/SQL/ Session 1 / 1 of 27 SQL Server Architecture.
1 PL/SQL programming Procedures and Cursors Lecture 1 Akhtar Ali.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
Introduction to DBMS and SQL Introduction to DBMS and SQL GUIDED BY : MR. YOGESH SAROJ (PGT-CS) MR. YOGESH SAROJ (PGT-CS) Presented By : JAYA XII –COM.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Introduction to Objects & Databases These.
Cursor and Exception Handling By Nidhi Bhatnagar.
Chapter 3 An Introduction to Relational Databases.
Oracle PL/SQL Programming Steven Feuerstein All About the (Amazing) Function Result Cache of Oracle Database 11g.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen M:N Relationships & Bridge Classes These.
ADO.NET A2 Teacher Up skilling LECTURE 3. What’s to come today? ADO.NET What is ADO.NET? ADO.NET Objects SqlConnection SqlCommand SqlDataReader DataSet.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Enforcing Access Constraints with Privileges.
Lecture 4 PL/SQL language. PL/SQL – procedural SQL Allows combining procedural and SQL code PL/SQL code is compiled, including SQL commands PL/SQL code.
Tom Castiglia Hershey Technologies
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 7 PL/SQL Packages.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Security and Data-Tier Implementations.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen :1 Relationships These slides are licensed.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 6 Functions.
PL/SQLPL/SQL Oracle11g : PL/SQL Programming Chapter 6 Functions.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Introduction to Relational Databases &
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Cursors These slides are licensed under.
PL/SQL A BRIEF OVERVIEW DAVID WILSON. PL/SQL User’s Guide and Reference PL/SQL User’s Guide and Reference.
1 ICS 184: Introduction to Data Management Lecture Note 11: Assertions, Triggers, and Index.
Triggers and Stored Procedures in DB 1. Objectives Learn what triggers and stored procedures are Learn the benefits of using them Learn how DB2 implements.
PL SQL Block Structures. What is PL SQL A good way to get acquainted with PL/SQL is to look at a sample program. PL/SQL combines the data manipulating.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Enforcing State & Transition Constraints.
1 IT420: Database Management and Organization Session Control Managing Multi-user Databases 24 March 2006 Adina Crăiniceanu
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Basic SQL These slides are licensed under.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Maintaining Session State in the Data.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Conditions & Roles These slides are licensed.
Advanced SQL: Triggers & Assertions
What is a Package? A package is an Oracle object, which holds other objects within it. Objects commonly held within a package are procedures, functions,
Topics Related to Attribute Values Objectives of the Lecture : To consider sorting relations by attribute values. To consider Triggers and their use for.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Implementing The Middle Tier These slides.
Dynamic SQL. 2 home back first prev next last What Will I Learn? Recall the stages through which all SQL statements pass Describe the reasons for using.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Subqueries These slides are licensed under.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Object-Relational Database Programming.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Using Data Structures in Embedded Programs.
1 Intro stored procedures Declaring parameters Using in a sproc Intro to transactions Concurrency control & recovery States of transactions Desirable.
Transactions, Roles & Privileges Oracle and ANSI Standard SQL Lecture 11.
Altering Tables and Constraints Database Systems Objectives Add and modify columns. Add, enable, disable, or remove constraints. Drop a table. Remove.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Relational State Assertions These slides.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Collection Operators These slides are.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Grouping These slides are licensed under.
PL/SQL programming Procedures and Cursors Lecture 1 [Part 2]
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Collection Operators These slides are.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Specifying & Enforcing Access Constraints.
CSCI N311: Oracle Database Programming 5-1 Chapter 15: Changing Data: insert, update, delete Insert Rollback Commit Update Delete Insert Statement –Allows.
20 Copyright © 2006, Oracle. All rights reserved. Best Practices and Operational Considerations.
SAP R/3 User Administration1. 2 User administration in a productive environment is an ongoing process of creating, deleting, changing, and monitoring.
What Are Subprograms? Subprograms are named PL/SQL blocks that can take parameters and be invoked. Subprograms allow decomposition of a program into logical.
Chapter 3 An Introduction to Relational Databases.
Oracle9i Developer: PL/SQL Programming Chapter 6 PL/SQL Packages.
SQL PL/SQL Presented by: Dr. Samir Tartir
Introduction to Database Systems, CS420
Working with Composite Datatypes
PL/SQL week10.
Copyright © Ellis Cohen Consistency & Initialization
Triggers.
Prof. Arfaoui. COM390 Chapter 7
Copyright © Ellis Cohen Enforcing State Constraints
Database Programming Using Oracle 11g
Presentation transcript:

1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Maintaining Session State in the Data Tier These slides are licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License. For more information on how you may use them, please see

2 © Ellis Cohen Overview of Lecture Temporary Session Tables Package Variables Problems with Middle Tier Session Data Maintaining Session State in the Data Tier Multi-User & Virtual Connections Shared Multi-User Connections Adding Security to Multi-User Connection

3 © Ellis Cohen Temporary Session Tables

4 © Ellis Cohen Session-Specific Information It can be useful to maintain a collection of information separately for each user session We could store this information in tables: –Use a single table, and use the user's session id as part of the primary key –Use a separate table for each user session

5 © Ellis Cohen Temporary Tables A temporary table Has a single CREATE TABLE definition A separate instance of the table is created for each separate database connection that accesses the table The instance of the table is deleted whether the database connected is closed. Assuming that every user session results in a separate connection to the DB, temporary session tables can be used to store user session-specific information

6 © Ellis Cohen Per-User Tables EmpDB Emps Depts Temp U1 U2 Temp for U1 Temp for U2 Two users, U1 and U2, connect to EmpDB Both can access Emps and Depts But Temp is a global temporary table. A separate instance of Temp is made for each of them and each can only access their instance

7 © Ellis Cohen Defining Temporary Tables CREATE GLOBAL TEMPORARY TABLE SomeTable ( … ) ON COMMIT PRESERVE ROWS; Session Tables: Use ON COMMIT PRESERVE ROWS, which retains the data in each table instance from transaction to transaction (just like permanent tables) Transaction Tables: Use ON COMMIT DELETE ROWS which automatically empties the data in each table instance at the end of every transaction (this is the default, and is useful for holding temporary data during a transaction)

8 © Ellis Cohen Using Session Tables Suppose our application has a number of user query operations which display information about products we want to keep track of every product we viewed in a session we want to be able to implement a query that shows the ids & names of all products we have viewed in the session so far

9 © Ellis Cohen Remembering Seen Products CREATE GLOBAL TEMPORARY TABLE SeenProducts ( prodid int primary key references Products ) ON COMMIT PRESERVE ROWS; PROCEDURE RememberProduct( aProdid int ) IS BEGIN INSERT INTO SeenProducts VALUES( aProdid ); -- insert the product into the table to remember it -- if it's already there, ignore the exception! EXCEPTION WHEN OTHERS THEN NULL; END;

10 © Ellis Cohen Remembering Displayed Products DECLARE productRec Products%ROWTYPE; BEGIN SELECT * INTO productRec FROM Products WHERE prodid = :prodid; pl( prodRec.prodnam ); pl( prodRec.description ); -- remember it! RememberProduct( :prodid ); EXCEPTION WHEN OTHERS THEN doerr(); END; ShowProduct( :prodid )

11 © Ellis Cohen List Remembered Products SELECT prodid, prodnam FROM Products NATURAL JOIN SeenProducts; ListRememberedProducts If multiple users are connected to the database, each user will have their own copy of SeenProducts

12 © Ellis Cohen Package Variables

13 © Ellis Cohen Package Variables PL/SQL Packages can declare variables A separate instance of each package variable is created for each separate database connection that accesses the package. These can hold typed data in the data tier specific to a database connection.

14 © Ellis Cohen Package Variable Visibility Variables can be declared in the package body: only accessible to procedures and functions also in the package body (i.e. private) the package description: also visible outside of the package. Package variables persistently hold data values for the lifetime of the connection

15 © Ellis Cohen Package Variable Example SQL> CREATE OR REPLACE PACKAGE BODY MyUtil AS startdate date; -- package body variable FUNCTION connectDate RETURN date IS BEGIN RETURN startdate; -- returns the date the user connected END; FUNCTION getNumColumns( tblnam varchar )... BEGIN -- package initialization SELECT sysdate INTO startdate FROM dual; END MyUtil; /

16 © Ellis Cohen Package Variables & Sessions Suppose MyUtil is was created by a user connected to the database as EmpDB. While that user is logged in, another user also connects as EmpDB. What happens to MyUtil.startdate? Is it reinitialized?

17 © Ellis Cohen Package Variables are Per-Connection No. Each different connection to EmpDB will get its own private copy of MyUtil.startdate. And that private copy of MyUtil.startdate will be initialized the first time that MyUtil is accessed by code executed via that connection!

18 © Ellis Cohen Package Body Exercise PACKAGE RememberedEmployee AS PROCEDURE Remember( IN anEmpno number ); -- remembers an employee's number FUNCTION GetEmp return number; -- returns the remembered employee's number FUNCTION GetJob RETURN varchar; -- returns the job of the remembered employee FUNCTION HasHigherSal( IN aSal number ) RETURN boolean; --- indicates whether the remembered employee has a salary higher than aSal END RememberedEmployee; Write the body!

19 © Ellis Cohen Package Body Exercise Answer #1 PACKAGE BODY RememberedEmployee AS remEmpno emp.empno%TYPE; PROCEDURE Remember( IN anEmpno number ) IS BEGIN remEmpno := anEmpno; END; FUNCTION GetEmp RETURN number IS BEGIN RETURN remEmpno; END; FUNCTION GetJob RETURN varchar IS remJob emp.job%TYPE; BEGIN SELECT job INTO remJob FROM Emps WHERE empno = remEmpno; RETURN remJob; END; FUNCTION HasHigherSal( IN aSal number ) RETURN boolean IS remSal emp.sal%TYPE; BEGIN SELECT sal INTO remSal FROM Emps WHERE empno = remEmpno; RETURN (remSal > aSal); END; END RememberedEmployee;

20 © Ellis Cohen Package Body Exercise Answer #2 PACKAGE BODY RememberedEmployee AS remEmpno emp.empno%TYPE; remJob emp.job%TYPE; remSal emp.sal%TYPE; PROCEDURE Remember( IN anEmpno number ) IS BEGIN remEmpno := anEmpno; SELECT job, sal INTO remJob, remSal FROM Emps WHERE empno = anEmpno; END; FUNCTION GetEmp RETURN number IS BEGIN RETURN remEmpno; END; FUNCTION GetJob RETURN varchar IS BEGIN RETURN remJob; END; FUNCTION HasHigherSal( IN aSal number ) RETURN boolean IS BEGIN RETURN (remSal > aSal); END; END RememberedEmployee; Dangerous if job or sal can be changed in Emps

21 © Ellis Cohen Problems with Middle Tier Session Data

22 © Ellis Cohen Middle-Tier Session Variables EmpDB Middle-Tier :curuser 7782 App User 7782 Middle-Tier :curuser 6419 App User 6419

23 © Ellis Cohen Session Variable Placement We've been assuming that middle-tier session variables are the best place to maintain some per-session information such as :curuser Are there any reasons to instead (or also) maintain this information in the data-tier (i.e. in the database?)

24 © Ellis Cohen Data Tier Placement Data tier placement enables –Session recovery on middle-tier crash –Session migration for load balancing –Simpler reusable views and procedures

25 © Ellis Cohen ShowSals using :curuser SELECT empno, ename, sal FROM Emps WHERE empno = :curuser OR mgr = :curuser ShowSals Shows employee #, name & salary of the current user and of all employees the current user directly manages (using the middle tier variable :curuser) Could you write a view that contained the employee #, name & salary of all employees the current user directly manages?

26 © Ellis Cohen Session-Based Views CREATE CurManageView AS SELECT empno, ename FROM Emps WHERE mgr = :curuser Middle-tier session variables can't be used in views. There's no way for the database to access them! (Remember how they are passed in and out of the database!)

27 © Ellis Cohen Maintaining Session State in the Data Tier

28 © Ellis Cohen Package Variables & Session Data Assuming that every user session uses a separate connection to the DB Then package variables can be used to store user session data

29 © Ellis Cohen Data-Tier Session Variables EmpDB Middle-Tier :curuser 7782 App User 7782 Middle-Tier :curuser 6419 App User 6419 curuser 7782 curuser 6419 Data-tier session variables are implemented as package variables, which are maintained separately for each session! With curuser as a package variable

30 © Ellis Cohen AuthPkg Example Suppose our application defines AuthPkg to register and login users, and to keep track of the current user in each session, with operations: PROCEDURE Register( aUser, aPwd, aRole ) PROCEDURE Login( usr, pwd, theRole ) PROCEDURE Logout FUNCTION GetUser RETURN int -- returns logged in user (or NULL) OUT parameter

31 © Ellis Cohen AuthPkg Body CREATE TABLE AuthUsers( userid int PRIMARY KEY, passwd varchar(128), role varchar(30) ); CREATE PACKAGE BODY AuthPkg AS curuser int; PROCEDURE Register( aUser int, aPwd varchar, aRole varchar ) IS BEGIN INSERT INTO AuthUsers VALUES( aUser, aPwd, aRole ); END; PROCEDURE Login( usr int, pwd varchar, theRole OUT char ) IS BEGIN SELECT role INTO theRole FROM AuthUsers WHERE userid = usr AND passwd = pwd; curuser := usr; END; PROCEDURE Logout IS BEGIN curuser := NULL; END; FUNCTION GetUser RETURNS int IS BEGIN RETURN curuser; END; … END AuthPkg; Each DB session (i.e. connection) has its own instance of package variables. So curuser has a value specific to the connected DB session

32 © Ellis Cohen Using AuthPkg in Login DECLARE theRole varchar(30); BEGIN AuthPkg.Login( :userid, :pwd, theRole ); pl( 'Logged in with role ' || theRole ); END; Login( :userid, :pwd ) OUT parameter Returns the role

33 © Ellis Cohen Using Script Variables DECLARE theRole varchar(30); BEGIN AuthPkg.Login( &1, &2, theRole ); pl( 'Logged in with role ' || theRole ); END; Login( :userid, :pwd ) &1 -- :userid &2 -- :pwd

34 © Ellis Cohen ShowSals using :curuser SELECT empno, ename, sal FROM Emps WHERE empno = :curuser OR mgr = :curuser ShowSals Shows employee #, name & salary of the current user and of all employees the current user directly manages (using the middle tier variable :curuser) If the user identity were ONLY maintained in the data tier (via AuthPkg), how would you rewrite ShowSals?

35 © Ellis Cohen ShowSals using AuthPkg SELECT empno, ename, sal FROM Emps WHERE empno = AuthPkg.GetUser OR mgr = AuthPkg.GetUser ShowSals Shows employee #, name & salary of current user and all employees the current user directly manages! Keeping track of the identity of the current user in the data-tier is known as Data-Tier Identity Now how could you write a view that contained the employee #, name & salary of all employees the current user directly manages?

36 © Ellis Cohen Session-Based Views CREATE CurManageView AS SELECT empno, ename FROM Emps WHERE mgr = :curuser CREATE CurManageView AS SELECT empno, ename FROM Emps WHERE mgr = AuthPkg.GetUser Middle-tier session variables can't be used in views. There's no way for the database to access them! But package functions can be used, and they can access session data stored in the package

37 © Ellis Cohen Caching Session Variables in the Middle Tier DECLARE theRole varchar(30); BEGIN AuthPkg.Login( :userid, :pwd, :currole ); :curuser := :userid; pl( 'Logged in with role ' || :currole ); END; Login( :userid, :pwd ) SELECT empno, ename, sal FROM Emps WHERE empno = :curuser OR mgr = :curuser ShowSals Using middle-tier data whenever possible (for efficiency). Use data-tier session data when necessary (e.g. for views)

38 © Ellis Cohen Multi-User & Virtual Connections

39 © Ellis Cohen Per-User DB Connection EmpDB Middle-Tier :curuser 7782 App User 7782 Middle-Tier :curuser 6419 App User 6419 curuser 7782 curuser 6419

40 © Ellis Cohen User Sessions & DB Connections In real systems Does the middle tier maintain a separate connection to the DB for each separate application user session?

41 © Ellis Cohen Database Connections Database connections are expensive Web/App servers typically use a small pool of connections, which are used for requests. Database Server App Server Connections

42 © Ellis Cohen Virtual Connections Some databases (e.g. Oracle) support virtual connections There are still only a small # of "physical" connections between the Web/App server and the database It's possible to code as if there were a separate connection for each application user Separate temporary tables and package variable instances are created for each virtual connection

43 © Ellis Cohen Shared Multi-User Connections

44 © Ellis Cohen Using Shared Connections If –a middle tier server uses connection pooling –virtual connections are not used then –it is not possible to associate a single user id with a connection The middle-tier server –gets requests from different application users –ships them over a shared connection to the database server –Although this requires each request to be a separate transaction

45 © Ellis Cohen Switching Users The middle tier processes requests on behalf of the various users. Suppose that :requser is the identity of the user whose request is being processed. Before executing the operation code to implement the request, the middle tier must switch the current user (for that connection) to be :requser If :curuser is maintained in the middle tier, the middle tier executes :curuser := :requser If curuser is mantained in AuthPkg, the middle tier sets the curuser package variable to hold the identity of :requser by calling AuthPkg.SwitchUser( :requser )

46 © Ellis Cohen AuthPkg with User Switching CREATE PACKAGE BODY AuthPkg AS curuser int; … PROCEDURE Login( usr int, pwd varchar, theRole OUT char ) IS BEGIN SELECT role INTO theRole FROM AuthUsers WHERE userid = usr AND passwd = pwd; curuser := usr; END; PROCEDURE Logout IS BEGIN curuser := NULL; END; PROCEDURE SwitchUser( requsr int ) IS curuser := requsr; … END AuthPkg;

47 © Ellis Cohen ShowSals w User Switching AuthPkg.SwitchUser( :requser ) SELECT ename, sal FROM Emps WHERE empno = AuthPkg.GetUser OR mgr = AuthPkg.GetUser ShowSals

48 © Ellis Cohen Adding Security to Multi-User Connections

49 © Ellis Cohen Adding Security Requests should only be able to be made on behalf of users who have logged in and not logged out. If we can ensure this, it can help protect against –Application Server Errors –Hackers who might tap into the application server or the database connection

50 © Ellis Cohen AuthPkg Body CREATE TABLE CurUsers( userid int primary key ); CREATE PACKAGE BODY AuthPkg AS curuser int; PROCEDURE Login( usr int, pwd varchar, theRole OUT char ) IS BEGIN SELECT role INTO theRole FROM AuthUsers WHERE userid = usr AND passwd = pwd; curuser := usr; INSERT INTO CurUsers VALUES( usr ); END; PROCEDURE Logout IS BEGIN DELETE FROM CurUsers WHERE userid = curuser; curuser := NULL; END; PROCEDURE SwitchUser( requsr int ) IS SELECT userid INTO curuser FROM CurUsers WHERE userid = requsr; … END AuthPkg; Checks that user is actually logged in This version of the code ensures that a user can only have one session. Why? How could you allow multiple sessions per user?

51 © Ellis Cohen User Assignment The middle tier could assign a request from any user to any connection Suppose when a user logged in, the middle tier assigned that user to a specific connection, and then directs all requests by that user to the same connection. Then, a request to SwitchUser should only work if it was on the same connection on which the user logged in. Change AuthPkg accordingly

52 © Ellis Cohen CREATE GLOBAL TEMPORARY TABLE CurUsers( userid int primary key ) ON COMMIT PRESERVE ROWS; CREATE PACKAGE BODY AuthPkg AS curuser int; … PROCEDURE Login( usr int, pwd varchar, theRole OUT char ) IS BEGIN SELECT role INTO theRole FROM AuthUsers WHERE userid = usr AND passwd = pwd; curuser := usr; INSERT INTO CurUsers VALUES( usr ); END; PROCEDURE Logout IS BEGIN DELETE FROM CurUsers WHERE userid = curuser; curuser := NULL; END; PROCEDURE SwitchUser( requsr int ) IS SELECT userid INTO curuser FROM CurUsers WHERE userid = requsr; … END AuthPkg; AuthPkg with User Assignment (1) Checks that the user is actually logged in on that connection Maintains separate table for each connection This depends upon trusting that the middle tier will not login the same user on multiple connections

53 © Ellis Cohen CREATE TABLE CurUsers( userid int primary key, sessid int ); CREATE PACKAGE BODY AuthPkg AS curuser int; … PROCEDURE Login( usr int, pwd varchar, theRole OUT char ) IS BEGIN INSERT INTO CurUsers VALUES( usr, SYS_CONTEXT( 'USERENV', 'SESSIONID') ); SELECT role INTO theRole FROM AuthUsers WHERE userid = usr AND passwd= pwd; curusr := usr; END; PROCEDURE Logout IS BEGIN DELETE FROM CurUsers WHERE userid = curuser; curuser := NULL; END; PROCEDURE SwitchUser( requsr int ) IS SELECT userid INTO curuser FROM CurUsers WHERE userid = requsr AND sessid = SYS_CONTEXT( 'USERENV', 'SESSIONID'); … END AuthPkg; AuthPkg with User Assignment (2) Remembers the connection to which the Login request was sent. Raises exception if user logged in more than once Checks that the request is in the same connection where the user was logged in