Download presentation
Presentation is loading. Please wait.
1
Database Systems Transaction management PL/SQL
Gergely Lukács Pázmány Péter Catholic University Faculty of Information Technology Budapest, Hungary
2
Overview Transaction management Database utilities
Motivation ACID properties Phenomena Lost updates Dirty reads, Non-repeatable reads, Phantom reads Isolation level Practical consequences Database utilities Procedural language PL/SQL
3
Transaction Management
3
4
Database Systems, Introduction
5
Transaction Concept A transaction is a unit of program execution that accesses and possibly creates/deletes/updates various data items. A transaction must see a consistent database. During transaction execution the database may be inconsistent. When the transaction is committed, the database must be consistent. Two main issues to deal with: Failures of various kinds, such as hardware failures and system crashes Concurrent execution of multiple transactions
6
ACID ACID (atomicity, consistency, isolation, durability) is a set of properties that guarantee database transactions are processed reliably. Atomicity. All or nothing. Either all operations of the transaction are properly reflected in the database or none are. Consistency. Any transaction will take the db from one consistent state to another, with no broken constraints Isolation. Although multiple transactions may execute concurrently, each transaction must be unaware of other concurrently executing transactions. Intermediate transaction results must be hidden from other concurrently executed transactions. That is, for every pair of transactions Ti and Tj, it appears to Ti that either Tj, finished execution before Ti started, or Tj started execution after Ti finished. Durability. After a transaction completes successfully, the changes it has made to the database persist, even if there are system failures. Ability to recover the committed transaction updates against any kind of system failure (transaction log)
7
Example of Fund Transfer
Transaction to transfer $50 from account A to account B: 1. read(A) 2. A := A – 50 3. write(A) 4. read(B) 5. B := B + 50 6. write(B) Consistency requirement – the sum of A and B is unchanged by the execution of the transaction. Atomicity requirement — if the transaction fails after step 3 and before step 6, the system should ensure that its updates are not reflected in the database, else an inconsistency will result.
8
Example of Fund Transfer (Cont.)
Durability requirement — once the user has been notified that the transaction has completed (i.e., the transfer of the $50 has taken place), the updates to the database by the transaction must persist despite failures. Isolation requirement — if between steps 3 and 6, another transaction is allowed to access the partially updated database, it will see an inconsistent database (the sum A + B will be less than it should be). Can be ensured trivially by running transactions serially, that is one after the other. However, executing multiple transactions concurrently has performance advantages.
9
Concurrency control Transactions executed serially:
no transaction concurrency, perfect isolation but: low performance, the dbms is slow! Concurrent transactions with interleaving operations in an uncontrolled manner: Undesirable results may occur Concurrent transactions in a controlled manner: increased performance, known phenomena allowed
10
Lost update Application in T1 transfers 300 EUR-t from bank account A to B Application in T2 calculates interest rate for bank account A Update of T2 is overwritten by T1, therefore, the update is lost!
11
Dirty reads (reading tentative data)
Commit, Abort…. Application 2 in T2 calculates interest (using interest rate 3%) Basis is an intermediate value, written by Application 1 in T1 T1 is aborted…. From ISO/ANSI: One process (P1) modifies a row, and another process (P2) then reads that row before it is committed by P1. If P1 then rolls back the change, P2 will have read a row that was never committed and that may thus be considered to have never existed. 1:40
12
Non-repeatable reads (reading changed data)
Application 1 reads a value several times – due to the other application, it reads different values at diifferent times! From ISO/ANSI: Process P1 reads a row. Process P2 then modifies or deletes that rows and commits the change. If P1 rereads the row it receives the modified value or discovers the row has been deleted.
13
Phantom reads (reading new data)
A phantom read occurs when, in the course of a transaction, two identical queries are executed, and the collection of rows returned by the second query is different from the first. From ISO/ANSI: Process P1 reads the set of rows N that satisfy some search condition. Process P2 then executes statements that generate one or more rows that satisfy the search condition. If P1 repeats the query it obtains a different collection of rows.
14
Isolation Property that defines how/when the changes made by one operation become visible to other concurrent operations SERIALIZABLE: All transactions occur in a completely isolated fashion, as if they were executed serially REPEATABLE READ: Multiple SELECT statements issued in the same transaction will always yield the same result READ COMMITTED: A lock is acquired only on the rows currently read/updated READ UMCOMMITTED: A transaction can access uncommitted changes made by other transactions
15
Isolation levels
16
Levels of Consistency in SQL-92
Serializable — default Repeatable read — only committed records to be read, repeated reads of same record must return same value. However, a transaction may not be serializable – it may find some records inserted by a transaction but not find others. Read committed — only committed records can be read, but successive reads of record may return different (but committed) values. Read uncommitted — even uncommitted records may be read. Lower degrees of consistency useful for gathering approximate information about the database, e.g., statistics for query optimizer.
17
Transaction Definition in SQL
Data manipulation language must include a construct for specifying the set of actions that comprise a transaction. In SQL, a transaction begins implicitly. A transaction in SQL ends by: Commit work commits current transaction and begins a new one. Rollback work causes current transaction to abort. Autocommit Can turn off auto commit for a session (e.g. using API) In SQL:1999, can use: begin atomic …. end Not supported on most databases
18
Oracle COMMIT; ROLLBACK; SQL Developer, SQLPlus: Autocommit
Read Committed SET TRANSACTION ISOLATION LEVEL READ COMMITTED; ALTER SESSION SET ISOLATION_LEVEL READ COMMITTED; Serializable SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; ALTER SESSION SET ISOLATION_LEVEL SERIALIZABLE; Read Only Transaction Isolation Level SET TRANSACTION ISOLATION LEVEL READONLY; ALTER SESSION SET ISOLATION_LEVEL READONLY;
19
Oracle – practical issues
Transactions – administration!! (even for single-user case!) Log files (Redo-log, Undo-log) Execution time !!! Storage place requirement !!! DML vs DDL operations in general INSERT INTO vs. CREATE TABLE <newtable> AS SELECT ….. DELETE FROM <tabletobeemptied> vs TRUNCATE <tabletobeemptied>
20
Database utilities
22
Oracle utilities Tools to allow fast and easy
data transfer, maintenance, and database administration (Data Pump) Export, Import Creates and reads „dump“ files SQL*Loader Text files
23
Different databases, different versions
Different vendors MySQL PostgreSQL MS SQL Server IBM DB2 Different versions Oracle 9, 10, 11R1, 11R2,…. Dump files and tools for them are vendor and version dependent No general data exchange tools for relational databases!
24
Procedural languages for relational databases Oracle PL/SQL
25
Advantages of Procedural Extensions
SQL – extensions – procedural processing power – needed Modular, maintainable, reusable software development Better performance (in specific cases!): multiple SQL statements simultaneously on server sided, thereby reducing network traffic. (not: PL/SQL functions, loops instead of SQL constructs – optimiser!!) Error Handling: effective handling of exceptions Security Predefined packages
26
SQL Procedural Extensions
Oracle PL/SQL Java PostgreSQL PL/pgSQL PL/Tcl PL/Perl PL/Python IBM DB2 SQL PL Microsoft MS SQL Server: TSQL MySQL SQL/PSM HANA SQLScript Standard ? SQL/PSM; SQL:1999, SQL:2011; IBM DB2, MySQL
27
Processing SQL and PL/SQL
28
PL/SQL Block variables, constants, records and cursors
programmatic constructs like loops, conditional statement and SQL statements DECLARE Variable declaration BEGIN Program Execution EXCEPTION Exception handling END; Anonymous Blocks: have no name (like scripts) can be written and executed immediately They are not stored in the database and cannot be executed again! (can also be used in a trigger) Named Blocks They are stored in the database Procedures Functions Graceful error handling
29
Development Tools (Oracle SQL Developer)
Full functioning Editor Code Formatter Syntax Highlighting Code Insight (auto complete) Code Folding Inline Error Reporting Code Bookmarking Customizable Quick Keys Run Procedures, Functions, and Packages DBMS_OUTPUT Function return values OUT parameters Full functioning debugger Control program execution(Step into, over, ...) Inspect and modify variables Configure breakpoint conditions … 6
30
Printing Output You need to use a function in the DBMS_OUTPUT package in order to print to the output If you want to see the output on the screen, you must type the following (before starting): set serveroutput on Then print using dbms_output. put_line(your_string); dbms_output.put(your_string);
31
Hello Word Example
32
DECLARE Syntax Examples identifier [CONSTANT] datatype [NOT NULL]
[:= | DEFAULT expr]; Notice that PL/SQL includes all SQL types, and more… Declare birthday DATE; age NUMBER(2) NOT NULL := 27; name VARCHAR2(13) := 'Levi'; magic CONSTANT NUMBER := 77; valid BOOLEAN NOT NULL := TRUE; 32
33
Declaring Variables with %TYPE and %ROWTYPE
Examples This variable can accept one record, same type as Tuple in the table Emp DECLARE v_hold_one_row Emp%ROWTYPE; v_name Emp.name%TYPE; v_fav_emp VARCHAR2(30); Variable for column „name” in table Emp v_hold_one_row :=987; v_hold_one_row:=877; 33
34
Static SQL in PL/SQL INSERT/UPDATE/DELETE directly in PL/SQL
Substituting pl/sql variables
35
SELECT Statements returning exactly one row
DECLARE v_ename VARCHAR2(10); v_id NUMBER(3); BEGIN SELECT ename, id INTO v_ename, v_id FROM emp WHERE id = '112'; END; / INTO clause is required. Query must return exactly one row. Otherwise, a NO_DATA_FOUND or TOO_MANY_ROWS exception is thrown 35
36
Creating a Cursor We create a Cursor when we want to go over a result of a query Syntax Example: DECLARE cursor c is select * from emp; emp_duplicate Emp%ROWTYPE; BEGIN open c; fetch c into emp_duplicate; emp_duplicate is a variable that can hold a row from the emp table Here the first row of emp inserted into emp_duplicate
37
Example fetch 3 6 8 RAD_VALS Rad_cursor Rad_val AREAS Radius Area 3
DECLARE Pi constant NUMBER(8,7) := ; area NUMBER(14,2); cursor rad_cursor is select * from RAD_VALS; rad_value rad_cursor%ROWTYPE; BEGIN open rad_cursor; fetch rad_cursor into rad_val; area:=pi*power(rad_val.radius,2); insert into AREAS values (rad_val.radius, area); close rad_cursor; END; / RAD_VALS Rad_cursor fetch Rad_val AREAS Radius Area 3 28.27
38
Explicit Cursor Attributes
Obtain status information about a cursor. Attribute Type Description %ISOPEN Boolean Evaluates to TRUE if the cursor is open. %NOTFOUND Boolean Evaluates to TRUE if the most recent fetch does not return a row. %FOUND Boolean Evaluates to TRUE if the most recent fetch returns a row; complement of %NOTFOUND %ROWCOUNT Number Evaluates to the total number of rows returned so far. Explicit Cursor Attributes As with implicit cursors, there are four attributes for obtaining status information about a cursor. When appended to the cursor or cursor variable, these attributes return useful information about the execution of a data manipulation statement. Note: Do not reference cursor attributes directly in a SQL statement. 38
39
Dynamic SQL SQL unknown at compile time
E.g., generic SELECT statement, table name not fixed at compile time v_stmt_str: VARCHAR2 ! :j: placeholder
40
PL/SQL Control structures
41
Loops: Simple Loop create table number_table( num NUMBER(10) );
DECLARE i number_table.num%TYPE := 1; BEGIN LOOP INSERT INTO number_table VALUES(i); i := i + 1; EXIT WHEN i > 10; END LOOP; END; Basic Loop The basic loop example shown in the slide is defined as follows: insert the first 10 new line items for order number 101. Note: A basic loop allows execution of its statements at least once, even if the condition has been met upon entering the loop. 41
42
Loops: Simple Loop with cursor
create table number_table( num NUMBER(10) ); DECLARE cursor c is select * from number_table; cVal c%ROWTYPE;--cursor type!! BEGIN open c; LOOP fetch c into cVal; EXIT WHEN c%NOTFOUND; insert into duplicate values(cVal.num*2); END LOOP; close c; END; Basic Loop The basic loop example shown in the slide is defined as follows: insert the first 10 new line items for order number 101. Note: A basic loop allows execution of its statements at least once, even if the condition has been met upon entering the loop. 42
43
Loops: FOR Loop DECLARE i number_table.num%TYPE; BEGIN
FOR i IN LOOP INSERT INTO number_table VALUES(i); END LOOP; END; Notice that i is incremented automatically 43
44
Loops: For Cursor Loops
DECLARE cursor c is select * from number_table; BEGIN for num_row in c loop insert into doubles_table values(num_row.num*10); end loop; END; / Cursor FOR Loops A cursor FOR loop processes rows in an explicit cursor. The cursor is opened, rows are fetched once for each iteration in the loop, and the cursor is closed automatically when all rows have ben processed. The loop itself is terminated automatically at the end of the iteration where the last row was fetched. Notice that a lot is being done implicitly: declaration of num_row, open cursor, fetch cursor, the exit condition 44
45
Loops: Simple Loop with cursor
DECLARE v_ename emp.ename%TYPE; CURSOR c_managers IS SELECT ename FROM emp WHERE job = 'MANAGER'; BEGIN OPEN c_managers ; LOOP FETCH c_managers INTO v_ename; DBMS_OUTPUT.put_line(v_ename); EXIT WHEN c_managers%NOTFOUND; END LOOP; END; /
46
Loops: WHILE Loop DECLARE TEN number:=10; i number_table.num%TYPE:=1;
BEGIN WHILE i <= TEN LOOP INSERT INTO number_table VALUES(i); i := i + 100; END LOOP; END; WHILE Loop In the example in the slide, the quantity increases with each iteration of the loop until the quantity is no longer less than the maximum price allowed for spending on the item. 46
47
IF-THEN-ELSIF Statements
. . . IF mark<2 THEN v_message := 'You failed'; ELSIF mark < 4 THEN v_message := 'Not bad'; ELSE v_message := 'Pretty good'; END IF; IF-THEN-ELSIF Statements When possible, use the ELSIF clause instead of nesting IF statements. The code is easier to read and understand, and the logic is clearly identified. If the action in the ELSE clause consists purely of another IF statement, it is more convenient to use the ELSIF clause. This makes the code clearer by removing the need for nested END IFs at the end of each further set of conditions and actions. Example IF condition1 THEN statement1; ELSIF condition2 THEN statement2; ELSIF condition3 THEN statement3; END IF; The example IF-THEN-ELSIF statement above is further defined as follows: For a given value entered, return a calculated value. If the entered value is over 100, then the calculated value is two times the entered value. If the entered value is between 50 and 100, then the calculated value is 50% of the starting value. If the entered value is less than 50, then the calculated value is 10% of the starting value. Note: Any arithmetic expression containing null values evaluates to null. 47
48
Exception handling -- Reminder: structure of a block
DECLARE (optional) /* Here you declare the variables you will use in this block */ BEGIN (mandatory) /* Here you define the executable statements (what the block DOES!)*/ EXCEPTION (optional) /* Here you define the actions that take place if an exception is thrown during the run of this block */ END; (mandatory) /
49
Trapping Exceptions Runtime errors vs compile time errors
NO_DATA_FOUND TOO_MANY_ROWS ZERO_DIVIDE Exception handling: actions that should happen when an exception is thrown. When handling an exception, consider performing a rollback Trapping Predefined Oracle Server Errors Trap a predefined Oracle Server error by referencing its standard name within the corresponding exception-handling routine. Note: PL/SQL declares predefined exceptions in the STANDARD package. It is a good idea to always consider the NO_DATA_FOUND and TOO_MANY_ROWS exceptions, which are the most common. 49
50
Trapping Exceptions EXCEPTION WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE (‘ There is no student with student id 123 ’); END;
51
num_row number_table%ROWTYPE; BEGIN select * into num_row
DECLARE num_row number_table%ROWTYPE; BEGIN select * into num_row from number_table; dbms_output.put_line(1/num_row.num); EXCEPTION WHEN NO_DATA_FOUND THEN dbms_output.put_line('No data!'); WHEN TOO_MANY_ROWS THEN dbms_output.put_line('Too many!'); WHEN OTHERS THEN dbms_output.put_line(‘Error’); end; Trapping Predefined Oracle Server Exceptions In the slide example for each exception, a message is printed out to the user. Only one exception is raised and handled at any time. 51
52
User-Defined Exception
DECLARE e_number1 EXCEPTION; cnt NUMBER; BEGIN select count(*) into cnt from number_table; IF cnt = 1 THEN RAISE e_number1; ELSE dbms_output.put_line(cnt); END IF; EXCEPTION WHEN e_number1 THEN dbms_output.put_line('Count = 1'); end; Trapping User-Defined Exceptions You trap a user-defined exception by declaring it and raising it explicitly. 1. Declare the name for the user-defined exception within the declarative section. Syntax exception EXCEPTION; where: exception is the name of the exception. 2. Use the RAISE statement to raise the exception explicitly within the executable section. RAISE exception; where: exception is the previously declared exception. 3. Reference the declared exception within the corresponding exception handling routine. In the slide example: This customer has a business rule that states a that a product can not be removed from its database if there is any inventory left in-stock for this product. As there are no constraints in place to enforce this rule, the developer handles it explicitly in the application. Before performing a DELETE on the PRODUCT table, the block queries the INVENTORY table to see if there is any stock for the product in question. If so, raise an exception. Note: Use the RAISE statement by itself within an exception handler to raise the same exception back to the calling environment. 52
53
Functions and Procedures
Up until now, our code was in an anonymous block It was run immediately It is useful to put code in a function or procedure so it can be called several times Once we create a procedure or function in a Database, it will remain until deleted (like a table).
54
Functions and Procedures
The header specifies : name and parameter list : return type (function headers) : any of the parameters can have a default value : modes - IN, OUT, IN OUT Function example Procedure example CREATE FUNCTION get_department_no ( p_dept_name IN VARCHAR2 := null) RETURN NUMBER IS DECLARE BEGIN RETURN(l_dept_no); EXCEPTION END; CREATE PROCEDURE department_change ( p_dept_number IN NUMBER p_new_name IN OUT VARCHAR ) AS DECLARE BEGIN ………….. END; 54
55
Creating Procedures CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter1 [mode1] datatype1, parameter2 [mode2] datatype2, . . .)] IS|AS PL/SQL Block; Modes: IN: procedure must be called with a value for the parameter. Value cannot be changed OUT: procedure must be called with a variable for the parameter. Changes to the parameter are seen by the user (i.e., call by reference) IN OUT: value can be sent, and changes to the parameter are seen by the user Default Mode is: IN
56
Example- what does this do?
Table mylog create or replace procedure num_logged (person IN mylog.who%TYPE, num OUT mylog.logon_num%TYPE) IS BEGIN select logon_num into num from mylog where who = person; END; / logon_ num who 3 Pete 4 John 2 Joe
57
Calling the Procedure declare howmany mylog.logon_num%TYPE; begin
num_logged(‘John',howmany); dbms_output.put_line(howmany); end; /
58
Creating a Function Almost exactly like creating a procedure, but you supply a return type CREATE [OR REPLACE] FUNCTION function_name [(parameter1 [mode1] datatype1, parameter2 [mode2] datatype2, . . .)] RETURN datatype IS|AS PL/SQL Block;
59
dbms_output.put_line(squareFunc(3.5)); END; /
Creating a function create or replace function squareFunc(num in number) return number is BEGIN return num*num; End; / Using the function: BEGIN dbms_output.put_line(squareFunc(3.5)); END; /
60
Packages Logically connected Functions, Procedures, Variables can be put together in a package In a package, you can allow some of the members to be "public" and some to be "private" There are also many predefined Oracle packages
61
Packages Many PL/SQL packages are provided within the Oracle Server
Extend the functionality of the database Some example of such packages: : DBMS_JOB - for scheduling tasks : DBMS_OUTPUT - display messages to the session output device : UTL_HTTP - makes HTTP(S) callouts Note: can be used for accessing a web-service from the database : PL/SQL web toolkit (HTP, HTF, OWA_UTIL, etc.) Note: can be used for building web-based interfaces e.g.
62
Oracle® Database PL/SQL Language Reference 11g Release 2 (11
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.