Dbms Unit 4 To 5
Dbms Unit 4 To 5
Dbms Unit 4 To 5
Transaction Operations
❑ The low level operations performed in a transaction are −
❑ begin_transaction − A marker that specifies start of
transaction execution.
❑ read_item or write_item − Database operations that may
be interleaved with main memory operations as a part of
transaction.
❑ end_transaction − A marker that specifies end of
transaction.
❑ commit − A signal to specify that the transaction has been
successfully completed in its entirety and will not be
undone.
❑ rollback − A signal to specify that the transaction has been
unsuccessful and so all temporary changes in the database
are
José Alferes - Adaptado de undone.
Database th A committed
System Concepts - 5 Edition transaction
15-17.4 cannot be rolled back.
Transaction ACID properties
E.g. transaction to transfer €50 from account A to account B:
1. read_from_acoount(A) (Suppose A=100,B=200 A+B=300)
2. A := A – 50 (A=50)
3. write_to_account(A) <---(Power Failure)
4. read_from_accont(B) Mismatch i.e.
5. B := B + 50 data
6. write_to_account(B) (A+B=50+200=250) inconsistent
Atomicity requirement
if the transaction fails after step 3 and before step 6, money will be “lost”
leading to an inconsistent database state
Failure could be due to software or hardware
the system should ensure that updates of a partially executed transaction
are not reflected in the database
All or nothing, regarding the execution of the transaction
Durability requirement — once the user has been notified of transaction has
completion, the updates must persist in the database even if there are software
or hardware failures.
A=100
A=50
B=200
B=250
SUM=300
A= 50
temp=50*.10=5
A=45
B=250
B=250+5=255
A+B=300
José Alferes - Adaptado de Database System Concepts - 5th Edition 15-17.13
Equivalent Schedule
temp=50*0.1=5
A=50-5=45
B=200
B=200+50=250
B=250
B=250+5=255
A+B=45+255=300
A=90
B=200
B=200+50
B=250
B=250+10=260
T1 T2
R(A)
W(A)
R(A)
W(A)
T1
T2 Precedence Graph
R(A)
W(A)
T1
T2
R(A)
W(A)
W(A)
T1--->T2
OR
T1 T2--->T1
T2
R(A)
W(A)
W(A)
R(A)
W(A)
W(A)
T1--->T2--->T3
T1---->T3---->T2 Factorial of no. of Conflict
T2---->T1----->T3 tractions View
T2----->T3---->T1 3!=6
T3----->T1----->T2
T3----->T2------>T1
José Alferes - Adaptado th
de Database System Concepts - 5 Edition 15-17.21
Numerical
T1 T2 T3
R(X)
R(Y)
R(X)
R(Y)
R(Z)
W(Y)
W(Z)
R(Z)
W(X)
W(Z)
Indegree=0
T1
T2--->T3--->T1
T3
Consistent
Yes No
View Blind Write
CS Yes No
Check Not View Serializability
Dependency
graph
Final
Write
W(A) W(A)
1-2-3
T1 1-3-2
T2 2-1-3
2-3-1
3-1-2
T3 3-2-1
Schedule 3 Schedule 6
José Alferes - Adaptado de Database System Concepts - 5th Edition 15-17.31
Conflict Serializability (Cont.)
T1 T2 T3 T4 T5
read(X)
read(Y)
read(Z)
read(V)
read(W)
T1 T2
read(W)
read(Y)
write(Y)
write(Z)
read(U)
read(Y)
T3 T4
write(Y)
read(Z)
write(Z)
read(U)
write(U) T5
Example 1:
S1: R1(x), W1(x), R2(x), R1(y), R2(y), W2(x), W1(y), C1, C2;
T1 T2
R(X)
W(X)
R(X)
R(Y)
R(Y)
W(X)
W(Y)
C1
C2
A=10 again
A=100 T1 T2 T3 T4
A=100-50=50
A=50 R(A)
W(A)
Rollback R(A)
A=50
R(A)
A=50 A=50
R(A)
Fail
Rollback
T1 T2
R(A)
A=A-5
W(A)
Commit
R(A)
A=A+2
W(A)
Commit
W(A)
R(A)
W(A)
C1
R(A)
T1 T2
R(A) Suppose100
A=A-50
W(A) A=50
A=A-30 50-30=20
(Lost)
W(A)
Fail
T1 T2
S(A) X(A)
R(A) R(A)
U(A) W(A)
U(A)
Grant
Case1 Case 2
T1 T2 T1 T2
R(A) R(A)
W(A) W(A)
R(A) R(A)
W(A)
Case3 Case4
T1 T2
May not free from X(A)
Irrecoverability R(A)
W(A)
U(A) S(A)
R(A)
U(A)
Commit
T1 T2
X(A)
R(A)
W(A) S(A)
R(A) T1---->T2
S(B) Serializability is
R(B)
achieved
U(A)
.
U(B)
José Alferes - Adaptado de Database System Concepts - 5th Edition 15-17.63
T1 T2
Lock S(A)
Growing Phase
Lock S(A)
Growing Phase
Lock Point Lock X(B)
UnLock(A)
Lock X(D)
Shrinking Phase
Lock Point
UnLock(B)
UnLock(A)
Shrinking Phase
UnLock(D)
T1 T2 T1 T2 T3 T4
X(A)
Lock X(A) R(A)
R(A) W(A) R(A)
W(A)
UnLock(A) R(A)
Lock S(A)
R(A) R(A)
Commit
Fail
T1 can rollback but T2 can’t- Fail
Irrecoverable Schedule
Cascading Schedule degrade
José Alferes - Adaptado de Database System Concepts - 5th Edition 15-17.65 performance
Deadlock
A system is in deadlock state if there exists a set of transactions such
that every transaction in the set is waiting for another transaction in
the set.
Waiting for T2 to release lock on Y
T1 T2
X,Y X,Y
Lock(X) Lock(Y)
T2 P Exclusive
Q Exclusive
T3 Q Shared
T4 P Exclusive
T2
José Alferes - Adaptado de Database System Concepts - 5th Edition 15-17.67
Deadlock Detection
Deadlocks can be described as a wait-for graph where:
vertices are all the transactions in the system
There is an edge Ti →Tk in case Ti is waiting for Tk
When Ti requests a data item currently being held by Tk, then the edge
Ti →Tk is inserted in the wait-for graph. This edge is removed only
when Tk is no longer holding a data item needed by Ti.
The system is in a deadlock state if and only if the wait-for graph has a
cycle. Must invoke a deadlock-detection algorithm periodically to look
for cycles.
Wound wait:If Ts(Ti)<Ts(Tj) [Ti is older than Tj], then abort Tj(Ti
wounds Tj and restart it with same timestamp.If Ts(Ti)>Ts(Tj),then Ti
is allowed to wait.
Time Out Based Scheme- If Transaction that has requested a lock
waits for at most a specified amount of time.If the lock is not granted
within that time,transaction is said to timeout and it rollsback and
restarts.
T1 T2
Abort
Note:Cascadeless and Strict recoverable Schedules are achieved from this modified 2 PL.
W(A)
Ts(Ti)=Timestamp of Ti
W(A)
W(A)
W(A)
W(A) R(A)
T1(OLDER)100 T2(YOUNGER)200
W(A)
W(A)
T1(OLDER)100 T2(YOUNGER)
200
W(A)
W(A)
transaction transaction
with smaller with larger
timestamp timestamp
<T1,Start>
A=100--->200 <T1,A,200>
B=200--->400 <T1,B,400>
<T1,commit>
<T2,Start>
<T2,C,500>
A=100--->200
B=200--->400
Successfully
written into Checkpoint
database
Redo as
Completed
T1 T1 transactions
System
T2 T2 Failure
System
T3 Failure T3
Undo as
Incompleted
T4 T4 transaction
Rollback Rollback
All the modifications which are done by transaction which are present in
buffers are transferred to physical database.
Output current page table to disk.
Disk address of current page table output to fixed location which is in stable
storage containing address of shadow page table. This operation overwrites
address of old shadow page table. With this current page table becomes
same as shadow page table and transaction is committed.
Failure :
If system crashes during execution of transaction but before commit
operation, With this, it is sufficient only to free modified database pages and
discard current page table. Before execution of transaction, state of database
get recovered by reinstalling shadow page table.
If the crash of system occur after last write operation then it does not affect
propagation of changes that are made by transaction. These changes are
preserved and there is no need to perform redo operation.
Disadvantages :
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;
DECLARE
message varchar2(20):= 'Hello, World!';
BEGIN
dbms_output.put_line(message);
END;
/
The end; line signals the end of the PL/SQL block. To run the code
from the SQL command line, you may need to type / at the beginning
of the first blank line after the last line of the code.
Delimiter Description
+, -, *, / Addition, subtraction/negation, multiplication, division
% Attribute indicator
' Character string delimiter
. Component selector
(,) Expression or list delimiter
: Host variable indicator
, Item separator
" Quoted identifier delimiter
= Relational operator
@ Remote access indicator
; Statement terminator
DECLARE
-- variable declaration
message varchar2(20):= 'Hello, World!';
BEGIN
/*
* PL/SQL
executable statement(s)
*/
dbms_output.put_line(message);
END;
/
PL/SQL block
Function
Package
Package body
Procedure
Trigger
Type
Type body
PL/SQL allows the nesting of blocks i.e. blocks with blocks. Based on
the nesting structure PL/SQL variables can be divide into following
categories:
Local variables – Those variables which are declared in an inner
block and not accessible to outer blocks are known as local variables.
Global variables – Those variables which are declared in the outer
block or a package and accessible to itself and inner blocks are known
as global variables.
<var_name> <tab_name>.<column_name>%TYPE;
Where <column_name> is the column defined in the <tab_name>.
José Alferes - Adaptado de Database System Concepts - 5th Edition 15-17.120
Consider a declaration.
SALARY EMP.SAL % TYPE;
This declaration will declare a variable SALARY that has the same
data type as column SAL of the EMP table.
Example:
DECLARE
SALARY EMP.SAL % TYPE;
BEGIN
Select SAL into SALARY from EMP where EMPNO = 1;
dbms_output.put_line('Salary of EMPNO1: ‘ || SALARY);
END;
If you don’t know the data type at the time of declaration. The data
type assigned to the associated variables will be determined
dynamically at run time.
If the data type of the variable you are referencing changes the
%TYPE or %ROWTYPE variable changes at run time without having
to rewrite variable declarations. For example: if the ENAME column of
an EMP table is changed from a VARCHAR2(10) to VRACHAR2(15)
then you don’t need to modify the PL/SQL code.
a is less than 20
value of a is : 10
Salary updated
IF condition THEN
S1;
ELSE
S2;
END IF;
DECLARE
a number(3) := 100;
BEGIN
-- check the boolean condition using if statement
IF( a < 20 ) THEN
-- if condition is true then print the following
dbms_output.put_line('a is less than 20 ' );
ELSE
dbms_output.put_line('a is not less than 20 ' );
END IF;
dbms_output.put_line('value of a is : ' || a);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
IF(boolean_expression 1)THEN
S1; -- Executes when the boolean expression 1 is true
ELSIF( boolean_expression 2) THEN
S2; -- Executes when the boolean expression 2 is true
ELSIF( boolean_expression 3) THEN
S3; -- Executes when the boolean expression 3 is true
ELSE
S4; -- executes when the none of the above condition is true
END IF;
Syntax
IF( boolean_expression 1)THEN
-- executes when the boolean expression 1 is true
IF(boolean_expression 2) THEN
-- executes when the boolean expression 2 is true
sequence-of-statements;
END IF;
ELSE
-- executes when the boolean expression 1 is not true
else-statements;
END IF;
When the above code is executed at the SQL prompt, it produces the
following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
After the body of the for loop executes, the value of the counter
variable is increased or decreased.
Example
DECLARE
a number(2);
BEGIN
FOR a in 10 .. 20 LOOP
dbms_output.put_line('value of a: ' || a);
END LOOP;
END;
/
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20
By default, iteration proceeds from the initial value to the final value,
generally upward from the lower bound to the higher bound. You can
reverse this order by using the REVERSE keyword. In such case,
iteration proceeds the other way. After each iteration, the loop counter
is decremented.
However, you must write the range bounds in ascending (not
descending) order. The following program illustrates this −
DECLARE
a number(2) ;
BEGIN
FOR a IN REVERSE 10 .. 20 LOOP
dbms_output.put_line('value of a: ' || a);
END LOOP;
END;
/
José Alferes - Adaptado de Database System Concepts - 5th Edition 15-17.155
When the above code is executed at the SQL prompt, it produces the
following result −
value of a: 20
value of a: 19
value of a: 18
value of a: 17
value of a: 16
value of a: 15
value of a: 14
value of a: 13
value of a: 12
value of a: 11
value of a: 10
PL/SQL procedure successfully completed.
José Alferes - Adaptado de Database System Concepts - 5th Edition 15-17.156
PL/SQL allows using one loop inside another loop. Following section
shows a few examples to illustrate the concept.
LOOP
Sequence of statements1
LOOP
Sequence of statements2
END LOOP;
END LOOP;
If you are using nested loops (i.e., one loop inside another loop), the
EXIT statement will stop the execution of the innermost loop and start
executing the next line of code after the block.
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
Syntax
The syntax for a CONTINUE statement is as follows −
CONTINUE;
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
José Alferes - Adaptado de Database System Concepts - 5th Edition 15-17.172
GOTO statement
A GOTO statement in PL/SQL programming language provides an
unconditional jump from the GOTO to a labeled statement in the same
subprogram.
Procedure created.
BEGIN
greetings;
END;
/
The above call will display −
Hello World
Parameter Mode:
IN:An IN parameter lets you pass a value to the subprogram. It is a read-only
parameter. Inside the subprogram, an IN parameter acts like a constant. It cannot
be assigned a value. You can pass a constant, literal, initialized variable, or
expression as an IN parameter. You can also initialize it to a default value;
however, in that case, it is omitted from the subprogram call. It is the default mode
of parameter passing. Parameters are passed by reference.
OUT:An OUT parameter returns a value to the calling program. Inside the
subprogram, an OUT parameter acts like a variable. You can change its value and
reference the value after assigning it. The actual parameter must be variable
and it is passed by value.
IN OUT:An IN OUT parameter passes an initial value to a subprogram and returns
an updated value to the caller. It can be assigned a value and the value can be
read.The actual parameter corresponding to an IN OUT formal parameter
must be a variable, not a constant or an expression. Formal parameter must
be assigned a value. Actual parameter is passed by value.
DECLARE
a number;
PROCEDURE squareNum(x IN OUT number) IS
BEGIN
x := x * x;
END;
BEGIN
a:= 23;
squareNum(a);
dbms_output.put_line(' Square of (23): ' || a);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Named Notation
In named notation, the actual parameter is associated with the formal
parameter using the arrow symbol ( => ). The procedure call will be like the
following −
While creating a function, you give a definition of what the function has
to do. To use a function, you will have to call that function to perform
the defined task. When a program calls a function, the program control
is transferred to the called function.
A called function performs the defined task and when its return
statement is executed or when the last end statement is reached, it
returns the program control back to the main program.
Maximum of (23,45): 45
n! = n*(n-1)!
= n*(n-1)*(n-2)!
...
= n*(n-1)*(n-2)*(n-3)... 1
Implicit cursors
Explicit cursors
In PL/SQL, you can refer to the most recent implicit cursor as the SQL
cursor, which always has attributes such as %FOUND, %ISOPEN,
%NOTFOUND, and %ROWCOUNT. The SQL cursor has additional
attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS,
designed for use with the FORALL statement.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 2500.00 |
| 4 | Chaitali | 25 | Mumbai | 7000.00 |
| 5 | Hardik | 27 | Bhopal | 9000.00 |
| 6 | Komal | 22 | MP | 5000.00 |
+----+----------+-----+-----------+----------+
José Alferes - Adaptado de Database System Concepts - 5th Edition 15-17.200
Explicit Cursors
Explicit cursors are programmer-defined cursors for gaining more
control over the context area. An explicit cursor should be defined in
the declaration section of the PL/SQL Block. It is created on a
SELECT Statement which returns more than one row.
1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
OLD and NEW references are not available for table-level triggers,
rather you can use them for record-level triggers.
If you want to query the table in the same trigger, then you should use
the AFTER keyword, because triggers can query the table or change it
again only after the initial changes are applied and the table is back in
a consistent state.
The above trigger has been written in such a way that it will fire before
any DELETE or INSERT or UPDATE operation on the table, but you
can write your trigger on a single or multiple operations, for example
BEFORE DELETE, which will fire whenever a record will be deleted
using the DELETE operation on the table.
Old salary:
New salary: 7500
Salary difference:
UPDATE customers
SET salary = salary + 500
WHERE id = 2;
When a record is updated in the CUSTOMERS table, the above
create trigger, display_salary_changes will be fired and it will display
the following result −
No such customer!
The above program displays the name and address of a customer whose
ID is given. Since there is no customer with ID value 8 in our database,
the program raises the run-time exception NO_DATA_FOUND, which is
captured in the EXCEPTION block.
DECLARE
exception_name EXCEPTION;
BEGIN You can use the above syntax in
raising the Oracle standard
IF condition THEN exception or any user-defined
exception.
RAISE exception_name; In the next section, we will give
END IF; you an example on raising a user-
defined exception. You can raise
EXCEPTION the Oracle standard exceptions in
a similar way.
WHEN exception_name THEN
statement;
END;
DECLARE
my-exception EXCEPTION;
DECLARE
c_id customers.id%type := &cc_id;
c_name customerS.Name%type;
c_addr customers.address%type;
-- user defined exception
ex_invalid_id EXCEPTION;
BEGIN
IF c_id <= 0 THEN
RAISE ex_invalid_id;
ELSE
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
END IF;
EXCEPTION
WHEN ex_invalid_id THEN
dbms_output.put_line('ID must be greater than zero!');
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
José Alferes - Adaptado de Database System Concepts - 5th Edition 15-17.219
Output
When the above code is executed at the SQL prompt, it produces the
following result −