Presentation is loading. Please wait.

Presentation is loading. Please wait.

CPSC-310 Database Systems

Similar presentations


Presentation on theme: "CPSC-310 Database Systems"— Presentation transcript:

1 CPSC-310 Database Systems
Professor Jianer Chen Room 315C HRBB Lecture #22

2 Persistent Stored Modules (PSM)
A recent SQL standard Mechanism for user to store in the DB schema functions and procedures that can be used in SQL statements The functions and procedures are written in a simple general-purpose language Includes if, loop, variable declaration, as well as SQL queries and updates

3 Basic PSM Form CREATE PROCEDURE <name> (<parameter list>)
<optional local declarations> <body>; CREATE FUNCTION <name> (<parameter list>) RETURNS <type> PSM uses mode-name-type triples for parameters, where the mode can be: IN = procedure uses value, does not change value. OUT = procedure changes, does not use. INOUT = both.

4 CALL JoeMenu(’Moosedrool’, 5.00);
Invoking Procedures Use SQL/PSM statement CALL, with the name of the procedure and arguments. Example: CALL JoeMenu(’Moosedrool’, 5.00); Functions used in SQL expressions wherever a value of their return type is appropriate.

5 Types of PSM statements
RETURN <expression> sets the return value of a function. DECLARE <name> <type> is used to declare local variables. BEGIN END for groups of statements. * Separate statements by semicolons. Assignment statements: SET <variable> = <expression>; Example: SET b = ’Bud’; Statement labels: give a statement a label by prefixing a name and a colon.

6 IF Statements Simplest form: IF <condition> THEN
END IF; Add ELSE <statements> if desired: IF THEN ELSE END IF; Add additional cases by ELSEIF <statements>: IF … THEN … ELSEIF … ELSEIF … ELSE … END IF;

7 Loops

8 LOOP <statements> END LOOP;
Basic form: LOOP <statements> END LOOP;

9 LOOP <statements> END LOOP;
Basic form: LOOP <statements> END LOOP; Exit from a loop by: LEAVE <loop name>

10 LOOP <statements> END LOOP;
Basic form: LOOP <statements> END LOOP; Exit from a loop by: LEAVE <loop name> <loop name> is associated with a loop by prepending the name and a colon to LOOP.

11 LOOP <statements> END LOOP;
Basic form: LOOP <statements> END LOOP; Exit from a loop by: LEAVE <loop name> <loop name> is associated with a loop by prepending the name and a colon to LOOP. Example: loop1: LOOP LEAVE loop1; END LOOP;

12 LOOP <statements> END LOOP;
Basic form: LOOP <statements> END LOOP; Exit from a loop by: LEAVE <loop name> <loop name> is associated with a loop by prepending the name and a colon to LOOP. Example: loop1: LOOP LEAVE loop1; END LOOP; Other loops

13 LOOP <statements> END LOOP;
Basic form: LOOP <statements> END LOOP; Exit from a loop by: LEAVE <loop name> <loop name> is associated with a loop by prepending the name and a colon to LOOP. Example: loop1: LOOP LEAVE loop1; END LOOP; Other loops WHILE <condition> DO <statements> END WHILE;

14 LOOP <statements> END LOOP;
Basic form: LOOP <statements> END LOOP; Exit from a loop by: LEAVE <loop name> <loop name> is associated with a loop by prepending the name and a colon to LOOP. Example: loop1: LOOP LEAVE loop1; END LOOP; Other loops WHILE <condition> DO <statements> END WHILE; REPEAT <statements> UNTIL <condition> END REPEAT;

15 Queries General SELECT-FROM-WHERE queries are not permitted in PSM.

16 Queries General SELECT-FROM-WHERE queries are not permitted in PSM.
Three ways to get the effect of queries:

17 Queries General SELECT-FROM-WHERE queries are not permitted in PSM. Three ways to get the effect of queries: * Queries producing one value can be the expression in an assignment.

18 Queries General SELECT-FROM-WHERE queries are not permitted in PSM. Three ways to get the effect of queries: * Queries producing one value can be the expression in an assignment. Example: From relation Sells(bar, beer, price), we can get the price Joe charges for Bud by (p is a local variable):

