0% found this document useful (0 votes)
163 views21 pages

Database Transaction: Management

1. The document discusses database transactions, including the concept of a transaction, transaction states, and transaction management properties. 2. A transaction is a sequence of one or more SQL statements that combine together to form a single logical unit of work. During execution, a transaction passes through several states until it commits or aborts. 3. The key properties of transactions that ensure its ACID properties are Atomicity, Consistency, Isolation, and Durability. This guarantees that transactions are processed reliably and data integrity is maintained.

Uploaded by

Piyush Pushkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
163 views21 pages

Database Transaction: Management

1. The document discusses database transactions, including the concept of a transaction, transaction states, and transaction management properties. 2. A transaction is a sequence of one or more SQL statements that combine together to form a single logical unit of work. During execution, a transaction passes through several states until it commits or aborts. 3. The key properties of transactions that ensure its ACID properties are Atomicity, Consistency, Isolation, and Durability. This guarantees that transactions are processed reliably and data integrity is maintained.

Uploaded by

Piyush Pushkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

10 Database Transaction

UNITIV

Syllabus

concept of a saction, Transaction


Transa
Basc
Management, Properties of Transactions,
Schedule
Conce
ncept of Schedule, Serial
lit: Conflict and View, Cascaded Aborts,
Recoverable and Non recoverable
Serializabi

Schedules.

10.1 Transaction

Example
Transaction during its execution should be in one ofthe
Transferring Rs.100 from one account to other
diferent states at any point of time, explain the
. Withdraw Rs.100 from
diferent states of transactions during its execution account 1
SPPU-Dec 17, Dec. 18,8 Marks 2. Deposit Rs.100 to account_2
oState and explain in brief the ACiD Properties During Simple query fired on DBMS is called SQL operation.
erecution of transaction, a transaction passes through
Collection of multiple operations that forms a single
several states, until it
finally commitsoraborts. List all logical unit is called as transaction.
possible sequences of states through which a
transaction may pasS. A transaction is a sequence of
Explain why each state one or more SQL
transitionoccurs. SPPU-May 18,9Marks statements that combined together to form a single
logical unit of wor
10.1.1 Concept of Transaction
Transaction
1. Introduction Block
Application Oracle
(SQL server
Single SQL command is sent to database server as aa commands)
query and server will reply with answer.
Fig. 10.1.2: Executing Transaction in DBMs
Multiple SQL commands (DML,DRL etc.) are sent to
Types of operations that can be done inside
0aTabase server which executed one after other
transaction
3s shown in
Fig. 10.1.1)
(a) Read operation
FsaL -
Application -SQL Other DBMSs Read operation transfers data item from
-SQL-
SQL- (e.g. table) the database memory to a local buffer
of the transaction that executed the read
ig. 10.1.1 Executing Single Operation in DBMS
operation.
In
place of
We ending one by one SQL command to server Example:
Combine
lar
multiple operations that are logically Data Selection /Retrieval Language
and send to unit called
server as a single logical SELECT
transaction. FROM Students;
TechKnouledge
PUbITC ationsS
Daabase Management System (SPPU-Sem 5-Comp) 10-2 atabase Transacion D a t a b a s e M

anagement system (SPPU-S n5-Comp) 10-3


a n a

2. Transaction structure
(b) Write operation: Transaction Manageme Architecture
The transaction consists of all sQL ? Tra.

A
Write operation transfer data from local memory
between the begin transaction and
oDe
rattransaction,
ions execut detailed system architecture of transaction is start Database Transaction
to database. and eend database tarted by
NSACTION cocommand.
O Write operation transfers one data item from the A transaction starts with a
ecuted Eplan

executed the DBMS


issuing BEGIN
Once this
a

3EG N commandI is
System

local buffer of the transaction that executed the notes o n : starts


monitoring the
write back to the database.
command.

BEGIN Command instructs


transactition monitor to
ransaction a
Wnte
a
short
ery processor
Al
operations executed
Command are treated
as a
after a BEGIN
transaction.
TRANSACTION
Example: starts monitoring the transaction
nsaction m a n a g e m e n t
Application single large operation.
statu Sequences ofprograms use transactions to execute
Transa

Data GStorage
managemen ent
manipulation language (DML) operations done aftera BEGIN comman
All the operations
when it is
UPDATE Student as a single large operation. working
of
of detailed system architecture operations are successfully important that all
SET Name Bhavna'
3. Transaction boundaries
treated a
DescriDe

DBMS
of
Example: completed.
Where Sid 1186 Whatdoyou nderstand by transaction management? During the transfer of money
information processing in DBMS divides Transaction must ends either by Transaction processing components ot a DBMS are accounts it is between two bank
operation unacceptable
individual, indivisible operational logical units, called or ROLLBACK command. executing COMMr a
Fig. 10.1.5)
updates the second for the
operation that
MIT Rtedbelow
(refer
the
account to fail. This would
lead to
transactions. transferred money
A
Until a transaction commits or rolls
back
T r a n s a
ions
c t i o n

management: The transaction manager being


withdrawn from one account lost. It will have been
transaction is sequence of small database tha but not inserted into the
onsible for co-ordina
d.

operations.
a
database remains unchanged. ata in the execution of all the second account.
transactions being executed by the DBMS,
Begin transaction
Transactions will execute to complete all set of : The scheduler is
aduler responsible for selecting
operations successfully. BEGIN TRANSACTION transfer
he best method of executing each transaction and
Commit Deduct Rs.100 from
Example: Rollback onsuring that a transaction does not interfere with the
account A
Fig. 10.1.4 execution of other transactions Add Rs.100 to
During the transfer of
money between two bank account B
accounts it is problematic if one of (a) Commit transaction Recovery manager: when a transaction fails and
transaction fails.
rolled back, it is the recovery manager's responsibility
BEGIN TRANSACTION transfer All successful transactions are f no errors
then
required to return the database to the state it was in before the
UPDATE accounts committed by issuing commit command. To to be transaction was executed. Save changes made by this operation
make all Else
SET balance=balance -100 changes permanent and available to other Buffer manager: The buffer
manager manages the
users of the
database. disc space and main memory that is Delete changes made by this
WHERE account=A required to operation
process the transactions. End If
(b) Rollback transaction
If transaction is unsuccessful due END TRANSACTION transfer
UPDATE accounts to some error then
it
SET balance=balance+ 100
must be rolled back. Transacilon Scheduler
manager Fig. 10.1.6: Sample implementation of
WHERE account=B Roll back command will
remove all changes to the transaction in PLISQL
database which are undone and the
if no errors then database remains Buffer Transaction management component will ensure the
unchanged by effect of transaction. manaager
Recovery
manager atomicity and durability properties.
Commit Transaction
The DBMS should take care of transaction it should be
else To detect system failures and restore the database to
either complete or fail. the state that existed prior to the occurrence of the
Rollback Transaction Access File
When a transaction fails all its methods failure database system must therefore perform
EndIf operations and tme manager
database is returned to the original state it was in failure recovery.
END TRANSACTION transfer
before the transaction started. System It is the responsibility of the concurrency-control
Fig. 10.1.3 Sample buffer
Implementation of Transaction in Database manager to control the interaction
between various

sQL concurrenttransactions, to ensure the consistency of

Fig. 10.1.5: Transaction architecture the database.

TechKaeulg TechKneuledge
Ocacons
YPubI1Cat
e ransacion DalaDase Mae

omp) 10-5
(SPPU-Sem
5-Comp) 10
Management System
(c) Failed Read (A); Database Transaction
Dalabase Processing-
in above
enters the failed state AA-100; either all above changes are made
case
10.1.3 Working of
Transaction A transaction after database
the transaction he Write(A)
or
nothing should be done as half done
onger System
Transaction State Diagram determines that can no

transaction may leave data as


may be
saved on
with its
normal execution.
proceeteed Read(B); incomplete state.
successfully it IT one part of
F transaction complete transaction.
Example: In case of Hardware or gical e BB +100; the transaction fails, the entire
committed
to database
server called as

database from
one errors occuts ransaction fails and the
database state is lert
transaction
transfers
while execution.
WritelB) unchanged.
A committed
which must
state,
Fig. 10.1.8 : Sample transaction
consistent
consistent state to other (d) Aborted 2. Consistency
failure.
is a system
persist even if there Failed transaction must be rolled back
always complete
its execution
back. Then it 1 . A t o m i c i t y
Consistent state is a database state in which all valid
ransaction may not the aborted state.
enters data will be written to the
must be aborted. ransaction must be treated as a single unit of database.
a transaction
successfully. Such Tran
that Transaction has been rolled back fa transaction violates some consistency rules, the
An aborted transaction
must not have any
change restoring intoto prior operation.

vhole transaction will be rolled back and the database


database. Such state. means when a sequence of operations is
made to the
the aborted transaction That
m
wIill be restored to its previous consistent state with
In this stage system have two options:
must be undone or rolled back. orformed in a single transaction, they are treated as a
changes those rules
undo ts
we cannot the transaction : A restarted single large operation.
is committed, 1) Restart
Once a transaction
effects by aborting it.
is considered to be a new transaction u transaction Example 1:
On the other hand, if a transaction is executed

nay successfully than it will take the database from one


recover from possible failure.
10.1.3.1 Transaction States (al Withdrawing money from your account. consistent state to another consistent state.
2) Killthe transaction: Because the bad airline reservation.
Making an DBMS should handle an inconsistency and also ensure
A transaction must be in one of the following
states
because the desired data were not (b)
presenttin the that the database is clean at the end of each
database an error can occurs. In this case wo The term atomic means thing that cannot be divided in
can atomic physics. transaction.
Partially Committed kill transaction to récover from failure. parts as in
Commite Execution of a transaction should be either complete Consistency means transaction will never leave your
(e) Committed all. database in a half finished (inconsistent) state.
or nothing should be executed at

Active
When last data item Is written out, the executions are allowed. (No half one part of the transaction fails, all of the pending
transaction No partial transaction
enters into the committed state. changes made by that transaction are rolled back.
done transactions)

Failed Aborted This state occurs after successful completion of Example 2: Example 1:
transaction. A transaction is said to have terminated if (a) Money transfer in above example. O Money transfer in above example
has either committed or aborted.
Fig. 10.1.7:State diagram of a transaction (b) Suppose some type of failure occurs after Write Initially in total balance in accounts A is 1000 and
10.1.4 Fundamental Properties of (A) but before Write (B) then system may lost 100 B is 5000 so sum of balance in both accounts is
(a) Active
Transaction/ ACID Properties rupees in calculation which may cause error as 6000 and while carrying out above transaction
This is initial state of transaction execution. sum of original balance(A+8) in accounts A and B some type of failure occurs after Write (A) but
As soon as transaction execution starts it is in active To understand transaction properties we consider a is not preserved (such situation is called as before Write (B) then system may lose 100 rupees

state. transaction of transferring 100 rupees from account A to inconsistency explained later), In such case in calculation.
database should automatically restore original o As now sum of balance in both accounts is 5900
Transaction remains in this state till transaction account B as Follows.
finishes. value of data items. (which should be 6000) which is not a consistent
Let T, be a transaction that transfers 100 rupees from result which introduces inconsistency in database.
Example 3:
(b) Partially committed account A to account B. This transaction can be defined as,
Making an airline reservation o This means that during a transaction the database
As soon as last operation in transaction is executed
may not be consistent
transaction goes to partially committed state. (a) Read balance of account A. a) Check availability of seats in desired flight.

