Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Database Design: DBS CB, 2 nd Edition SQL in a Server Environment: CLI & JDBC & Security Ch. 9.5 + Ch. 9.6 – Ch 10.1.

Similar presentations


Presentation on theme: "1 Database Design: DBS CB, 2 nd Edition SQL in a Server Environment: CLI & JDBC & Security Ch. 9.5 + Ch. 9.6 – Ch 10.1."— Presentation transcript:

1 1 Database Design: DBS CB, 2 nd Edition SQL in a Server Environment: CLI & JDBC & Security Ch. 9.5 + Ch. 9.6 – Ch 10.1

2 2 An Aside: SQL Injection SQL queries are often constructed by programs These queries may take constants from user input Careless code can allow rather unexpected queries to be constructed and executed

3 3 Example: SQL Injection Relation Accounts(name, passwd, acct) Web interface: get name and password from user, store in strings n and p, issue query, display account number. SELECT acct FROM Accounts WHERE name = :n AND passwd = :p

4 4 User (Who Is Not Bill Gates) Types Password: Your account number is 1234-567 gates’ -- who cares? Name: Comment in Oracle

5 5 The Query Executed All treated as a comment SELECT acct FROM Accounts WHERE name = ’gates’ --’ AND passwd = ’who cares?’

6 6 Host/SQL Interfaces Via Libraries The third approach to connecting databases to conventional languages is to use library calls: 1. C + CLI 2. Java + JDBC 3. PHP + PEAR/DB

7 7 Three-Tier Architecture A common environment for using a database has three tiers of processors: 1. Web servers --- talk to the user 2. Application servers --- execute the business logic 3. Database servers --- get what the app servers need from the database

8 8 Example: Amazon Database holds the information about products, customers, etc. Business logic includes things like “what do I do after someone clicks ‘checkout’?”  Answer: Show the “how will you pay for this?” screen

9 9 Environments, Connections, Queries The database is, in many DB-access languages, an environment Database servers maintain some number of connections, so app servers can ask queries or perform modifications The app server issues statements : queries and modifications, usually

10 10 Diagram to Remember Environment Connection Statement

11 11 SQL/CLI Instead of using a preprocessor (as in embedded SQL), we can use a library of functions:  The library for C is called SQL/CLI = “Call- Level Interface”  Embedded SQL’s preprocessor will translate the EXEC SQL … statements into CLI or similar calls, anyway

12 12 Data Structures C connects to the database by structs of the following types: 1. Environments: represent the DBMS installation 2. Connections: logins to the database 3. Statements: SQL statements to be passed to a connection 4. Descriptions: records about tuples from a query, or parameters of a statement

13 13 Handles Function SQLAllocHandle(T,I,O) is used to create these structs, which are called environment, connection, and statement handles:  T = type, e.g., SQL_HANDLE_STMT  I = input handle = struct at next higher level (statement < connection < environment)  O = (address of) output handle

14 14 Example: SQLAllocHandle SQLAllocHandle(SQL_HANDLE_STMT, myCon, &myStat); myCon is a previously created connection handle myStat is the name of the statement handle that will be created

15 15 Preparing and Executing SQLPrepare(H, S, L) causes the string S, of length L, to be interpreted as a SQL statement and optimized; the executable statement is placed in statement handle H SQLExecute(H) causes the SQL statement represented by statement handle H to be executed.

16 16 Example: Prepare and Execute This constant says the second argument is a “null-terminated string”; i.e., figure out the length by counting characters. SQLPrepare(myStat, ”SELECT beer, price FROM Sells WHERE bar = ’Joe’’s Bar’”, SQL_NTS); SQLExecute(myStat);

17 17 Direct Execution If we shall execute a statement S only once, we can combine PREPARE and EXECUTE with: SQLExecuteDirect(H,S,L);  As before, H is a statement handle and L is the length of string S.

18 18 Fetching Tuples When the SQL statement executed is a query, we need to fetch the tuples of the result:  A cursor is implied by the fact we executed a query; the cursor need not be declared SQLFetch(H) gets the next tuple from the result of the statement with handle H

19 19 Accessing Query Results When we fetch a tuple, we need to put the components somewhere Each component is bound to a variable by the function SQLBindCol:  This function has 6 arguments, of which we shall show only 1, 2, and 4: 1 = handle of the query statement 2 = column number 4 = address of the variable