19 Queries General SELECT-FROM-WHERE queries are not permitted in PSM. Three ways to get the effect of queries: * Queries producing one value can be the expression in an assignment. Example: From relation Sells(bar, beer, price), we can get the price Joe charges for Bud by (p is a local variable): SET p = (SELECT price FROM Sells WHERE bar = ’Joe’’s Bar’ AND beer = ’Bud’);

20 Queries General SELECT-FROM-WHERE queries are not permitted in PSM. Three ways to get the effect of queries: * Queries producing one value can be the expression in an assignment. * Single-row SELECT INTO.

21 Queries General SELECT-FROM-WHERE queries are not permitted in PSM. Three ways to get the effect of queries: * Queries producing one value can be the expression in an assignment. * Single-row SELECT INTO. Example. For a query guaranteeing to return one tuple, we can place INTO <variable> after SELECT clause:

22 Queries General SELECT-FROM-WHERE queries are not permitted in PSM. Three ways to get the effect of queries: * Queries producing one value can be the expression in an assignment. * Single-row SELECT INTO. Example. For a query guaranteeing to return one tuple, we can place INTO <variable> after SELECT clause: SELECT price INTO p FROM Sells WHERE bar = ’Joe’’s Bar’ AND beer = ’Bud’;

23 Queries General SELECT-FROM-WHERE queries are not permitted in PSM. Three ways to get the effect of queries: * Queries producing one value can be the expression in an assignment. * Single-row SELECT INTO. Example. For a query guaranteeing to return one tuple, we can place INTO <variable> after SELECT clause: SELECT price INTO p FROM Sells WHERE bar = ’Joe’’s Bar’ AND beer = ’Bud’;

24 Queries General SELECT-FROM-WHERE queries are not permitted in PSM. Three ways to get the effect of queries: * Queries producing one value can be the expression in an assignment. * Single-row SELECT INTO. * Cursors.

25 Cursors A cursor is a tuple-variable that ranges over all tuples in the result of a query.

26 DECLARE c CURSOR FOR <query>;
Cursors A cursor is a tuple-variable that ranges over all tuples in the result of a query. Declare a cursor c by: DECLARE c CURSOR FOR <query>;

27 DECLARE c CURSOR FOR <query>;
Cursors A cursor is a tuple-variable that ranges over all tuples in the result of a query. Declare a cursor c by: DECLARE c CURSOR FOR <query>; To use cursor c, issue command: OPEN c;

28 DECLARE c CURSOR FOR <query>;
Cursors A cursor is a tuple-variable that ranges over all tuples in the result of a query. Declare a cursor c by: DECLARE c CURSOR FOR <query>; To use cursor c, issue command: OPEN c; Then the query of c is evaluated, and c is set to point to the first tuple of the result.

29 DECLARE c CURSOR FOR <query>;
Cursors A cursor is a tuple-variable that ranges over all tuples in the result of a query. Declare a cursor c by: DECLARE c CURSOR FOR <query>; To use cursor c, issue command: OPEN c; Then the query of c is evaluated, and c is set to point to the first tuple of the result. When finished with c, issue command: CLOSE c;

30 Fetching Tuples From a Cursor

31 Fetching Tuples From a Cursor
To get the next tuple from a cursor c, issue command: FETCH FROM c INTO x1, x2,…, xn;

32 Fetching Tuples From a Cursor
To get the next tuple from a cursor c, issue command: FETCH FROM c INTO x1, x2,…, xn; The x’s are a list of variables, one for each component of the tuple referred to by c.

33 Fetching Tuples From a Cursor
To get the next tuple from a cursor c, issue command: FETCH FROM c INTO x1, x2,…, xn; The x’s are a list of variables, one for each component of the tuple referred to by c. The cursor c is moved automatically to the next tuple.

34 Cursor Loops The usual way to use a cursor is to create a loop with a FETCH statement, and do something with each tuple fetched.

35 Cursor Loops The usual way to use a cursor is to create a loop with a FETCH statement, and do something with each tuple fetched. A tricky point is how we get out of the loop when the cursor has no more tuples to deliver