At this condition the transaction has completed it (D) Withdraw 100 rupees from account A and write
Dack 6) Airline confirms your reservation 3. lsolation
that each transaction must
execution and ready to commit on database server. result of balance update. c Reduces number of available seats Isolation property ensures

But, it is still possible that it may be aborted, as the () remain unaware of other concurrently executing
Charges your credit card (deduct amount from
actual output may be there in main (C) Read balance of account B. transactions.
memory, and thus your balance)
a hardware tailure transactions
may prohibit its successful (d Deposit 100 rupees to account B and wre eIncreases number of meals loaded on fight Isolation property keeps multiple
completion. separated from each other
until they are completed.
of balance update. (Sometimes)
TechKneuwledge
uledau
udiltations
TechKao
ubila
DataDase
Management System
(SPFU-SEl
Durability Deoion DatabaseManagement
System SPPU-Sem 5-Comp) 10-7
transaction
(example, insert4

perations
occurringin a invisible
to otner
The results of
a transaction that has been Serial Schedule
Database Transaction
abase will remain suco
are In above
statements) the Serial schedule for we can first
Orupdate

the
transaction
commits (on committed to
ssfuly 1 0 . 2

model in which transactions executed ransaction T2 then


execute
transactions

transaction
until

success) or rolls
back (on
transaction tais).
even
after database fails.
unchanged This
aserial
is simple
order that means after finishing
in
first
Twhich may results in some
na
Changes made during a transaction are transaction secondtransaction starts its execution.
Example 1: e Representation: TT
When a transaction changes a bank
account
balance

balance until
once the transaction commits.
permanent Thisapproach specifies first my transaction, then your
transactions should
Schedule B:A
consistent serial schedule
transactions cannot
see the new if the database server is
fails in transaction
otner
not see
Other
hs preliminary results.
A serial schedule that is also consistent is obtained by
the transaction commits. transaction, it will return to a
consistent state
this whs
executing T right after T
Different isolation levels can be set to modify is restarted.
Example10.2.1:
default behaviour. Ty and T2.
T2 A BOperations
The database handles durability by transactionlog. nsider below
two transactions

Transaction isolation is generally configurable


in a ie
:Deposits Rs.100 to both accounts A and B.
25 25 Initial
Once the execution of the above Transaction
T1 Balance
variety of modes.
completes successtully and the user will be transaction Transaction
Ta : Doubles the balance of accounts A and B. Read(A);
Example 2:
A-A+ 100
that the transfer of amount has taken place, if
T ReadA) T Read[A) WritelA)
In onemode, a transaction locks until
the other
no system failure in this transfer of funds. here is 125 25
A-A+ 100 A-A*2 Read(B);
transaction finishes.
The durability property 8uarantees that, all Write(A)
B B+100
System must guarantees that, for every transactions tha Write(A)
changes made by transaction on the Write(B) 25 125
(Tilother al transactions has finished before database will h Read(B) Read(B)
available permanently, athough there is any Read(A);
type o
transactions (Ti) started, or other transactions are
- A*2
started execution after transactions (Ti) finished, Even failure after the transaction completes execution, B-B+100 B-B*2
Write(A) 250 125
though many transactions may execute concurrentiy
10.1.5 Transactions Schedules
Write(8) Write[B)
in the system.
(Concept of Read(B);
Schedules) Serial schedule for above transaction can be B-B2
That means, each transaction is unaware of other represented as below.
1. Introduction Write(B)| 250 250
transactions executing in the system simultaneously. 250 250|Final
Schedule A : A consistent serial schedule
Example 3: Schedule is a sequence of database instructions in Balance
A consistent serial schedule is obtained by executing T
form of execution sequence of operations.
o Money transfer in above example. right after T2
Representation:
TT
A transaction which completes successfully will In above schedule T is executed entirely then T2 has
O The database is temporarily
inconsistent while T A BOperations
above transaction is executing, with the deducted commit all changes done by its instructions. started. Assume account A with Rs.25 and B with Rs.25.
25 25 Initial Balance
Then transaction T will update A as 125 and B as 125. Now
total written to A and the increased total is not A transaction that fails to complete its execution may Read(A); T will read updated values of A and B. Ta will update value
written to account B. f some other concurrently need to abort all changes done by its transaction at A-A*2
running transaction reads balance of account A ofAas 250 and B as 250. The consistency constraint is A +B
the end of execution. Write(A) 50 25 should remain unchanged. So at end of Ty A+ B i.e. 250 +
and B at this intermediate point and computes
2. Representation Read(B); 250 500 remains unchanged so execution ofthis schedule
A+B, it will observe an inconsistent value
(Rs. B-B*2 keeps database in consistent state.
5900). If that other transaction wants to We denote this transaction T as,
perform Write(B) 50 50
10.2.1 Concurrent Schedule
updates on accounts A and B based on the
RrX) Denotes read operation performed by the Read(A);
inconsistent values (Rs. 5900) that it
database may be left database in an
read, the
transaction Ton object X. A-A+ 100 Introduction
inconsistent Write(A) 15 Transactions executed concurrently, that means
state even after both transactions
have WAX): Denotes write operation peformed bythe Read(B); for
operating system executes one transaction some
completed.
A way to avoid the problem of
transaction Ton object X. B-B+100 time then context switches to second transaction and
concurrently
transactions is to execute one transaction executing tach transaction must specify its final action Write(B) 150 150 on.
at a time. commit or abort. 150 150 | Final Balance Transaction processing can allows multiple

transactions to be executed simultaneously on

database server.
ledge

Tech Knouledga
PublIations
(SPPU-Sem 5-Comp) 10-8 Databa Iransacion atabase
Management
System (S
PU-Sem 5-Comp) 10-9
Datdbase Management System can be converted to equivalent
data in
ransaction l2 Doubles the balance off -accoun above schedule
serial Database Transaction
to change A and nce it co
is consistent
it is schedule.
Alowing multiple transactions B.
h e n c e

ons). Also
complications
Ta Read(A) sohedule
edule
and
explain the concept of view
database concurrently causes several equivalents chedules and
with consistency of the data in database. A-A*2
10.3
Se
ability/Serializable Schedule conflict equívalent schedule
Considering the example schedule
given below
maintain consistency in
case of Write(A) Consider Transaction (3). Transaction (TA
t h e Transa
It was
very simple to and SPPU-Dec.18, 8Marks
execution ansaction ( 6 are any hypothetical transactions
senal execution as compare to concurrent Read(B) ran

of transactions. item
B-B2 working
on
data

o l e explaining the execution of TaT and


2 Advantages of concurrency readA)
Write(B) AFA-50
below. Decide whether following schedule is
Write(A)
Improvedthroughput Above transaction can be executed given
or not? Justify your answer. read(A)
the below.
concurrently as confiict serializable emp A0.1
AA-temp
Throughput of transaction
number of transactions
is defined
executed in a
as

given
SPPU-Dec.17,8 Marks write(A)
Schedule C:A schedule that IS NOT SERIAL but read(B)
amount of time. consistent
is still T T B*8*50
write(B)
Ifwe are executing multiple transactions read(B)
Obtained by interleaving the actions of
T with those BB+temp
simultaneously that may increase throughput of Ta write(B)
considerably. Table 10.2.1

Resource Utilization: A B Operations read()


The database system must control above concurrent

25 execution of transactions serializability will ensure that


Resource utilization defined as the processor and
25 Initial Balance Write(Q) the database state remains in consistent state.
disk performing useful work or not (in idle state). ReadA);
We first need to understand which schedules will
The processor and disk utilization increase as A-A+100; Write 0)
Write(A); 125
Write(Q) ensure consistency, and which schedules will not.
number of concurrent transactions increases.
A schedule is the actual execution sequence of
Read(A); Explain Señalizablity Decide
the Concept of Confict .

Reduced waiting Time : Q. whether following schedule is conflict serializable or concurrent transactions.
A-A*2;
T2 Is
A schedule of two transactions T and
There may be some small transaction and some
Write(A); 250 not. Justity your
answer.
SPPU- May 18,8 Marks has
'serializable' if and only if executing this schedule
long transactions may be executing on a system.
Read(B); read (A) 2 or
the same effect as any serial schedule (either T:12
If transactions are running serially, a
short B-B+100;
write (A) T:T)
transaction may have to wait for an earlier long Write(B); 125 write for
read(A) We consider only two operations: read and
transaction to complete, which can lead to Read(B); simplicity.
write (A) purpose of computational
random delays in running a transaction. B-B*2; read(B) Between a read (Q instruction and a write ()
Write(B); instruction on a data item a transaction may
Example 10.2.2:
250 250 Final Balance write(B) sequence of operations on the copy of Q that
Consider two transactions Ty and T perform
Part of is executed which
read(B) is residing in the
local buffer of the
transaction.
In above given schedule Ti
Transaction T: Deposits Rs.100 to both accounts A and B. updates A to 125. Then processor switches to T and part o write B) operations of a
transaction

Thus, the only important


T2 which updates A to 250 is executed. Then context swt of view are its read and write
T Read(A) to and remaining part of T which updates B to 250 EXplain the Concept of Conflict Serializabilty wit
from a scheduling point

A-A+100 executed. At the end remaining part of T2 which


reads De dnple. Since every conflict-serializable
scheaue
instructions.

equivalence are:

Various forms
of schedule
Write(A) eW serializable, why do we emphasize contfict
125 and it to 250 by multiplying value
updates ot or serializability (a) Conflict serializability
This concurrent schedui
consistency
Enalizability rather than view
Read(B) also m a i n t a i n s

SPPU- Dec.18,8 MarksS