20 20 Example: Binding Suppose we have just done SQLExecute(myStat), where myStat is the handle for query SELECT beer, price FROM Sells WHERE bar = ’Joe’’s Bar’ Bind the result to theBeer and thePrice: SQLBindCol(myStat, 1,, &theBeer,, ); SQLBindCol(myStat, 2,, &thePrice,, );

21 21 Example: Fetching Now, we can fetch all the tuples of the answer by: while ( SQLFetch(myStat) != SQL_NO_DATA) { /* do something with theBeer and thePrice */ } CLI macro representing SQLSTATE = 02000 = “failed to find a tuple.”

22 22 JDBC Java Database Connectivity (JDBC) is a library similar to SQL/CLI, but with Java as the host language Like CLI, but with a few differences for us to cover

23 23 Making a Connection The JDBC classes The driver for mySql; others exist URL of the database your name, and password go here. Loaded by forName import java.sql.*; Class.forName(com.mysql.jdbc.Driver); Connection myCon = DriverManager.getConnection(…);

24 24 Statements JDBC provides two classes: 1. Statement = an object that can accept a string that is a SQL statement and can execute such a string 1. PreparedStatement = an object that has an associated SQL statement ready to execute

25 25 Creating Statements createStatement with no argument returns a Statement; with one argument it returns a PreparedStatement. The Connection class has methods to create Statements and PreparedStatements Statement stat1 = myCon.createStatement(); PreparedStatement stat2 = myCon.createStatement( ”SELECT beer, price FROM Sells ” + ”WHERE bar = ’Joe’ ’s Bar’ ” );

26 26 Executing SQL Statements JDBC distinguishes queries from modifications, which it calls “updates” Statement and PreparedStatement each have methods executeQuery and executeUpdate:  For Statements: one argument: the query or modification to be executed  For PreparedStatements: no argument

27 27 Example: Update stat1 is a Statement. We can use it to insert a tuple as: stat1.executeUpdate( ”INSERT INTO Sells ” + ”VALUES(’Brass Rail’,’Bud’,3.00)” );

28 28 Example: Query stat2 is a PreparedStatement holding the query ”SELECT beer, price FROM Sells WHERE bar = ’Joe’’s Bar’ ” executeQuery returns an object of class ResultSet – we’ll examine it later The query: ResultSet menu = stat2.executeQuery();

29 29 Accessing the ResultSet An object of type ResultSet is something like a cursor Method next() advances the “cursor” to the next tuple:  The first time next() is applied, it gets the first tuple  If there are no more tuples, next() returns the value false

30 30 Accessing Components of Tuples When a ResultSet is referring to a tuple, we can get the components of that tuple by applying certain methods to the ResultSet Method getX (i ), where X is some type, and i is the component number, returns the value of that component:  The value must have type X

31 31 Example: Accessing Components Menu = ResultSet for query “SELECT beer, price FROM Sells WHERE bar = ’Joe’ ’s Bar’ ” Access beer and price from each tuple by: while ( menu.next() ) { theBeer = Menu.getString(1); thePrice = Menu.getFloat(2); /*something with theBeer and thePrice*/ }

32 32 Database Design: DBS CB, 2 nd Edition SQL in a Server Environment: Security and User Authorization in SQL Ch 10.1

33 33 Authorization A file system identifies certain privileges on the objects (files) it manages:  Typically: read, write, execute A file system identifies certain participants to whom privileges may be granted.  Typically: the owner, a group, all users

34 34 Privileges – (1) SQL identifies a more detailed set of privileges on objects (relations) than the typical file system Nine privileges in all, some of which can be restricted to one column of one relation

35 35 Privileges – (2) Some important privileges on a relation: 1. SELECT = right to query the relation 2. INSERT = right to insert tuples w May apply to only one attribute 3. DELETE = right to delete tuples 4. UPDATE = right to update tuples w May apply to only one attribute

36 36 Example: Privileges beers that do not appear in Beers. We add them to Beers with a NULL manufacturer. For the statement below: INSERT INTO Beers(name) SELECT beer FROM Sells WHERE NOT EXISTS (SELECT * FROM Beers WHERE name = beer); We require privileges SELECT on Sells and Beers, and INSERT on Beers or Beers.name