36 Cursor Loops The usual way to use a cursor is to create a loop with a FETCH statement, and do something with each tuple fetched. A tricky point is how we get out of the loop when the cursor has no more tuples to deliver Each SQL operation returns a status, which is a 5-digit number.

37 Cursor Loops The usual way to use a cursor is to create a loop with a FETCH statement, and do something with each tuple fetched. A tricky point is how we get out of the loop when the cursor has no more tuples to deliver Each SQL operation returns a status, which is a 5-digit number. For example, = “Everything OK,” and = “Failed to find a tuple.”

38 Cursor Loops The usual way to use a cursor is to create a loop with a FETCH statement, and do something with each tuple fetched. A tricky point is how we get out of the loop when the cursor has no more tuples to deliver Each SQL operation returns a status, which is a 5-digit number. For example, = “Everything OK,” and = “Failed to find a tuple.” In PSM, we can get the value of the status in a variable called SQLSTATE.

39 Cursor Loops We may declare a condition, which is a boolean variable that is true if and only if SQLSTATE has a particular value.

40 Cursor Loops We may declare a condition, which is a boolean variable that is true if and only if SQLSTATE has a particular value. Example: declare condition NotFound by: DECLARE NotFound CONDITION FOR SQLSTATE ’02000’;

41 Cursor Loops We may declare a condition, which is a boolean variable that is true if and only if SQLSTATE has a particular value. Example: declare condition NotFound by: DECLARE NotFound CONDITION FOR SQLSTATE ’02000’; The structure of a cursor loop is thus: cursorLoop: LOOP FETCH c INTO … ; IF NotFound THEN LEAVE cursorLoop; END IF; END LOOP;

42 Example: Cursor A procedure that examines the relation Sells(bar, beer, price), and raises by $1 the price of all beers at Joe’s Bar that are under $3.

43 Example: Cursor A procedure that examines the relation Sells(bar, beer, price), and raises by $1 the price of all beers at Joe’s Bar that are under $3. Yes, we could write this as a simple UPDATE, but the details are instructive anyway.

44 Example: Cursor CREATE PROCEDURE JoeGouge( ) DECLARE theBeer CHAR(20);
examines the relation Sells(bar, beer, price), and raises by $1 the price of all beers at Joe’s Bar that are < $3. Example: Cursor CREATE PROCEDURE JoeGouge( ) DECLARE theBeer CHAR(20); DECLARE thePrice REAL; DECLARE NotFound CONDITION FOR SQLSTATE ’02000’; DECLARE c CURSOR FOR (SELECT beer, price FROM Sells WHERE bar = ’Joe’’s Bar’); BEGIN OPEN c; menuLoop: LOOP FETCH c INTO theBeer, thePrice; IF NotFound THEN LEAVE menuLoop END IF; IF thePrice < 3.00 THEN UPDATE Sells SET price = thePrice WHERE bar = ’Joe’’s Bar’ AND beer = theBeer; END IF; END LOOP; CLOSE c; END;

45 Example: Cursor CREATE PROCEDURE JoeGouge( ) DECLARE theBeer CHAR(20);
examines the relation Sells(bar, beer, price), and raises by $1 the price of all beers at Joe’s Bar that are < $3. Example: Cursor CREATE PROCEDURE JoeGouge( ) DECLARE theBeer CHAR(20); DECLARE thePrice REAL; DECLARE NotFound CONDITION FOR SQLSTATE ’02000’; DECLARE c CURSOR FOR (SELECT beer, price FROM Sells WHERE bar = ’Joe’’s Bar’); Used to hold beer-price pairs when fetching through cursor c BEGIN OPEN c; menuLoop: LOOP FETCH c INTO theBeer, thePrice; IF NotFound THEN LEAVE menuLoop END IF; IF thePrice < 3.00 THEN UPDATE Sells SET price = thePrice WHERE bar = ’Joe’’s Bar’ AND beer = theBeer; END IF; END LOOP; CLOSE c; END;