(b) View serializability
database as ultimately A +B is250 + 250 = 500 (unchang
B-B+100
ne result of above transaction is exactly Sa is view
serializable

Write(B) herefore Ch whether following schedule


serial schedule shown in above Table 10.2.1.
not. Justify your answer. (Note.T&2
e c hKnowledge

Pu iicat
Database
ee M
Management
anagem
system (SPPU-Sen Comp) 10-11

(SPPU-Sem 5-Comp)
10-10
1 The following set of actions is conflicting:
atabase ransaction for
view
equivalend ence
Note
Database Transaction
onditions
Management System
Cono
Data item
YDatabase
T, :W(X)
=

Every conflict serializable


T, R(X), T,:(X),
D
Transaction schedules schedule is view serializable
10.3.1 Conflict Serializability While the following sets of actions are not
e but not vice
Sy, S2 versa.
Database transaction
In above
1. Introduction o T, R(X) T,:R(X), T,:R(X) example T2 and T,Writes data without
database system
must contro
concurrent

o T, R(X), T,:W(Y), T,:R(X T and S2 are view equivalent if they satisfy reading value of data item by themselves so they are
he that tne
transactions
which ensure
h e d u l e s

followingconditions for data item D, called as "Blind Writes".


execution of
3. Conflict equivalence
consistent state.
database state remains
in
S,must have same transactions included
Two schedules are contlict equivalent if th a)
and
are perrorming same operations on
10.4 Precedence Graph
Conflict turned into one another by a seauens ey can
nf non
be nd
also they
database actions (reads, writes) data.if T, read initial value of DinS, then T1. Introduction
A pair of consecutive
the conflicting swaps of adjacent actions. same
order would change value of D in S,.
is in conflict if changing their reads initial A
transactions.
also particular transaction schedule can be serialized; we
result of at least one of the Example of D written by in
reads
value T, S, then T can draw a
precedence graph.
If Ti
b) also
Transaction A schedule is conflict serializable if it IS reads value of D written by T, in S2 Precedence (or serializability) 8raph for schedule S is a
equivalent to a serial schedule. conflict
Read(D) write(D) final value ot D in Si, then T, also writes graphical representation of transactions executed.
#T, writes
2 of D in S2 A precedence graph is also known as conflict graph or
No Conflict Conflict final value
Read(D) ad(P)
conditions
ensure that transaction reads same serializability graph.
Conflict Conflict Write(P) First 2
Write(D) both schedules.
Precedence graph is a graph of nodes and vertices,
Read(P) value in
where the nodes are the transaction names and the
Consider schedule S has two consecutive instructions ensures that final consistent state.
Read(Q) Condition 3 vertices are attribute collisions.
and , from transactions T, and T, respectively. schedule is view equivalent to a serial
Write(P) If a concurrent
fl and , access to different data items then theywil
Write(Q) schedule of same transactions then it is view Agorithm for precedence graph
not conflict and can be swapped, without any
(a) Add a node for each transaction.
problem. Read(Q) serializable.

If and access to same data item D then consider Write(Q) Consider following schedule Si with concurent (b) Add a directed edge from T, to T,, if T, reads the

following consequences: Fig. 10.3.1 : Schedules transactions <T, T2 T3>. value of an item written by
T
o READ (D), , = READ (D) then no conflict as they In both the schedules S and a serial schedule S<T (c) Add a directed edge from T to T, if T, writes a
Now the schedule S after performi swapping can
only read value. value in to an item after it has been read by Ti.
transformed into schedule R as shown above which T, T> T reads initial value of D. Transaction Ts writes
o This operation is called as non conflicting swap. final value of D. So schedule S satisfies al three
also results in same values of P and Q. Example
o READ (D), , = WRITE (D) then conditions and is view serializable to <T, Tz T,>.
they conflict and The above schedule is same as serial schedule <T, Let us consider Schedule C
can not be swapped. T
o = WRITE (D),
If a schedule S can be transformed into a schedule R Example
=
READ (D) then they conflict and
by a series of swap operations on non Below two schedules S and R view equivalent,
can not be swapped. conflicting8 are

= WRITE instructions, then we can say schedule S and R are


(D),
WRITE (D) then
cannot be swapped.
=
they conflict and
conflict equivalent.
ScheduleS Read(A); A-A+ 100;
1 2
So we can say that If a
instructions conflict if both concurrent schedule is conflict equivalent to a
|Read(P) Write(A);
consecutive instructions operate serial schedule of
on same data
item same transactions then it is contlict Read(A); A-A*2; |
and from different
transactions
Write (P)
and one of them is Serializable. So schedule S is conflict serializable to
WRITE operation.
serial schedule Write (P) Write(A);
<T, T>. Write (P)
If and
access to different data item D then consider Read(B); B-B+ 100;
following 10.3.2 View
read
all
consequences no conflict as
they only Serializability Schedule R
or
writing different values. 1. Introduction T Write(B)
= READ
T
(D)/WRITE (D), READ =

(P) Read(P) Read(B); B-B*2;


they only reading or /WRITE
no conflict as (P) then View equivalence is less strict than co
onflict
data. writing different Write (P) Write(B);
equivalence, but it is like conflict equivalence on
only the read and write
base Write (P)
operations of transaction
Write (P)
TechKaowledge
TechKuuledge
ICations Pubilcations
gement System (SPPU-Sem -Comp) 10-13
patabaseanagemen
Database Transaction
10-12
tabase iransaction S1e0 3Correspo,
nding serial schedule
10.5
RecoverabilityI Recoverable and No
5-Comp) corre
System
(SPPU-Sem

schedule
Recoverable Schedules
Database Managen equivalent
serial

:
e sS,
Schedule According to ACID properties the schedule
whicn
Keeps database in consistent state after execution of
whole
2. Conclusion schedule is acceptable.
r)
serializable as there it transaction T, fails, then to maintain atomicity of T
Not conflict
precedence graph. above r{y) the system has to undo all the effects made by
Example transaction T are well as other transaction
wy referencing values updated by T For this reason
T Example:
and other transactions depend on T should be
schedule has transactions T, andT, as given
READIA)
w,v), rv), w,lz), w,ty)
below r(x)
aborted.
READB rlz) ollowing types of schedules are acceptable
from
Precedence graph.
READIA 1. Draw
Vviewpoint of recovery from transaction failure.
READ(B 2. Is schedule
conflict serializable or not ? Find
Find respective serial
r wx)
10.5.1 Recoverable Schedules
WRITE (A) schedule. ri2)
Schedule view serializable or not? If a transaction Ta reads a data items previously
3 Is above
rlv) written by a transaction T the commit operation of T
WRITE (C)
Solution: then the
of T2
appears before the commit operation
WRITE (B) r,12), rgM}, Ts(Y), w,0), w,(y), rh w(z)
(1) Step 1: r,(o), r,(2), type is Recoverable
schedule of this
schedule.
WRITE (C)
w,l), walv) wy) Following schedule is not recoverable,
rzt)
S, rsK), ra{V), Wa(Y), rx),
Schedule
Schedule S : Given
Schedule
.Serial
wbtlla), r(9),
walz), w,(v Read(P)
ro) schedule is view serializable or not. Write (P)
41 Step4:Above Read(P)
r(Z) Conditions for view serializability:
As no cycle in graph number of transaction Read (Q)
r(Z) S and S, must have same
be committed before T
(1) -In the above schedule T2 may
Schedule is Conflict Serializable. r(x) and same number of read write operation. In this case if T, fails
as it finishes execution before T.
schedule is given as, then it needs to be
roll back
.. Corresponding serial r(y (2) Initial read operation because of certain reason

wx) Xis read initially by T, in S as well as S,


T o

in S and S, both.
and even l2
committed so cannot
be rolled back
wY) Yis read initially by T, But T2 is already
3. Test for conflict serializability o
will be in
inconsistent state. To
in both S and S, and hence database
serializable ifit produces an
r(y) o Zis read initially by T,
it is to commit T2after
A schedule is conflict recoverable necessary
1. make it
wlz) Y written by T; then S, also
acyclic precedence graph. 3) IfS reads value of X or is committed.
transaction.
w{y) reads value of x or y written by same /Cascaded
Schedules
Example Less
reads value Y written by T3. 10.5.2 Cascade
oS, Aborts /Cascaded Rollbacks
la), w,fa), r,(b), r,lb), w,(b),w,(b) S also reading value of Y
which is written by
(2) Step 2: Precedence graph
Cascading rollback
T a series of
failure leads to
transaction

Read(A) (4) Final write operation A single


transaction rollbacks.
S
T, in S as well
as
X-final write (x) done by series of
failure leads to
WritelA) both. A single
transaction

Y-final write (y) done by T, in S and S, transaction rollbacks.


Read(B) amount of
lead to significant
Sis view serializable. Cascaded
rollback can

Read(B) Or S is view
Above graph show no cycle equivalent of S,. work undone.

Write(B) -Schedule
with T T, and Ts
:.Schedule s, is conflict serializable.
TechKaculedge
Write(B) PUDcations
TechMaolei

Pueilcat
70-14 Databasee
Darabase
Management
System
(SPPU.Sem
5-Comp)

Q. 2 Explain the transaction

state diagram.
ocessing with Transhelapcia
the
APT