37 37 Database Objects The objects on which privileges exist include stored tables and views Other privileges are the right to create objects of a type, e.g., triggers Views form an important tool for access control

38 38 Example: Views as Access Control We might not want to give the SELECT privilege on Emps(name, addr, salary) But it is safer to give SELECT on: CREATE VIEW SafeEmps AS SELECT name, addr FROM Emps; Queries on SafeEmps do not require SELECT privilege on Emps, just on SafeEmps

39 39 Authorization ID’s A user is referred to by authorization ID, typically their login name There is an authorization ID PUBLIC:  Granting a privilege to PUBLIC makes it available to any authorization ID

40 40 Granting Privileges You have all possible privileges on the objects, such as relations, that you create You may grant privileges to other users (authorization ID’s), including PUBLIC You may also grant privileges WITH GRANT OPTION, which lets the grantee also grant this privilege

41 41 The GRANT Statement To grant privileges, say: GRANT ON TO ; If you want the recipient(s) to be able to pass the privilege(s) to others add: WITH GRANT OPTION

42 42 Example: GRANT Suppose you are the owner of Sells. You may say: GRANT SELECT, UPDATE(price) ON Sells TO sally; Now Sally has the right to issue any query on Sells and can update the price component only

43 43 Example: Grant Option Suppose we also grant: GRANT UPDATE ON Sells TO sally WITH GRANT OPTION; Now, Sally not only can update any attribute of Sells, but can grant to others the privilege UPDATE ON Sells:  Also, she can grant more specific privileges like UPDATE(price)ON Sells

44 44 Revoking Privileges REVOKE ON FROM ; Your grant of these privileges can no longer be used by these users to justify their use of the privilege:  But they may still have the privilege because they obtained it independently from elsewhere

45 45 REVOKE Options We must append to the REVOKE statement either: 1. CASCADE: Now, any grants made by a revokee are also not in force, no matter how far the privilege was passed 2. RESTRICT: If the privilege has been passed to others, the REVOKE fails as a warning that something else must be done to “chase the privilege down”

46 46 Grant Diagrams Nodes = user/privilege/grant option? / is owner?  UPDATE ON R, UPDATE(a) on R, and UPDATE(b) ON R live in different nodes  SELECT ON R and SELECT ON R WITH GRANT OPTION live in different nodes Edge X  Y means that node X was used to grant Y

47 47 Notation for Nodes Use AP for the node representing authorization ID A having privilege P:  P * = privilege P with grant option  P ** = the source of the privilege P I.e., A is the owner of the object on which P is a privilege Note ** implies grant option

48 48 Manipulating Edges – (1) When A grants P to B, We draw an edge from AP * or AP ** to BP  Or to BP * if the grant is with grant option If A grants a subprivilege Q of P [say UPDATE(a) on R when P is UPDATE ON R] then the edge goes to BQ or BQ *, instead

49 49 Manipulating Edges – (2) Fundamental rule: User C has privilege Q as long as there is a path from XP ** to CQ, CQ *, or CQ **, and P is a superprivilege of Q:  Remember that P could be Q, and X could be C

50 50 Manipulating Edges – (3) If A revokes P from B with the CASCADE option, delete the edge from AP to BP But if A uses RESTRICT instead, and there is an edge from BP to anywhere, then reject the revocation and make no change to the graph

51 51 Manipulating Edges – (4) Having revised the edges, we must check that each node has a path from some ** node, representing ownership Any node with no such path represents a revoked privilege and is deleted from the diagram

52 52 Example: Grant Diagram AP** A owns the object on which P is a privilege BP* A: GRANT P TO B WITH GRANT OPTION CP* B: GRANT P TO C WITH GRANT OPTION CP A: GRANT P TO C

53 53 Example: Grant Diagram AP**BP*CP* CP A executes REVOKE P FROM B CASCADE; However, C still has P without grant option because of the direct grant. Not only does B lose P*, but C loses P*. Delete BP* and CP* Even had C passed P to B, both nodes are still cut off

54 54 END


Download ppt "1 Database Design: DBS CB, 2 nd Edition SQL in a Server Environment: CLI & JDBC & Security Ch. 9.5 + Ch. 9.6 – Ch 10.1."

Similar presentations


Ads by Google