46 Example: Cursor CREATE PROCEDURE JoeGouge( ) DECLARE theBeer CHAR(20);
examines the relation Sells(bar, beer, price), and raises by $1 the price of all beers at Joe’s Bar that are < $3. Example: Cursor CREATE PROCEDURE JoeGouge( ) DECLARE theBeer CHAR(20); DECLARE thePrice REAL; DECLARE NotFound CONDITION FOR SQLSTATE ’02000’; DECLARE c CURSOR FOR (SELECT beer, price FROM Sells WHERE bar = ’Joe’’s Bar’); Used to hold beer-price pairs when fetching through cursor c BEGIN OPEN c; menuLoop: LOOP FETCH c INTO theBeer, thePrice; IF NotFound THEN LEAVE menuLoop END IF; IF thePrice < 3.00 THEN UPDATE Sells SET price = thePrice WHERE bar = ’Joe’’s Bar’ AND beer = theBeer; END IF; END LOOP; CLOSE c; END; Returns Joe’s menu

47 Example: Cursor CREATE PROCEDURE JoeGouge( ) DECLARE theBeer CHAR(20);
examines the relation Sells(bar, beer, price), and raises by $1 the price of all beers at Joe’s Bar that are < $3. Example: Cursor CREATE PROCEDURE JoeGouge( ) DECLARE theBeer CHAR(20); DECLARE thePrice REAL; DECLARE NotFound CONDITION FOR SQLSTATE ’02000’; DECLARE c CURSOR FOR (SELECT beer, price FROM Sells WHERE bar = ’Joe’’s Bar’); Used to hold beer-price pairs when fetching through cursor c BEGIN OPEN c; menuLoop: LOOP FETCH c INTO theBeer, thePrice; IF NotFound THEN LEAVE menuLoop END IF; IF thePrice < 3.00 THEN UPDATE Sells SET price = thePrice WHERE bar = ’Joe’’s Bar’ AND beer = theBeer; END IF; END LOOP; CLOSE c; END; Check if the recent FETCH failed to get a tuple Returns Joe’s menu

48 Example: Cursor CREATE PROCEDURE JoeGouge( ) DECLARE theBeer CHAR(20);
examines the relation Sells(bar, beer, price), and raises by $1 the price of all beers at Joe’s Bar that are < $3. Example: Cursor CREATE PROCEDURE JoeGouge( ) DECLARE theBeer CHAR(20); DECLARE thePrice REAL; DECLARE NotFound CONDITION FOR SQLSTATE ’02000’; DECLARE c CURSOR FOR (SELECT beer, price FROM Sells WHERE bar = ’Joe’’s Bar’); Used to hold beer-price pairs when fetching through cursor c BEGIN OPEN c; menuLoop: LOOP FETCH c INTO theBeer, thePrice; IF NotFound THEN LEAVE menuLoop END IF; IF thePrice < 3.00 THEN UPDATE Sells SET price = thePrice WHERE bar = ’Joe’’s Bar’ AND beer = theBeer; END IF; END LOOP; CLOSE c; END; Check if the recent FETCH failed to get a tuple Returns Joe’s menu If Joe charges less than $3 for the beer, raise it’s price at Joe’s Bar by $1.