Read (D)
a.3 Give an example of a schedule of a
31 ran
11 oncurrency Control
Write (DJ is not conflict señalizable but
view ciona.
write(
Write diagram
serializable ?
tha
UNIT IV
s taied en a4 Explain state transition
In above schedule
if transaction T,
for transaction execution. What
are
the stale
must be rolled back. e desirate
value oroperties of transactions
on T, lo read the S y l l a b u s

T, and Ts depends
Transaction as eking methods, Deadlocks, Time stamping methe
This is called What is transaction ?
T; and T; should roli back. Q.5 Discuss the
so even state
asaded roll back.
cannot
diagram and properties of transactions transitin
Cascade less schedules: cascading rollbacks
of Concurrency Control
Conflict
occur for each pair of transactions T,and T,
such that Q. 6 Explain Serializability ahd 44 Need Time
T reads a data item previoushy
written by T, the serializability. VIew Balance
appears before
the read vanious
neeo or concurrency control t4
A A-10 WRITE (A) 600
commit operation of T Q. 7 With respect to schedule define: Explain
Confilict
operation of T
and confict serializable. equivalent Fxolain various problems of concurrent
executions. t5 WRITE (A) COMMIT 490
Every cascade less schedule is also recoverable. tb COMMIT 490
Q.8 Why transaction processing systems usualy allow
Review Questions concurret executions? Give reasons. Concurrent Executions Problems T&T2 Transaction Y has read the value of Aas 50o.
Transaction Xhas readthe value of Aas 500.
Q1 Discuss the ACID properties of transaction| a9 What is a schedule? vwnat Is a
serializah
erializabe 1. Lost update problem T TransactionY writes the new value of A as 200
schedule?
processin
Transaction X has subtracted 10 from its value
2. Uncommitted dependency problem of Ato produce 490.

3. Inconsistent analysis problem


TsTransaction X updates the value of Aon disc.
T The result of this operation Taperformed by
4. Dirty-read transaction Y is lost.
Transaction X has overwritten the result of transaction Y.
5 . Non repeatable read
Solution
6. Phantom read The problem is avoided by not allowing only one
transaction to update data at a time.

Fig. 11.1.1:Concurrency execution problem 2. Uncommitted dependency problem


1. Lost update problem This problem occurs when user sees data coming from
Update made by one transaction intermediate step of another ongoing transaction
is overwritten byy
other transaction or other user. which is yet uncommitted.

This may loss


updates of one transaction. Time
begin transaction 100
Example 11.1.1
read (A) 100
Time K Balance A=A+ 100 00

BEGIN 500 t begin transaction Write (A) 200


TRANSACTION read (A) 200
s
t2
BEGIN READ (A) 500 A=A-10 Rollback 100
transaction write (A) 190
3
READ (A) 190
A=A+100 500 commit
anagement System (SPPU-Sem5-Com 11-3

Concurrency Contro
Dalabase M a n a

lation property ensures that each transaction must


ensures
Concurrency Control
112
Management
System
(SPPU-Sem
5-Comp)
Dirty Data

mmitted hence
: Data updated
all users
by a transa
reading
ansactoldion,databut not yet a i n
ware of other concurrently executing
Failure to this would
corrupted data.
result in inconsistent ana

transactions.
Database

Example 11.1.2: the


value
or called as dirty
data.
which is concu
current transactions, when several Example
updated of
and read: A transaction reading dirty data i.
Y reads
at
time
data is case
an5actions are
are
executing simultaneously on a
executing I n case of traffic signals only one lane (line) is
ransaction

A (100 + 100 200) and writes


the result
A=100
because
'dirty read. called as not
t ppreserve isolation property for long allowed to pass at a time and other lanes are
updating may
be locked.
X should
and its
changes undone Because
there is always a
chance tnat d a t a b a s e

the
ransaction

rolled back
Y has been Y but this
transaction might
rollback the cha first there be O Similarly, in data transaction only one transaction
transaction

X has used
the result of transaction t h es e c o n d t r a n s a c t i o n reads an invalid
hich causes time

nt
concurrent system must

transactions. can perform operations at a time other transitions


ransaction

transaction Y failed. value. interaction among varic


fo n among
various concurrent

incorrect as read is changes mado are locked.


resut was
In short, dirty done by
using one of the concurrency
Solution:
not allowing
transaction
n
Transaction are 'visible to other parties during a This
can
he

11.2.1 Types of Lockss


is avoided by commits or c o n t r o ls c h e m e s

This problem Y either Whether dirty reads are actually oided


of A until
transaction
schemes are based on serializability
to read the
value or lowing
depends on the database backend used and not the Types of locks
rolls back or its osf
chedules.

configuration.
Inconsistent Read problem
3.
results of incomplete
read
1 Ock
Based ProtocolslLocking a. Shared locks
Transaction reads partial 5. Non repeatable
transaction.
made by other
Methods

read occurs when b. Exclusive locks


transaction update A non-repeatable
a
persistent object distributed
within a same transaction transaction
is read twice oncurrency
controiin
BEGIN Transaction Is used, explain in Fig. 11.2.1:Types of locks
possible that
between the reads, data is o For
manager approach
BEGIN Transaction SUM=0
It is modified dh ted lock replication types of locking to control concurrent
tor dealing with
Ihere are two
transaction, therefore the second
by another read defail different approacnes
R(X) R(X) returns different values as compared to the first.
in distributed lock manager
approach. access
=SUM +X dataitems
X=X-20
SUM
If Transaction Ti reads a row and Transaction
of SPPU-Dec.17, 9 Marks a. Shared locks / Read Lock
R(Y)
WX) SUM =SUM + Y
changes the same roW, when 1 re-reads and sees the oflocking
This type of locking is used by the DBMS
when a
Explain concept
R(Z) changes made by T2,then this is non - repeatable read,
a.
of lock based protocol. transaction wants to only read data without
Z=Z+1 0 a Explain algorithm
performing modification to it from the database.
W(Z) 6. Phantom read (concept of locking) a
can also acquire
Introduction

Another concurrent transaction


COMMIT R(2 Phantom reads means insert or delete action is implementation o f isolation
SUM SUM+Z shared lock on the same data, allowing the other
table row which is referred by another users can access
performed on a environment, many
COMMIT In concurrent transaction to read the data.
transaction. imultaneously; each user feels
same data in a DBMS Shared locks are represented byS.
inserts a row, T, re-reads the query and exclusive access to the
database.
Example 11.1.3:
Transaction T, that he is having a shared lock on
data
ghost row to T, then If a transaction T, has obtained
if T, the additional row, it is
see
a
must have interaction
read data item X,
the values of X, Y and Z.
we
Transaction Ta is adding To achieve such system, item X, then transaction T, can only
T is transfering this is called as Phantom read. concurrent transactions which is also
However, at the same time, transaction amongst those but cannot write on data
item X.

Rs.100 between X and Z. called as Mutual Exclusion.


Example 11.1.4
executions sQLImplementation:
balances of X and Z its book content for concurrent
As transaction T2 has used the old changes to a Mutual exclusion is required
DTP operator makes some
are LOCK TABLE customer IN
final result is incorrect. when the changes of various transactions.
submitted by any author, but
Solution : of the document by
the
Whenever one transaction is accessing data,
second SHARED MODE;
incorporated into the master copy
Lock
by preventing transaction
This problem can be solved department, they find that new unedited matena change data otherwise there Exclusive locks /Write
production transaction should not b.
be done with help the DBMS when a
T from transferring the amount, before transaction T,
has
has been added to the document by the author. may be dirty read problem. This can
This type of locking
is used by
committed. of locking concept. wants to read
or write (i.e. performing8
Solution: transaction
coua that
4. Dirty-read This problem could be avoided if only one editor ransaction can access data if it is locked by update) data in the
database.
some
exclusive lock on
In database transactions, one transaction reads and edit material at a time. transaction. When a transaction has an
of
environment o cannot acquire any type
changes the value while the other reads the value LOCKing is necessary in a concurrent data, other
transactions

11.1.1 Concurrency Control Schemes should not retrieve or update exclusive) on the
data.
before committing or rolling back by the first SUre that one process lock (shared or
a
transaction.
Fundamental property of
transaction is
isolation. record which another process is updating Tech Kaoulede
Pubications

TechKaouleigi
P u b l i t a t i e
Lock by
Transaction

D
DatabasE VdIlagement
Management system (SPPU-Sem5
Etabase Management System

transaction
(SPPU-Sem 5-Comp)

is holding
conflicting lock
OnQ EXplain advance
locking conce pt oncurrency Contr
using 2P
5-Comp) 11-7
lock point
No other
(a)
it.
(1) Introduction locking. Number
(1) Strict
-phase locking
Concurrency Control
(D) No other transaction is waiting on that data item

Two-Phase Locking (2PL) synchronizee Locks


oids cascadedrol
rollbacks. protoc
for locking it. by explicitly detecting and preve read and Shinking
t
requires not
only
11.2.5 Rejecting Locks between concurrent operations. wrte phase exclusive-locks held two-phase locking but also that all
conflicting type of
lock is Before reading
data item X, a
transactin
contlcts Growingp h a s e

Time that by
transaction commitstransaction should be held unti
Lock is rejected when other
read lock on X.
Before Fig.11.3.1 Locking point This
or
abort
held by other transactions.
a
writing int must" own property ensures that if data is
must "own" a write lock on X. A, one
transaction being modified by
f any transaction has exclusive lock for writing
tem D then no other transaction can acquire any type
on data

The ownership of locks is governed


transaction Lockp e
int is end of growing phase tor that
transaction can't read it until(holding lock-X) then other transaction
first transaction
by of shrinking phase. commits.
of lock on data item D. (a) Different transactions cannot two rules and start Strict schedule recoverability.
simultane edule to be serializable, transactions should Not deadlock free.
Lock compatibility matrix will show the locks that will conflicting locks (i.e. WR). The s c h e c
be
their lock points.
be granted or rejected. b) Once a transaction surrenders arranged accordingto (2) Rigorous two-phase locking
lock, it may never obtain owner.
nip of a
when the
transaction
transacti
terminates (or aborts), all protocol
11.3 Two-Phase Locking(2PL) Protocol additional locks.
It also avoids
cascading rollbacks.
The definition of conflicting lock
acks
remaining locks are automaticallyreleased. Some t
Q.A transaction may be waiting for more time for an depends o requires that all share and exclusive locks to be held
of synchronization being performed.
(ate
also require that transactions hold all locks until the
transaction commits.
Exclusive (X)lock on an item, while a sequence
ofother compatibility matrix) er
lock until t e r m i n a t i o n .
So
transactions
trensactions request and are granted as Shared can be
(S)
lock on the same item. What is this problem? How it is
For 'RW
synchronization two locks conflict (3) Advantages commit.
serialized in the sequence they
Both
if,
solved by two
o are locks onthe same data Most of the
phase lock protocol? item. Two phase locking protocol ensures conflict database systems
One is read lock and the other implement strict or

SPPU-Dec 17, 8Marks


o a
is serializability. rigorous two phase locking protocol.
a
write lock
Q How two phase commit protocol to ensure the atomicity For 'WW synchronization two locks conflict if.
in
TwO-phase locking protocol is simple to implement Conservative 2-P Locking Protocol (Static 2PL)
distributed transaction, handles the following failures: Both and understand.
0 Faiiure of participating site
o are
locks on the same data item. t is also called
as static 2P
o Both are write locks.
locking protocol.
(4) Drawbacks
() Failure of coordinator This scheme
requires locking all items needed to
The second lock ownership rule access before the transactions
Ti) Failure due to network partition. causes Deadlock may occur in two phase locked schedule. starts.
transaction to obtain locks in a two every t begins execution
phase manner. Cascaded rollback may occur under two phase by declaration about read set and
SPPU-Dec.17,8 Marks Growing phase locking. write Set of all data items needed
a Explain the Two Phase lock Protocol for Cascaded rollbacks do mean by if one transaction is in advance.
control. Also explain its two
concurrency o Read set : Set of all data transactions lock.
versions: strict two phase In this
phase, transaction may obtain rolling back all
n number of new transactions depends on this
lock protocol and locks but may not release oWrite set : Set of all data than n-calls
rigorous two phase lock protocol. any lock. transaction will be rolied back. transactions
SPPU-May 18, 8Marks Shrinking phase Example
ock.

QDescribe Two Phase Commit (2PC) Protocol. It any one item of abOve list is
currently not available
how 2PC
protocol responds in different ways to Explain
various
Transaction may release locks but
cannot obtain any (A) No 2P (B) with 2P locking.
for locking then lock will not be granted it waits till all
types of failures new Lock. items are ready for locking.
SPPU -May 18, 9Marks 11.3.1 Modified Versions of
Q. Explain the Two Phase lock Protocol (2) Working of 2P Two-phase It is almost free from deadlocks all
ensures coflict
and show how it
protocols Locking Protocol as required items

does not ensure


serializability. Two Phase lock protocol Initially transaction is in 'growing phase'. It acquires
are listed in advanced.
freedom from deadlock Versions of
necessary example .Also explain its two explainw locks as needed. Once
it starts releasing locks it enters Two-phase Locking Protocol 11.4 Concept of Deadlock
two phase lock versíons: strict into the
protocol and rigorous two "Shrinking Phase' and now it may not dcqu
protocol. phase iock any lock after
shrinking phase starts. 1 . Strict two-phase locking protocoi
is said to be in a state of deadlock
system ifthere
Q Describe SPPU-Dec.18,9 Marks
Two Phase Commit he point at which transaction obtains final oCK
exists a set of transactions such that every transaction in

how 2PC (2PC) Protocol.


Explain is called
(last 2 . Rigorous two-phase locking protocol the set is waiting for another transaction to complete its
protocol responds in different as lock point of transaction. execution.
types of failures like site falure, ways to various
network parüition. coordinator failure and Conservative 2-P Locking Protocol (Static 2PL Example:
SPPU-Dec.18, 9Marks 9 11.3.2: Versions
of Two-phase Locking ProtOCO Consider two transactions given below:
TechKnowl4

ublicati Teciklo
11-8
Concur Contro Dalabase
Management System (SPPU-Sem
Manage
Comp) 11-9
5-Comp) two principle methods to Concurrency Contro
(SPPU-Sem
There are
o k
handle t
trra
an ca c t i o n
Tj requires that or
deadlock for ns
System test for
Management
write
data on
dation
validation
t est
When T, wants to hold data item, currently hold by
system, inN Ti wwith
i t h TS (T)< IS ( then one of the
then
se
transaction first read and read
and
wrire
The fi then T, is allowed to wait if and only if T, is younger t
(a) Deadlock prevention transaction

'his
performs must be hold
hold.
after that
data item X, then
all conditions

otherwise T, is rollback (wounded).


deadlock prevention
on data item Y. We can use

that the system


will never enter a
echnique to
deadlock state.ensur
following
Finish
(T) <start

serializability should
(T) as T, finishes before
be maintained.
ConsiderT T T, transactions.
a) the
Read
(X) (b)
Deadlock
detection and recovery
its write phase before T, starts its
requests for data item hold by Tzthen data item is
the system to enter a
mpletes pre-empted from T, and given to T, and T, is rollback.
Write( (X) We can allow deadlock
stata and
then we can detect such state by deadlnele
detection D1dation phase (Start (1,) <tinish (T) <Validation f T requests for data item hold by T, then T need to
Read ( techniques and try to recover from roll back.
Write (Y
then write
data on
using and deadlock recovery scheme.
deadlock state by res writes of both transactions do not take
Prevention may lead to starvation
transaction first read and write
of transaction,
Both of above methods may result
'This time.
performs
read and
in at
same
they are rollback again and again. But both schemes
d a t a ftem Y, then after that
rollback.
transaction place
o f T, n o t
affected by writes of T, and T, can't wait-die and wound-wait avoid starvation by making
on data item X.
Read is maintained.
Deadlock Prevention is commonly used so serializability use of timestamps.
fect read of T,
deadlock occurs in he
probability that the system is high
3 Prevention and transaction 11.4.2 Deadlock Detection and Recovery
Read(Y else detection and recovery are more
Approach 3
probability of deadlock occurrence is less.
ificient i
Write
r o l l b a c k s

Introduction
Pre-emptive Technique
Read 11.4.1 Approaches for Deadlock Prevention When system is having deadlock detection and
transaction
T, wants to hold
write Pre-emption
means,
i recovery techniques, the detection is done periodically
1. Approach 1 then system may preempt
two transactions are executing using lock on data
item hold by T, to check whether the system is in deadlock, if yes then
Consider above A simplest form, in which a transaction acquires it back and
all previous locks) T, by rolling the recovery techniques are used to resolve this
lockingprotocol as below lock (UNLOCK
on all data items which will be required by on that data item. deadlock.
transaction granting lock to T,
at the start of execution. it is effective as This can be done with help of some deadlock detection
other Transaction can be assigned a
Lock-X(X) transactions can't hold lock on those data items till
To control Pre-Emption,
algorithms.
Read ( first unlocks data item. unique timestamp.
To achieve this, system must do the following:
Write (X) System wil use this timestamp to decide whether to
Disadvantages (a) System should maintain information about
Lock-X(Y) wait or rollback transaction.
() It is difficult to know in advance which data items current data items allocation to transactions and
Read rollback
need to be locked. The transaction keeps its old time stamp if it is requests to be satisfied.
Write (Y)) and restarted.
Wait for transaction T, to Uniock Y (i) Data utilization is very low as may be unused data (6) Algorithm that uses this information to detect
Lock-X(Y
items locked by transaction. Various deadlock prevention techniques using deadlock.
Read(
timestamps, to be applied after detection
Write (Y) 2. Approach 2 (c) Recovery techniques
of deadlock.
Lock-X(X) Wait fortransactionT, to UnlockX 0) Wait-Die
This approach uses timestamp ordering of dataitems
Read (X) t is something like tree protocol and every transaction his is Non pre-emptive technique of deadlock 1. Deadlock detection
Write (X) have to access data item in given sequence only. The prevention. Deadlock can be detected using directed graph called
So in above schedule
consider two transactions variation of this approach with two phase protocol as wait-for-graph.
below transaction T, is given When transaction T, wants to hold data item, currently
waiting for transaction T, to a5Sures deadlock prevention. Order of data items must
be seen as V is of vertices i.e.
unlock data item Y and transaction hold by T, then T, is allowed to wait if and only if it is The graph G =
(V,E) can
T, is waiting for be known to transaction. and E is
transaction T,to unlock data item X. every older than set of transaction in execution concurrently
T, otherwise T, is rolled back (die).
o have
So system is in a deadlock state
concurrency control, two phase locking requests for data item hold by T, then TS
set of edges.
transactions T,and T, such that,
as there are set of protocol is used which will ensure locks are requeste TS (T,) so
as
(T, Such that edge T> T, if T> T is present
in graph it
both are
waiting for in right order. T should wait. shows that, transaction T, is waiting for transaction T
cacr otner state. to complete. This state is called
as deadlocktransaction i) Wound-Wait
Timestamp ordering is determined by validatio to release a data item it needs.
e. Ts (Ti)= validation (Ti) to achieve serializabinty Th If cycle is present in wait-for-graph
then deadlock is
Fre-emptive Technique of deadlock prevention. deadlock.
present and
transactions in cycle are
TechKaowledg

PubiC*
TechKnouBedge
PuDIlications
System SPPU-Sem 5-Comp) 11-11
Concurrency soniConrtoel
a n a g e m e n t

5-Comp) 11-10 atabase


Database Management System (SPPU-Sem concept of Timestamp
How many data items it may
need
oNumber oftransaction to be ahead? 11.5.7

d timestamp is assigned at start of exe Working Concurrency Contro


rollback. 1fixed 2cution of (a) For
(b) Rollback r a n s a c t

tion. Every transaction , has been


i o n .

transaction T, to execute
assigned READ (X)
a timestamp by database system denoted as TS (T). Operation
Once victims are decided then If TS (T)<W
timestamp (X)
-

there re
do sO. two transaction
which has entered in
system recen nen T, is
trying
Fig. 11.4.1: Wait-forgraph with
a cycle Ways to A
timestamp. if transaction T, starts after by other transaction.
to
read value of X that is
overwritten
Total rollback: The
transaction is T,
To detect deadlock, system must
maintain wait-for-
restart it. aborted and TS(T)
TS (T) W
timestamp (X)
then
-

then,
that =
149
graph and periodically invoke an algorithm dock is used
(Recent Write)
Partial rollback: Rollback the only trar
as
timestamp 1.e.
system time
searches cycle in the graph. is needed to break the deadiock. yransaction Tenters system or a
logical counter Operations
But this approach needs to
can be use as timestamp and incremented after every 148 READ (X) TS (T)< W timestamp (X)
-

record
2
information like state of running transactions more a s s i g n m e n t . i.e. 148 < 149
data item held by them, and
deadlock On TS(T) TS(T), then system must ensure that (W-Timestamp)
algorithm specifies pointsup to which tranection :lizable schedule is equivalent to a serial schedule 149 Uniock WRITE (X)
be rollback and recovery method has to roiltton to | Record W -

timestamp
Fig. 11.4.2: Wait-for graph with no cycle
After sometime transaction asTy (X)=149
So this READ is
If no cycle is present it mean no deadlock in system. transaction.
resume; partial Everydata item X is with two timestamp values rejected (as T, is already performing
write operation on data so no other
fdeadlock occurs frequently, then detection (a) W-timestamp (X) operation can be
(c) Starvation performed by any other transaction) and
algorithm should be invoked more frequently problem T, is rolled
in this scenario is the data items locked by deadlock
t denotes the largest timestamp or any transaction back
It may happen every time same
transaction is s
transaction will be unavailable until the deadlock is as victim and this may Selected that executed WRITE (X) Successfully on given data ifTS (T)2 W-timestamp (X)
lead to
starvation of that
that item X. Then READ executed and set
problem. transaction (minimum cost transaction
This may tend to more cycles in graph degrading every time).
it selecte That mean it is timestamp of recent WRITE (X)
R-timestamp{X) =
max {TS (T R-timestamp
capacity of granting lock requests. System should take care thatevery time same
operation.
S.
transaction should not be selected as victim. of next WRITE Operations
Recovery from deadlock So it will On execution (X) operation (0,),
not be starved. w-timestamps will be updated to new timestamp of O, 48 *
WRITE Record W - timestamp (X) =
When deadlock is detected in the system, then system
ie. TS (O,). (X) 148
should be recovered from deadlock using recovery 11.5 Timestamp Based ProtocolsiTime
schemes. (recent write)
Stamping Methods (b) R-timestamp (X)
A most common solution is roliback one or more 149 | READ *** TS (T2W timestamp X)
Denotes the largest timestamp of any transaction that
transaction to break the deadlock. Q. Suppose a transaction 1 iSsues a
read command on (X) Le. 1492148 (W-Timestamp)
executed READ (X) successfully on data item (X).
Methods for recover from deadiock data item. How time-stamp based protocol decides Record R-timestamptX)= 149
That mean it is timestamp of recent READ (X)
whether to allow the
(a) Selection of victim
operation to be executed or not operation.
uSing 150 |
time-stamp based protocol of concurrency On execution of next READ (X)operation (O),
If deadlock is detected then control
a transaction one or more SPPP- Dec. 17, Dec. 18, 9 Marks Ktimestamps will be updated to new timestamp of O, 151 READ TS(T)2W timestamp(
transactions (victims) to be selected to break theQ What do
deadlock.
you mean by time stamp-based protoco ie. TS (O,). (X) ie. 1512 148 (W-Timestamp)
EXplain timestamp modeling protocol 11.5.2 Record R-timestamplX)
Transactions with minimum cost should be selected
Introduction
Timestamp ordering -
Protocol max{149,151)
for rollbacks.
nis protocol ensures any conflicting READ or WRITE iS
Cost To achieve order of transactions 151
can be detected by following factors. serializability o executed in order of timestamp.
o For how much time execution can be decided in advance using its tm (6) If transaction T, execute WRITE (X) Operation,
transaction has computed and which transaction entered in system.
Dy any reasons, if transaction is aborted then on
R-timestamp (X)
how much time it needs to do.
stamp Etarting, new timestamp is assigned. IfTS (T) <

which is not needed


has produced value of X
A e
o How many data items it
general method to achieve this is using Then T,
has locked? ordering protocol. now so rollback T,

TechPublications
Knouledge
TechkaOl
11-12
Management System (SPPU-Sem 5-Comp) patabase MEnagement.System (Se
dsse
11.6 Thomas' Write Rule Currency Control Management
PU-Sem 5-Coomp)
TS Operations
a5e

timestamp (D 11-13
148| Q. Explain Thomas write rule with algort S (T<R-
producing value of
D, which 11.7 Optimist Methode
149 WRITE(X) orithm. needed
/5
TS (T)<R-timestamp (X) currency Control
i.e. 149 151 (R-Introduction
he
prevou.
not now Assuming it is never produced Based Protocol ods -Validation
reiects WRITE
systemrejects
and T,is roliback,
Timestamp Thomas Write Rule is also 1. Introduction
Reject WRITE roll back T,
timestamp protocol. known as Operations
When
150 ****

Thomas Write Rule uses view Modified ***


maximum
only then the numbers of
151 READ Record R-timestamp(X) = serializabilituty. rate of transactions are
(X) 151
It generates schedules which are
protocols.
not poceit TS (T)<R
-timestamp (X) many conflicting transactions are lowread
transactions can read data as
(Recent READ Operation) 9/
WRITELX

IfTS (T)<W- timestamp (X Generated schedules that are


other i.e. 149<151 (R-timestamp) t
may increase overhead, simultaneously.
view scheme for to reduce this
Then T, is trying to write obsolete value of X, So
serial schedule.
equivalent to tha Reject WRTE roll back
T will monitoring the system is overhead
rollback T, Example: give
knowledge of required, which
conflicting
also called as transactions
This Method is
TS 150
Operations READ (X)Record control or
optimistic methods foroptimistic concurrency
148 READ (D) R-timestamp(X) =151|| 2. Working concurrency control.
(Recent READ Operation)
149 WRITE TS (T)<W-timestamp X)
WRITE (D) We can
< W-timestamp (D) assume that transaction
(X) FTS (T) T executes in 2 or 3
i.e. 149<151 (W-Timestamp) WRITE (D) Then T, is writing obsolete or outdated value of phases, in its lifetime.
Cannot D so
write The above
as
other schedule with 2 WRITE is ignored. Generally, Transaction
transaction using data X for transactions T, and T, goes through 3 phases and
As T, starts before T, so concurrent transaction
be in
writing timestamp TS (T,) <
TS (T
Operations time.
can
different phases at a
150 T, executes READ (D), and then
T2 executes 148
Now W-timestamp (D) TS =
WRITE (D1 (a) Read phase
151
WRITE (T2) so when
Record W-timestamp(X) =
151 WRITE (D), but TS (T,) <W- T, executes 149 WRITE ** TS (T)< W -timestamp (X)
(X) timestamp (D), So WRITE (ID Transaction reads values of
of T, is rejected and i.e. 149< various data item and
T, is rolled back. 151 (W-timestamp stores them in local
variable
cOtherwise, system executes WRITE (X) and sets But this Cannot write Pertorm writes
W-timestamp (X) =TS (T) rollback is
unnecessary. Since T, has
as other on
temporary values not actual
written value of D and is already transaction using data X for database.
TS T, trying to write value which writing.
Operations will never be read. (b) Validation phase
150
So any time if Transaction performs validation
151 WRITE (X) T, with TS
(T) < TS (T,) trying to READ test to check
whether
Record
W-timestamp(X) 151 will be rollback as TS (T) < W (D) 151 WRITE Record it can
copy temporary
=
W-timestamp(X) =
151 values which writtenin
are
11.5.3 Advantages transaction T, with TS
timestamp (D). Any X) previous phase to database without violating rules of
TS (T)> (T,) should read value of ) Otherwise serializability.
This protocol ensures conflict
DbyT
conflicting operations serializability, as So such WRITE
WRITE (D) is executed and
W-timestamp (D) TS
(c) Write phase
are
processed in order (D) operations (as in T) obsolete
=

(
timestamp of operation. of and should be
are
TS Systems performs write to actual databases otherwise
Ensures that it is
ignored. Operations rollback transaction.
free from deadlock. 130
Thomas' Write Rule 3 timestamps associated with any transaction is,
11.5.4 Disadvantages
Toachieve this O1 WRITE(X)|.Record W-timestamp(X)= 151 (a) Start (T): Time when transaction (T) starts
Starvation is possible for functionality timestamp ordering
protocol is modified which is Lompare to Basic execution.
transaction conflicts with it long transaction if short Rule.
called as Thomas Write Timestamp ordering8
(b) Validation (T) Time when transaction (T)
transaction again causes
restorative Unlike, timestamp
and again.
of long
Rejects few write
protocol, Thomas write rule
SKS to ignore write operation if T, issues WRITE finishes read phase and starts validation phase.
It may not give (D) operations by modifying cec
recoverable schedules. for WRITE(D).
(DJand TS (T) <W- timestamp (D) (c) Finish (T): Time when transaction (T) finished its

Suppose, T,issues WRITE (D) write phase.

Tech Kaoui
TechKrouledae
Pubiications
5-Comp) iel*
mp) ourrency Control
Explain Two phase locking.
(SPPU-Sem
Management System Q.3
Yatabase
Review Questions

understand by
concumency
controi r
Q.4

Q. 6
Explain time

List and explain


stamp based

variouS
otocols.

issues
while transactions
whil
12 Recovery Methods
running concurrently in DBMS.
Q.1 What do you serializability
conflict are
and
Epiain view serializability UNIT IV
with proper example. Explain
two phase cking
lockina protocol.
controlled
where it can
6
advantages of this protocol.
Also St
What is concumency
? If not control
methods to
What are the Syllabus
ead to?
Shadow-Pagingand LOg-Based Recovery, Checkpoints, Query Processing, Query
concurrency ? O00 Optimization, Perfomance Tuning.

Database Recovery Concepts


backup media
recovery
IS the process of restoring the database failure
Database
state it was before
database
to original (correct) as
100 200 300 400 00
database failure occurs. SCN

solving any type of database failures,


The process of
without data loss and keep database
Quickly and Archived

database recovery.
redo logs
available is called redo log &&
back up o
element of database recovery is the most databasee
The main

recentdatabase backup. If you maintains database


then database recovery is very
backup efficiently,
straight forward process. Recover (redo changes)
database Hecovered
(media failure) database
Example: To recover data from system having full

backup option is as below, Fig. 12.1.1

need
Restoring entire system to a certain point in time To understand concept of database recovery we

WOuld require locating the time when last full backup to understand below terms

taken and all the incremental backups that cover the a. Database Backup

period of time between the full backup and the b. Database Failure

particular point in time to which the system is Database recovery algorithms


transaction executions ensure that
Supposed to be restored. (a) During normal
is backed up to allow
information
enough
recovery from possible failures.

ensure that database consistency,


(b) Data should
transaction atomicity, and durability.

recovery phases
database recovery/
Types of
recovery
Forward database
(a)
database recovery
Backward
(b)
Dataoa5C

se
anagem
Management ystem PPU-Sem 5-Comp) 12-3
5-Comp) 12-2
atabase Management System (SPPU-Sem
o The time or
recording varies
Recov Methods <ume
25Su
that every log record i
stable storage
tten to the end
log is Example:
operation on
as
Database recovery techniques soon as Recovery Methods
(a) Log based recovery (
checkpoint algorithm.
Completion record
according to of
the
reated. Consider
simple banking system.
(b) Shadow paging recovery Records all work has been done ed-Modification Technique action
that transfers Rs.50 be

(c) Checkpoints transaction.


for this particular 12REDO Algorithm) account B: from account A

Fields in transaction log 1.Introduction


12.2 Log-Based Recovery read(A)
To ensure atomicity despite failures we uses Recovery It has these fields:
The d e f e r r e d - m o d i f i c a t i o n

technique ensures A -A-550


Q. action omicity by recording database
Methods. Explain in detail Log-Based Recovery (a) Transaction identifier: It is the
nique modifications in the transaction iog files, but all write writelA)
SPPU -May 18, 8 Marks
performed identifier ot
method. the transaction that
operation.
h of
operat
transaction is done after
transaction read(B
Introduction write partialy commits.

(b) Data-item identifier: it is the B-B+50


oatial commit when the final action
There can be problem in accessing database due to any
the data item writtern.
unique
identi the
Typically, it is the l partia been executed a transaction write(B)
reason can causes a database system failure. on disk of the data item. ransaction has said to be Let be a
partially c o m m i t t e d . transaction that withdraws Rs. 100 from
The most widely used structure for recording database account C.
(c) Old value : t is the value of the
modifications is transaction log (Log). data item nrin ersion of the deferred-moditication technique
the write. orior to
The log is a sequence of log records, recording all the hat we describe assumes that serial
execution of read(c)
(d) New value: It is the value
that the data item. transactions.
update activities done on the database by all database have after the write. m will CC+100
users.
when a transaction partiaily commits, the information
12.2.2 Working of Log Based on the log associated with transaction is used in write(C)
12.2.1 Types of Transaction Log
Protocol ecuting the deferred writes. it the system crashes Suppose that these transactions
are executed
-

There are some special log records in theorder T, followed serially,


There are several types of log records. exist to before the transaction completes its execution, or if by T, and that the values of
events during transaction processing, such record
accounts A, B, and C before the
(a) Update log record
as the star
tart
the transaction aborts, then the information on the log execution
took place
of a transaction and the commit were Rs.100,
or abort of will be ignored. Rs.100, and Rs.100, respectively.
A n update log record describes a single database transaction.
The portion of the
2. Working log containing the relevant
write. We denote the various types of log records information on these two transactions
as The execution of transaction T, proceeds as follows: asappears
It also includes the value of the
bytes of page <T, start>: Transaction T, has started. below,
before and after the page (a) Before T, starts its execution a record < T, start>
change. <TnX, V V2>: Transaction Ti has performed awrite
(b) Compensation log record
is written to the log. <T start
on data item
X X, had value V, before the write, and (b) A write(X) operation by T, results in the writing of To A, 50
Compensation log record the rollback of a will have value V, after the write.
a new record to the
particular change to the database. log. SoB, 150>
<Tpi commit>: Transaction T, has committed. c) Finally, when T, partially commits, a record <
Each corresponds with exactly other Tn
one Update <T,abort>: Transaction T, has aborted. commit> is written to the log and the records l Commit
Log Record.
Whenever a transaction performs a write operation, it associated with it in the log a used in T start
executing
(c)Commitrecord is essential that the
log record for that transaction the deferred writes.
Records a decision to commit a transaction. should be created before the database is modified Dy 0) Since a failure
ST C.200
(d) Abort record may occur while this updating
t
taking place, we must ensure that, before the TCommit
Records a decision to abort and hence rollback Once a lo8 record exists, we can write the modification Start of these Fig. 12.2.1 Database log corresponding to T, an T,
updates, all the log record are
transaction. to the written out to stable There are various orders in which the actual outputs
database only if it is desirable. storage.
(e) Checkpoint record can take place to both the database system and the log
Undo operation can be done for modification that nas Once they have been written, the actual updating and shown
oRecords a point when checkpoint has it oy takes as a result of the execution of To T. as

been made. already been done to the database. We undo place, and the transaction enters the
above.
These are used to speed up using the old-value field in log records. Committed state.
recovery. The value of A is changed in the database only
after the
o It also record For ystem Ooserve that only the
information that log records to be useful for recovery from newvalue of the data item in the log.
eliminates the record <T A, 50> has been placed
need to read a log's past. and disk failures, the log must reside in stable sto age.
equired by the deferred modification
technique. Tech Knewledge
PUDIlCtons
nowledge
Database
Management system (SPPU-Se
managem

Database Management System


(SPPU-Sem 5-Comp) 6
previous consistent state after acovery Methods is executed
5-Comp) 12-5
the transaction had operationTO, the
Database completed. A T t e
this
values A112.2.4 Recove Methods
Let us return to our banking example
and Bare Rs.50 and Rs.150, respectively.
Immediate Modifica ion Technique
(UND Algorithm)
To start Ta and T, executed one after the with transactlons
with
alue of
account C remain
before, the log|
other in the h e

1.
ToA,50> followed by T. Earlier figure shows
the logorder
those
(0 of the incomplete ransaction T, can be introduction
results from the complete execution ofT. from the log. The immediate-modification technlquue
TB 150 > and T. deleted
database allows
TCommit> T% start To starts when the
modifications to be written to the database
transaction is still in the
A 50 ToA, 50 To. A 50 (Running state) active state.
B 150 o B. 150 <To B,150 Data modifications
written by
active
called uncommitted modifications. transactions are
T Start>
Fig. 12.2.3: Same log at different To Commits -

In the
event of a crash
TC, 200> times no commit recorded <T, starts system must use
or a
transaction failure, the
the old-value field of
the log records
T,Commit> [Method 2: T C 200
to restore the modified
data items to the value had
prior to the start of the
C 200 (A) System crashes berore the transaction.
completion TCommit 2. UNDO operation
transactions he
Fig. 12.2.2 Fig. 12.2.5
(a) Assume crash OCCurs just after the Before a
transaction T, starts its execution,
log record tor the
Using the log, the system can handle any failure that
the step WRITE(B) of transaction crash occurs just after the log record < T commit: writes the record systemn
results in the loss of information on volatile storage.
TO has
been <T, start> to the log.
written to stable storage. to is stable storage
is written During transaction execution, any
The recovery scheme uses the following recovery WRITE(X)
(b) When the system comes back up, no redo (al The log at the time of this crash is as in (c) the operation by T, is preceded by the
procedure. to be taken, since no commit
action writing of the
record appears in system comes back up. appropriate new update record to the log.
thelog.
( Method 1: (b) Two commit records are in the log: one for T, and
When
T partially commits, the system writes the
(c) The values of accounts A & B remain record <T, commit> to the log.
OUse two lists of transactions: the committed Rs.100and one for To
transaction since the last checkpoint and the Rs.100, respectively.
Since the information in the
log is used in restoring the
active transaction. (d) The log records of the incomplete T, c)Therefore, the system must perform operations
can be original database state, we cannot allow the actual
deleted from the log. redo (To) and redo (T,) in the order in which their
Apply the REDO operation to all the WRITE update to the database to take place before the corre-
operations of the committed transactions from commit records appear in the log.
<lo start sponding log record is written out to stable storage.
the log in the order in which they were to the log. (d) After the system executes these operations, the We therefore require that, before the execution of an
<To A, 50
Restat the active transaction. REDO(T,) sets the values of accounts A, B, and C, are Rs.50, Rs.150, output (B) operation its log records is written to stable
value of all data items updated by transaction T To B, 150 and Rs.200. storage.
to the new values.
Slo commit Finally, let us consider a case in which a second system This procedure is defined as follows
oThe set of data items updated by T, and their
crash occurs after
<T, start recovery from the first crash. (1) Use two lists of transactions maintained by the
respective new values can be found in the log.
system;
oThe redo operation must be T C, 200 Summary
executing once. (a) Committed transactions since the last
After a failure, the recovery subsystem consults ror each commit record
<T, commit>found in thelog
o
Fig. 12.2.4:<T, commit> recorded checkpoint
the log to determine which transactions need to tne system
(B) The crash comes just after the log record
performs the operation redo (T,). In other (b) Active transactions
be redone.
wOrOs, it restarts the recovery actions from the the active
been Undo all the WRITE operations of
o Transaction T, needs to be redone if and
only if (3) For the step WRITE(C) of transaction T1 has (2)
the log contains both the record <
beginning. transaction from the log, using
the UNDO
T, start> and written to stable storage.
nce
the record<T, commit>. on
redo writes values to the database independent procedure.
(0) When the system comes back up, the opera of the committed
Thus, if the system crashes after the values currently in the database, the result of a (3) Redo the WRITE operations
ecord
transaction redo (To) is performed since the transaction from the log in the order in which
completes its execution, the recovery scheme uses the
esstul second attempt at 'redo' is the same as
written in the log, using the REDO
the log the disk. they were
information in the log to restore the system to a
commit> appears in on
unough 'redo' had succeeded the first time.
procedure.
TechKsoeldgi Tech Knouledga
Pudicat1ons
P O D I O
a t a v a s ei W a n a
ement System (SPPU-Sem 5 omp) 12-7
comes back
the system , it finds Recovery Methods
-omP 60 Tle, tne system can handl
Recovery Methods When
t h e r e c o r d
To start> in the log. but no
T starts
Using the log le any failure <lo Commit> record,
(SPPU-Sem
System corresponding
Management
result in the loss of i TA, 100,50
atabese

UNDO operation consists of


thatdoes not
volatile storage.
nformation in non Thus,
transaction
To must be undone, so an
T B, 100, 150>
performed.
a WRITE
operation,
T reading
Old
recovery
scheme uses two recoy
ery procedures
undo ( is
Undoing of write The
its log entry
of item X in
result, the values in accounts A and B
Commit>
the value
e x a m i n a t i o n

value and
setting Method 1: O lnn the disk) are restored to Rs.100 an
T, start>
value,
new
which s
the berore()
value
to old
the database
(a) Undo(T,)
restores the value of all d
data i
Rs.100, respectively.

ems
TC, 200, 30
image. from one
updated by transaction T, to the old
number of WRITE
operations
alues and <To start T commit
redo(T) sets the value of all data items
Undoing a
must proceed
from the log
or more
transactions

in which
the
the updated Tor A, 100,50 Fig.12.2.8
by transaction T,
the order to new values,
in the reverse order from C) If crash
in the log just after the log record
occurs
<
The set of data items updated <To, B, 100, 150
written
operations
were
(b) by T, and commit> has been written to stable storage.
their
Example: respective old and new values can be found in the <lo Commit> When the system comes to backup, both To
with
transactions o
simple banking
system, log. and T, need to be redone, since the records
Consider a
in the order To
after the other <T, start To start> and <T, commit> appear in the
and T, executed o n e
(c) The undo and redo operations must guarant
to
folilowed byT correct behaviour, even if a failure occurs log, as do the records <T, start> and <l

possible order
of execution
in both
during T C, 300, 200 commit>.
Fgure below shows of the recovery process.
as a result
of the execution Fig. 12.2.7
the database and the log After the system performs the recovery
d) After a failure has oCCurred, the recovery scheme
T and T occurs arter the log record for the procedures and REDO(T,), the
REDO(T)
comes
consults the log to determine which transactions b) if crash transaction T, has been written values in accounts A, B, and C, are Rs. 50,
start
need to be redone, which need to be undone: step write (C) of
Rs. 150, and Rs. 300, respectively.
T A, 100, 50 to stable storage.
o Transaction T, needs to be undone if the log
comes back up, two
TB, 100, 150> When the system 12.3 Recovery Related Structures
contains the record < T, start>, but does not
actions need to be taken.
<T commit> contain the record <T, commit>.
recovery Checkpoint
UNDOT) must be
<I start> The operation
o Transaction T, needs to be redone if the log o
since the record <T, start»|ntroduction
performed,
C100, 200 contains both the record < T, start> and the
but there is no record A database checkpoint is where all committed
appears in the log,
<I commit record <T, commit>. transactions are written to the redo/audit logs.
<T, commit>.
-In our banking example, with transaction To and T, ex the frequency
be administrator determines
REDO(T) must The database
ecuted one after the other in the order T, followed by o The operation
volume of transactions.
Log
Database
contains both the of the checkpoints based on
performed, since the log
occurs, we must
consult the log
record <T, start> and the record T When a system failure
T,start <T start>
those transactions that need to be
to determine
<, A 1200, 950> 50>
commit>.
need to be undone using above
To, A, 100, redone and those that
the entire recovery
TB, 2000,2050> To, B, 100, 150
At the end of
A, B, and files.
procedure, the values of
accounts
A 950 affect the performance.
Fig. 12.2.6 checkpoints can
C are Rs.50, Rs.150, and Rs.300, Too frequent
B 2050
Note that the UNDO(T,) in This Approach
(10) Method 2: respectively. 12.3.1 Problems
<T Commit

the completion
of tne
operation is performed before the redo(To).
(a) f system crashes before process is time-consuming.
start The search
to our
transactions I n this example, the same outcome would transactions that, according
C,700, 800> occur Most of the have already
that the crash result if the order were reversed. redone as they
First, let us a s s u m e need to be
step or
<T, commit> record for the algorithm,
just after the log of doing undo into the
database.
to stabie However, the order updates
has been
written written their
C800
transaction T, operations,
operations first, and then redo
storage. u D l I C a t i o n s

Is important for the recovery algorithm.


TechKaowledg

PubIie
ase Management System
Management System (sPPU-Sem5-Comp) 1 PU-Sem 5-Comp) 12-9
Database
12.3.2 Need of Checkpoints
Once the system has identified
respect
ecovery Methods shadow Paging
Tothe redo and undo
to beransac.
operations
To reduce these types of overhead, we introduce
only for transaction Tn and all transact
need ntroductio Recoveryy Methods
applied page 5
old)
checkpoints. executing after transaction T
to
that nvenient to
maintain logs page 1
During execution, the system maintains the lo8,
using
The exact recovery operations to be
started tions
ransact
for the purposes of reco
covery.
of all
page 4
one of the two techniques. perfor
erformed depend to
alternative is t o use a system of shadow
An

The system periodically performs checkpoints,


with onthe modification technique
being paging. page 3
used. i where the atabase is divided into pages that
following sequence of actions : -For the immediate-modification This is Current Directory
L Output all log records onto stable storage which recoveryoperations are: technique, the maybe.
stored in any order on the disk.

ye
Shadow Directory
(Stable Storage)
ntify the location or
are currently stored in main memory. o For all
transactionsk in T that
have
n o r d e rt o
identit

page table.
any given
page, we
2. Output to the disk all modified buffer blocks. T, commit> record in the log, execute $omething
called a

UNDo Fig.
3. Output onto stable storage a log record o For all transactions Tk in T such
ce

(h)
12.4.1:Page table -shadow paging
that
he
1 2 4 . 1 O v e r v i e w

Looking at below
<checkpoint>. T commit> appears in the
log, executaecord diagram we see how these tables
appear during a
iransactions are not allowed to perform any update
actions, such as writing to a buffer block or writing a |
Obviously, the undo operation does not
need
REDOIT). had considers the database is made up of a
transaction. As we can see the
page table shows the shadow

deferred-modification technique pages.


when the
.
size state of the database
applied of f i x e d
to a
transaction, and the current page table just prior
number
iog record, while a checkpoint is in working state. being employed. is irectory with n entries is constructed which the
state of the shows the
The presence of a <checkpoint> record in the log Consider the set of transactions database during or after
{To T 0oints to the database page on disk. been completed.
a
transaction has
alows the system to restructure its recovery 10
executed in the order of the
subscripts. Suppose is kept in the main memory.
procedure. This directory 12.4.3 Process of
the recent
checkpoint took place during the eot ot too large and all references read and write to
Recovery
of transaction Te. Thus, only transactions T..T
7Tn
We now have
12.3.3 Working disk. system whereby if we ever want to
a
need to be considered during the database pages
on
undo the
recovery schem actions of a transaction all we have to do is
Consider a transaction T that committed prior to the Each of them needs to be redone if it has recover the shadow
otherwise, it needs to be undone.
committed: 124.2 M e t h o d page table to be the current page
table.
checkpoint.
bl During the life of a transaction two page tables are AS Such this method makes the shadow
For such a transaction, the <T, commit> record appears 12.3.4 Advantages page table
maintained as below, particularly important, and so it must always be stored
in the log before the <checkpoint> record.
(1) A Database storage checkpoint keeps track of block on stable storage.
() Shadow page table (i) Current page table.
Any database modifications made by transaction T, change information and thereby enables incremental On disk we store a single
pointer location that points to
must have been written to the database either prior to database backup at the block level. b) When a transaction begins both of these page tables the address of the shadow page table.
point to the same locations (are identical).
the checkpoint or as part of the checkpoint itself. Thus, (2) A Database Storage Checkpoint helps recover data This means that to swap the shadow table for the
at recovery time, there is no need to perform a redo from incorrectly modified files. (o) During the lifetime of a transaction the shadow page current page table (commiting the data) we just need

table doesn't change at all. to update this single pointer (very unlikely to fail during
operation on T (3) A Database Storage Checkpoint can be mounted,
this very short fast operation).
allowing regular file system operations to be
After a database failure has occurred, the recovery 6) However during the lifetime of a transaction update
In case of no failure means while committing
performed, Mountable Database Storage Checkpeints values etc. may be changed.
scheme examines the log to determine the most recent transaction just discard the shadow directory.
can be used for a wide range of application solutions
transaction T, that started executing before the most For pagesupdated by the transaction, two versions are multi-user environment with concurrent
that include backup, investigations into data integrity, e In case of
incorporated
recent checkpoint took place. kept. The old version is referenced by the shadow logs and checkpoints must be
staging upgrades or database modifications, and data transaction,

replication solutions. directory and the new version by the current directory. in shadow paging.
It can find such a transaction by searching the log
backward, from the end of the loE until it finds the ) So whenever we update a page in the database we 12.4.4 Advantages
12.3.5 Disadvantages Undo or
first
ccheckpoint> record (since we are searching always write the updated page to a new location. does not require any
to Shadow page method
be used
backward, the record found is the final <checkpoint (1) Database Storage Checkpoints can only Redo algorithm for
recovery purpose.
Ihis means current page
restore from logical errors (E.g. a human error) 15 that when we update our
record in the log): then it continues the search
(4Because all the data blocks are on the same physicu relect the changes that have been made by Recovery using this method wi.
records.
backward until it finds the next <T, start> record. This for writing log
cannot be that transaction. No Overhead
evice, Database Storage Checkpoints use
record identifies a transaction
T to restore files due to a media failure.
ferh Knouledoe
uDIIClions

Tech Knoul
PUDe
Management System (SPPU-Ser
Datapase Managem
5-Comp) 12-11
5-Comp) 1Z0
Recove Methods
Management System (SPPU-Sem 3. Valldate
Processing

Recovery Methods
Validating
Quer
Database Staps
of
a Q u e r yDecomposition
12.4.5 Disadvantages also be validated by
The query must
checking that all QueryOptimization
Query validation is done
by
(1) Data fragmentation attributes and relation names are valid in
the attribute
checking that all
technique is
the updated
database schema (column) and relation
(table) names are
The main disadvantage of this is of the particular being queried by Code Generation
valid i.e.
the data
Data will suffer from
fragmentation
as
linear Query Execution Plan
query. untime Query Execution
Table, column name
present in 8ven
not be in
dividedup into pages
that may or database.
storage
sets of related
hence, complex Query Decomposition
order for large Query execution plan will give idea about
management strategies.
how query Semantically meaningful names in the given
will be executing in stepwise manner. includes scanning,
decomposition parsing and database schema which is
(2) Commit overhead
being queried.
An internal representation
of the query
the overhead of writing
can be
created validatingprocess Example: To write 'column name' for showing
the directory size is large, data structure which is calleda
as a tree
shadow directories to disk as
transaction commit query tree. S c a n n i n g
employee is alive or not then column name is
The DBMS must find all alternative
finds the language
tokens like SQL
significant. execution
trategies Sca
ner Employee_Alive_Bln' this column name is
for retrieving the result of the query The
and relation names in the
(3) Garbage collection from he attribute names,
meaningful and we understand everything about
kevwords,
on the disk as database. query. variable.
accumulate in the pages ofthe
Garbage will text
Example: Department information can be accessed An internal representation of the query is then shown
references. For
data is updated and pages loose any in Parsing
as a tree data structure called a query tree
contains a data item
X following ways, of query to find out whether
page that the syntax
example if i have a
Parser checks nternal representation
of the query is then shown
that is replaced with a new value then a new page wil 1. Department table
ten according to the syntax rules (rules of A
as a graph data structure called a query graph
table is updated language.
be created. Once the shadow page 2. Employee_Department_Join table query
grammar) of the
nothing will reference the old value of X.
A query can have many possible execution strategies.
between current and shadow Query in highHevel
The operation to migrate Process of selecting a suitable strategy for processing a anguage (typicaly SQL
an atomic mode.
directories must be implemented as
query is known as query optimization.
Query System catalog
12.5 Query Processingi SQLDatabase -Query optimization is achievable for simple queries but decomposition
it becomes very complex for difficult queries.
12.5.1 Introduction to Query Processing Relational algebra
Each DBMS has a number of general database access expression
of
Relational query processing refers to the range
algorithms that such as SELECTION, PROJECTION or
from Query Database statistics
activities which includes in extracting data a
JOIN or combination of these operations. Compile time optimization

database using a database query.

A query processing involves below steps,


12.5.2 Typical Query Processing in DBMS Execution plan

1 Scan Introduction Code


genration
module produces
2 Parse The scanning, parsing, and validating
tree
3. Validate an internal representation of the query like query Generated code

or query graph.
1. Scan Main database
strategY
The DBMS must then find its execution 1 Runtime query
The scanner reads the language tokens such
keywords, relation names in the text of the query.
as sQL
result of query from the database
files.
Runtime execuion 1
fetching
ution Query output Query Optim/zation
2. Parse A query typically can have many possible execu
suitable one for
The Parser check the query syntax to verify it is as per strategies the process of selecting a DBMS
the syntax rules of the query language. optimization. Processing in
processing a query is known as query Fig. 12.5.1:Query
CAIOS
TochKaoutedg
PUDIIC
Databaseanagemnen SE OOc
em o-Comp)
5-Comp) 12-13

System SPPU-Sem 5-Comp) 12-12 covery Metho f he


ardware resources Recovery Methods
Database Management 12.6.1 Goals of Query Optimization nods p t o n
2

Name((Age 25EMPLOYEF e)
he and significantly
s
speed up
b) Query Optimization Eliminate all unwanted data E u (Departments d)))
( d . d n a m e "
- H R "
( D e p a r t m e n

12.6.3
performance.
important
tasks (a) ary Optimizers
Query optimization is one
ofthe most tries to
above query option is to be selected
ted is
Query optimization eliminate NOW, Wich o f
Query optimization is
of a relational DBMS.
and or rows from given
relation.
unwanted tuples. query
optimizer.

one of the
alternative plans by of a most
TheQueny optimizer generates lentified relational DBMS. important taskS
estimated cost. Approaches
chooses the best plan with
the least Examplee
ery
Optimization The
Query optimizer
used to find out
an
SELECT*
Qu
Performance Tuning generates alternative
chooses the best
62
plan with the least estimatedplans and
The query optimizer
module is
to
execution plan which is the
execution strategy
FROM EMPLOYEES R e l a t i o n a la p p r o a c h Query optimizer is cost.

execution plan for responsible


files.
from the database for
identifying a best
retrieve the result of the query If we require only employee ids then to tind
select only attempts query expression evaluating the query.
execution strategies
system

have many possible employee Id column from table. No need to DBMS The
A query can
the process o
h R D B

equivalent t o the given query expression, but aptimizer generates mutiple


each with differet performances the columns from table by specifying *
in which is selects the query plans and
execution plan is known
select Clause. more
efficient way. plan with the least estimated cost.
reasonably efficient in
selecting So, Optimized query will be
a execute

To estimate the cost of every


as query optimization.
Algorithma p p r o a c h

plan, the optimizer uses


SELECT Emp_ID by choosing algorithm
for operat or
system catalogs.
c)CodeGeneration FROM EMPLOYEES celecting query to u s e and so on.
The system catalogs contain the information needed
indices by
The code generator generates the
code to execute the hoo5ing specific the optimizer to choose
between alternate
block. (b) Speed up queries
commonly
used strategies
for optimizatio
given query.
tor a
plans
execution plan selected by query optimization other
Query optimization try to find out query which Query
d) Runtime Query Execution result very fast.
gives e index

is strategy that can used to speed


accepted by runtime Using an index
The above generated code will be
Query parser
a query evaluation.
(c)Increase query pertormance by perfornmancetunine
the generated code up d
query processor which executes is very important for query
and produces the query resut. Break up the single complex sQl statement
nto This strategy Parsed query
user wants.
several simple sQL statements which will increase optimization.
This is desired query output that
performance of execution of query. Aggregate table
Query optimizer
only higher level data
12.6 Query Optimizationin SQL In many cases,
temporary table
you can
(such
build
tables
an
used
index on the
to store
o Tables which
stores

data need to be parsed.


so
Pan

genedorestmator
Plan cost Catalog
manager
DBMS in fewer amounts of
(1) Query optimization is an essential for many intermediate results of query) in order to speed up the evaluation becomes faster
which best query execution plan, out of multiple o So, Query
query performance. Evaluation plan
alternative query execution plans is to be identified for Vertical partitioning
(d) Select best query plan out of alternative query plan columns. Query plan evaluator
solving a query efficiently. o Slicing the table vertically using
is nothing but selecting the Consider following query to "Find all employees having
Vertical partitioning will decrease
the amount of
execution
Fig. 12.6.1:Query parsing, optimization and
(2) Query optimization o
efficient query execution plan among the available working for department HR."
age above 25 and data required for query processing have a remarkable impact
Query evaluation plan can
query pians for soBving a given query.
SELECT e.Emp_Name Horizontal partitioning on query
execution time.
(3) The query plan is constructed based on multiple cost
FROM EMPLOYEES e row wise.
Partition the table by data value, or by Review Questions
factors. JOIN data
of
O This method will decrease the amount
(4) Query optimization tries select query plan which is
to DEPARTMENTS d backup is
query needs to process. is database backup ? Why
iower processing cost (but not always low cost plans Q. 1 What
?
ON e.did-d.did of database backup
are selected as other factors are also included in query Denormalization needed ? Explain types
WHERE e.age25 tables into a database failures
that
evaluation). T h e process of combining multiple diferent types of
(5) Query optimization come into picture when we want AND d.dname "HR';| Single table is called as denormalization.
Q. 2
Discuss

in
database
environment?

For above query we can write alternative relationa may


occur

?
to develop a good system to minimize the cost of because
es of recovery
his speeds up query performance ? Explain types
query evaluation. queries like below, What is
recovery

number of joins is required. a. 3 (Forward, Backward Recovery)


(6) There is a trade off between the amount of time spent Option 1 Server tunin8
to find out the best plan and the amount of time IR
tuning
AND d dnanie cdcn and often
required for running the plan. Different DeMS have cmp_Nane eAge 25 server has its own parameters, TechKnowledg
P u b l i C a t i o n s

different ways for balancing these two factors. (EMPLOYEES e D didesd did Departments a) erver parameters so that it can fully take
aova
och Knowledge

DIICat

You might also like