49 Combining SQL and Conventional Programming Languages
Three ways to combine: Persistent Stored Modules (PSM): Code stored in the DB schema and executed on command from a user Embed SQL statements in programs written in some conventional language Call-level interfaces (CLI) * SQL/CLI (SQL standard, for use with C * JDBC (for use with Java)

50 Combining SQL and Conventional Programming Languages
Three ways to combine: Persistent Stored Modules (PSM): Code stored in the DB schema and executed on command from a user Embed SQL statements in programs written in some conventional language Call-level interfaces (CLI) * SQL/CLI (SQL standard, for use with C * JDBC (for use with Java)

51 Embedded SQL and CLI's

52 Host-language compiler
Embedded SQL and CLI's host language + function calls (CLI) Host-language compiler SQL library object-code program

53 Host-language compiler
Embedded SQL and CLI's host language + function calls (CLI) host language + function calls (CLI) Host-language compiler SQL library object-code program

54 Host-language compiler
Embedded SQL and CLI's host language + function calls (CLI) host language + function calls (CLI) Host-language compiler SQL library object-code program

55 Host-language compiler
Embedded SQL and CLI's host language + embedded SQL host language + function calls (CLI) host language + function calls (CLI) Host-language compiler SQL library object-code program

56 Host-language compiler
Embedded SQL and CLI's host language + embedded SQL preprocessor host language + function calls (CLI) host language + function calls (CLI) Host-language compiler SQL library object-code program

57 Host-language compiler
Embedded SQL and CLI's host language + embedded SQL preprocessor host language + function calls (CLI) host language + function calls (CLI) Host-language compiler SQL library object-code program

58 Host-language compiler
Embedded SQL and CLI's host language + embedded SQL host language + Embedded SQL preprocessor host language + function calls (CLI) host language + function calls (CLI) Host-language compiler SQL library object-code program

59 Connecting SQL to a Host Language
Embedded SQL is a standard for combining SQL with seven languages. CLI (Call-Level Interface) is a different approach to connecting C to an SQL database. JDBC (Java Database Connectivity) is a way to connect Java with an SQL database (analogous to CLI).

60 Embedded SQL

61 Embedded SQL Key idea: Use a preprocessor to turn SQL statements into procedure calls that fit with the host-language code surrounding.

62 Embedded SQL Key idea: Use a preprocessor to turn SQL statements into procedure calls that fit with the host-language code surrounding. All embedded SQL statements begin with EXEC SQL, which can be identified easily.

63 Embedded SQL Key idea: Use a preprocessor to turn SQL statements into procedure calls that fit with the host-language code surrounding. All embedded SQL statements begin with EXEC SQL, which can be identified easily. Issues for embedded SQL (Section 9.3)

64 Embedded SQL Key idea: Use a preprocessor to turn SQL statements into procedure calls that fit with the host-language code surrounding. All embedded SQL statements begin with EXEC SQL, which can be identified easily. Issues for embedded SQL (Section 8.3) how to transfer data between host language and SQL -- use shared variables

65 Embedded SQL Key idea: Use a preprocessor to turn SQL statements into procedure calls that fit with the host-language code surrounding. All embedded SQL statements begin with EXEC SQL, which can be identified easily. Issues for embedded SQL (Section 8.3) how to transfer data between host language and SQL -- use shared variables how to handle multiple tuples returned by a query -- cursor

66 Embedded SQL Key idea: Use a preprocessor to turn SQL statements into procedure calls that fit with the host-language code surrounding. All embedded SQL statements begin with EXEC SQL, which can be identified easily. Issues for embedded SQL (Section 8.3) how to transfer data between host language and SQL -- use shared variables how to handle multiple tuples returned by a query -- cursor how to execute SQL statements that are not known at compile time -- dynamic SQL

67 Example: Embedded SQL EXEC SQL BEGIN DECLARE SECTION;
char theBar[21], theBeer[21]; float thePrice; EXEC SQL END DECLARE SECTION; /* obtain values for theBar and theBeer */ EXEC SQL SELECT price INTO :thePrice FROM Sells WHERE bar = :theBar AND beer = :theBeer; /* do something with thePrice */

68 Example: Embedded SQL EXEC SQL BEGIN DECLARE SECTION;
char theBar[21], theBeer[21]; float thePrice; EXEC SQL END DECLARE SECTION; /* obtain values for theBar and theBeer */ EXEC SQL SELECT price INTO :thePrice FROM Sells WHERE bar = :theBar AND beer = :theBeer; /* do something with thePrice */ embedded SQL statement

69 Example: Embedded SQL EXEC SQL BEGIN DECLARE SECTION;
char theBar[21], theBeer[21]; float thePrice; EXEC SQL END DECLARE SECTION; /* obtain values for theBar and theBeer */ EXEC SQL SELECT price INTO :thePrice FROM Sells WHERE bar = :theBar AND beer = :theBeer; /* do something with thePrice */ declaration of shared variables embedded SQL statement

70 use of shared variables in embedded SQL statements
Example: Embedded SQL EXEC SQL BEGIN DECLARE SECTION; char theBar[21], theBeer[21]; float thePrice; EXEC SQL END DECLARE SECTION; /* obtain values for theBar and theBeer */ EXEC SQL SELECT price INTO :thePrice FROM Sells WHERE bar = :theBar AND beer = :theBeer; /* do something with thePrice */ declaration of shared variables embedded SQL statement use of shared variables in embedded SQL statements

71 Call-Level-Interface: SQL/CLI

72 Call-Level-Interface: SQL/CLI
SQL/CLI uses a library of functions (sqlcli.h) and calls them as part of an ordinary C program.

73 Call-Level-Interface: SQL/CLI
SQL/CLI uses a library of functions (sqlcli.h) and calls them as part of an ordinary C program. C connects to the database by structs of the following types:

74 Call-Level-Interface: SQL/CLI
SQL/CLI uses a library of functions (sqlcli.h) and calls them as part of an ordinary C program. C connects to the database by structs of the following types: * Environments: represent the DBMS installation. * Connections: logins to the database. * Statements: SQL statements to be passed to a connection. * Descriptions: records about tuples from a query or parameters of a statement.

75 Environment/Connection/Statements
Function SQLAllocHandle(T,I,O) is used to create these structs, which are called environment/connection/statement handles.

76 Environment/Connection/Statements
Function SQLAllocHandle(T,I,O) is used to create these structs, which are called environment/connection/statement handles. * T = type, e.g., SQL_HANDLE_STMT (DBC, ENV). * I = input handle = struct at next higher level * O = the created output handle.

77 Environment/Connection/Statements
Function SQLAllocHandle(T,I,O) is used to create these structs, which are called environment/connection/statement handles. * T = type, e.g., SQL_HANDLE_STMT (DBC, ENV). * I = input handle = struct at next higher level * O = the created output handle. Example. SQLAllocHandle(SQL_HANDLE_STMT, myCon, &myStat);

78 Environment/Connection/Statements
Function SQLAllocHandle(T,I,O) is used to create these structs, which are called environment/connection/statement handles. * T = type, e.g., SQL_HANDLE_STMT (DBC, ENV). * I = input handle = struct at next higher level * O = the created output handle. Example. SQLAllocHandle(SQL_HANDLE_STMT, myCon, &myStat); * myCon is a previously created connection handle.

79 Environment/Connection/Statements
Function SQLAllocHandle(T,I,O) is used to create these structs, which are called environment/connection/statement handles. * T = type, e.g., SQL_HANDLE_STMT (DBC, ENV). * I = input handle = struct at next higher level * O = the created output handle. Example. 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.

80 Preparing and Executing

81 Preparing and Executing
SQLPrepare(H, S, L) causes the string S, of length L, to be interpreted as an SQL statement and optimized; the executable statement is placed in statement handle H.

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

83 Preparing and Executing
SQLPrepare(H, S, L) causes the string S, of length L, to be interpreted as an SQL statement and optimized; the executable statement is placed in statement handle H. SQLExecute(H) causes the SQL statement given by statement handle H to be executed. Example. SQLPrepare(myStat, ”SELECT beer, price FROM Sells WHERE bar = ’Joe’’s Bar’ ”, SQL_NTS); SQLExecute(myStat);

84 Preparing and Executing
SQLPrepare(H, S, L) causes the string S, of length L, to be interpreted as an SQL statement and optimized; the executable statement is placed in statement handle H. SQLExecute(H) causes the SQL statement given by statement handle H to be executed. Example. SQLPrepare(myStat, ”SELECT beer, price FROM Sells WHERE bar = ’Joe’’s Bar’ ”, SQL_NTS); SQLExecute(myStat); This constant says the second argument is a “null-terminated string”; i.e., figure out the length by counting characters.

85 Preparing and Executing
SQLPrepare(H, S, L) causes the string S, of length L, to be interpreted as an SQL statement and optimized; the executable statement is placed in statement handle H. SQLExecute(H) causes the SQL statement given by statement handle H to be executed. If we will execute a statement S only once, we can combine PREPARE and EXECUTE by calling: SQLExecuteDirect(H, S, L);


Download ppt "CPSC-310 Database Systems"

Similar presentations


Ads by Google