0% found this document useful (0 votes)
4 views

Module 4 DBMS.

The document discusses Transaction Management in Database Management Systems, detailing the concept of transactions, their states, and the ACID properties that ensure data integrity. It explains transaction schedules, including serial and concurrent schedules, and introduces conflict and view serializability for maintaining consistency in multi-user environments. Additionally, it covers concurrency control methods, deadlock handling, and the importance of SQL stored procedures in transaction management.

Uploaded by

funnyanimals2314
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)
4 views

Module 4 DBMS.

The document discusses Transaction Management in Database Management Systems, detailing the concept of transactions, their states, and the ACID properties that ensure data integrity. It explains transaction schedules, including serial and concurrent schedules, and introduces conflict and view serializability for maintaining consistency in multi-user environments. Additionally, it covers concurrency control methods, deadlock handling, and the importance of SQL stored procedures in transaction management.

Uploaded by

funnyanimals2314
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/ 32

Database Management Systems – A8514

Module 4: Schema Refinement and Normal Forms

Transaction Management
Transaction concept
Transaction states
ACID properties
Schedules
Serializability
• Conflict serializability
• View serializability
Recoverability
Concurrency control
• Lock based protocols
• Timestamp-based protocols
Deadlocks handling
SQL stored procedures
Transaction Management
Transaction Management is a crucial concept in Database Management Systems (DBMS) that
ensures the integrity, consistency, and reliability of data in a multi-user environment.
A transaction is a sequence of one or more SQL operations (like insert, update, delete)
performed as a single logical unit of work.

Transaction concept
Transaction refers to execution of any one user program in dbms.
(Or)
Transaction can be defined as group of tasks being executed.
(Or)
Transaction also referred to as an event that which occurs on a database with read/write
operation.
Basic transaction operations:
➢ read (X): Performs the reading operation of data item X from the database.
➢ write (X): Performs the writing operation of data item X to the database.
Note: During transaction execution the database may be inconsistent but when the
transaction is committed, the database must be consistent.
Two main issues to deal with:
• Failures, (e.g. hardware failures and system crashes)
• Concurrency, for simultaneous execution of multiple transaction
Transaction states
Every transaction undergoes several states in its execution.
A transaction can be in any one of the following states:
1. Start
2. Partially Committed
3. Committed
4. Failed
5. Aborted Or Terminate
Active - This is the first state of transaction and here the transaction is being executed. For
example, updating or inserting or deleting a record is done here. But it is still not saved to the
database. When we say transaction it will have set of small steps, and those steps will be
executed here.

Partially Committed - This is also an execution phase where last step in the transaction is
executed. But data is still not saved to the database. In example of calculating total marks,
final display the total marks step is executed in this state.

Committed - In this state, all the transactions are permanently saved to the database. This
step is the last step of a transaction, if it executes without fail.

Failed - If a transaction cannot proceed to the execution state because of the failure of the
system or database, then the transaction is said to be in failed state. In the total mark
calculation example, if the database is not able fire a query to fetch the marks, i.e.; very first
step of transaction, then the transaction will fail to execute.

Aborted - If a transaction is failed to execute, then the database recovery system will make
sure that the database is in its previous consistent state. If not, it brings the database to
consistent state by aborting or rolling back the transaction. If the transaction fails in the middle
of the transaction, all the executed transactions are rolled back to it consistent state before
executing the transaction. Once the transaction is aborted it is either restarted to execute
again or fully killed by the DBMS.
ACID properties
To ensure consistency, completeness of the database in scenario of concurrent access, system
failure, the following ACID properties can be enforced on to database.
1. Atomicity,
2. Consistency,
3. Isolation and
4. Durability

Atomicity: This property states that all the instructions with in a transaction must be executed
or none of them should be executed.
➢ This property states that all transactions execution must be atomic i.e. all actions
should be carried out or none of the actions should be executed.
It involves following two operations.
➢ Abort: If a transaction aborts, changes made to database are not visible.
➢ Commit: If a transaction commits, changes made are visible.
Atomicity is also known as the ‘All or nothing rule’.
Example: Consider the following transaction T consisting of T1 and T2: Transfer of 100 from
account X to account Y.
If the transaction fails after completion of T1 but before completion of T2 (say, after write(X)
but before write(Y)), then amount has been deducted from X but not added to Y. This results
in an inconsistent database state. Therefore, the transaction must be executed in entirety to
ensure correctness of database state.

Consistency: The database must remain in consistence state even after performing any kind
of transaction ensuring correctness of the database.
➢ If we execute a particular transaction in isolation (or) together with other transaction
in multiprogramming environment. the transaction should give same result in any
case.
➢ Each transaction, run by itself with no concurrent execution of other transactions,
must preserve the consistency of the database. This property is called consistency and
the DBMS assumes that it holds for each transaction. Ensuring this property of a
transaction is the responsibility of the user.
Example: Consider the following transaction T consisting of T1 and T2

Referring to the example above,


The total amount before and after the transaction must be maintained.
Total before T occurs = 500 + 200 = 700.
Total after T occurs = 400 + 300 = 700.
Therefore, database is consistent. Inconsistency occurs in case T1 completes but T2 fails. As a
result, T is incomplete.

Isolation: When executing multiple transactions concurrently & trying to access shared
resources the system should create an order such that the only one transaction can access the
shared resource at the same time & release it after completion of its execution for other
transaction.
➢ This property ensures that multiple transactions can occur concurrently without
leading to inconsistency of database state. Transactions occur independently without
interference.
➢ Changes occurring in a particular transaction will not be visible to any other
transaction until that particular change in that transaction is written to memory or has
been committed.
Note: To achieve isolation, you should use locking mechanism among shared resources.

Example: Let X= 500, Y = 500. Consider two transactions T and T”.

Suppose T has been executed till Read (Y) and then T’’ starts. As a result, interleaving of
operations takes place due to which T’’ reads correct value of X but incorrect value of Y and
sum computed by T’’: (X+Y = 50, 000+500=50, 500) is thus not consistent with the sum at end
of transaction: T: (X+Y = 50, 000 + 450 = 50, 450).

This results in database inconsistency, due to a loss of 50 units. Hence, transactions must take
place in isolation and changes should be visible only after a they have been made to the main
memory.

Durability: This property states that once after the transaction is completed the changes that
made should be permanent & should be recoverable even after system crash/power failure.
➢ This property ensures that once the transaction has completed execution, the updates
and modifications to the database are stored in and written to disk and they persist
even is system failure occurs. These updates now become permanent and are stored
in a non-volatile memory.
Transaction Schedules
Schedule
➢ It refers to the list of actions to be executed by transaction.
➢ A schedule is a process of grouping the transactions into one and executing them in a
predefined order.
Schedule of actions can be classified into 2 types.
1. Serializable schedule/serial schedule.
2. Concurrent schedule.
1. Serial schedule:
➢ In the serial schedule the transactions are allowed to execute one after the other
ensuring correctness of data.
➢ A schedule is called serial schedule, if the transactions in the schedule are defined to
execute one after the other.
2. Concurrent schedule:
Concurrent schedule allows the transaction to be executed in interleaved manner of
execution.

Complete schedule:
It is a schedule of transactions where each transaction is committed before terminating. The
example is shown below where transactions T1 and T2 terminates after committing the
transactions.
Serializability
Basic Assumption – Each transaction preserves database consistency. Thus, serial execution
of a set of transactions preserves database consistency.
A (possibly concurrent) schedule is serializable if it is equivalent to a serial schedule. Different
forms of schedule equivalence give rise to the notions of:
1. Conflict Serializability
2. View Serializability

Conflict Serializability
A schedule is conflict serializable if it is conflict equivalent to some serial schedule.
Conflict Equivalent: Two schedules are said to be conflict equivalent when one can be
transformed to another by swapping non-conflicting operations.
Conflict Serializable: A schedule is called conflict serializable if it can be transformed into a
serial schedule by swapping non-conflicting operations.
Conflicting operations: Two operations are said to be conflicting if all below conditions are
satisfied:
➢ They belong to different transaction
➢ They operation on same data item
➢ At Least one of them is a write operation
Conflicting operations refers to two instructions of two different transactions may want to
access same data to perform read/write operation.
Conflicting Instructions
Instructions li and lj of transactions Ti and Tj respectively, conflict if and only if there exists
some item Q accessed by both li and lj, and at least one of these instructions write Q
1. li = read(Q), lj = read(Q). li and lj don’t conflict
2. li = read(Q), lj = write(Q). They conflict
3. li = write(Q), lj = read(Q). They conflict
4. li = write(Q), lj = write(Q). They conflict

Rules for conflict serializability:


➢ If two different transactions are both for read operation, then there is no conflict and
can allowed to execute any order.
➢ If one instruction performing read operation and other instruction performing write
operation there will be conflict hence instruction ordering is important.
➢ If both transactions performing write operation, then there will be in conflict so
ordering the transaction can be done.
➢ A non-serial schedule is a conflict serializable if, after performing some swapping on
the non-conflicting operation results in a serial schedule.
➢ It is the process of checking the non-serial schedule and an equivalent serial schedule.
This process of checking is called Conflict Serializability.
➢ It is tedious to use if we have many operations and transactions as it requires a lot of
swapping.
➢ For checking, we will use the Precedence Graph technique.
➢ First, we will check conflicting pairs operations (read-write, write-read, and write-
write) and then form directed edges between those conflicting pair transactions.
➢ If we can find a loop in the graph, then the schedule is non-conflicting serializable
otherwise it is surely a conflicting serializable schedule.

Example: Draw precedence graph for below transaction schedule

As precedence graph is having cycles or closed loops, the given schedule is not serializable.
Example: Check whether the given schedule S is conflict serializable or not-
S : R1(A) , R2(A) , R1(B) , R2(B) , R3(B) , W1(A) , W2(B)
Step-01: List all the conflicting operations and determine the dependency between the
transactions-
• R2(A) , W1(A) (T2 → T1)
• R1(B) , W2(B) (T1 → T2)
• R3(B) , W2(B) (T3 → T2)
Step-02: Draw the precedence graph

Clearly, there exists a cycle in the precedence graph. Therefore, the given schedule S is not
conflict serializable.

Example: Check whether the given schedule S is conflict serializable or not.

Step-01: List all the conflicting operations and determine the dependency between the
transactions-
• R4(A) , W2(A) (T4 → T2)
• R3(A) , W2(A) (T3 → T2)
• W1(B) , R3(B) (T1 → T3)
• W1(B) , W2(B) (T1 → T2)
• R3(B) , W2(B) (T3 → T2)

Step-02: Draw the precedence graph

Clearly, there exists no cycle in the precedence graph. Therefore, the given schedule S is
conflict serializable.
Example: A schedule "S" having three transactions t1, t2, and t3 working simultaneously.
Check Whether S is Conflict Serializable or Not?
T1 T2 T3
R(x)
R(y)
R(y)
W(y)
W(x)
W(x)
R(x)
W(x)

Precedence graph
As there is no loop in the graph, it is a conflict serializable schedule as well as a serial
schedule.
Since it is a serial schedule, we can detect the order of transactions as well.
The order of the Transactions: t1 will execute first as there is no incoming edge on T1.
(i.e., In degree=0)
T3 will execute second as it depends on T1 only.
T2 will execute at last as it depends on both T1 and T3.
So, order of its equivalent serial schedule is: T1 --> T3 --> T2
Example: A schedule "S" having three transactions t1, t2, and t3 working simultaneously.
Check Whether S is Conflict Serializable or Not?
T1 T2 T3
R(x)
R(z)
W(z)
R(y)
R(y)
W(y)
W(x)
W(z)
W(x)
Precedence graph
As the cycle is formed, the transactions cannot be serializable.
Example: Check Whether S is Conflict Serializable or Not?

Step-1: List all the conflicting operations and the dependency between the transactions.
₋ W1(B) , W2(B) (T1 → T2)
₋ W1(B) , W3(B) (T1 → T3)
₋ W1(B) , W4(B) (T1 → T4)
₋ W2(B) , W3(B) (T2 → T3)
₋ W2(B) , W4(B) (T2 → T4)
₋ W3(B) , W4(B) (T3 → T4)
Step-2:
• Draw the precedence graph.

Step-3:
• Clearly, there exists no cycle in the precedence graph. Therefore, the given schedule
S is conflict serializable.
Example: Check Whether S is Conflict Serializable or Not?

Step-1:
List all the conflicting operations and determine the dependency between the transactions-
₋ R1(A) , W2(A) (T1 → T2)
₋ R2(A) , W1(A) (T2 → T1)
₋ W1(A) , W2(A) (T1 → T2)
₋ R1(B) , W2(B) (T1 → T2)
₋ R2(B) , W1(B) (T2 → T1)
Step-2:
• Draw the precedence graph.
Step-3:
• Clearly, there exists a cycle in the precedence graph.
Therefore, the given schedule S is not conflict serializable.
View Serializability
This is another type of serializability that can be derived by creating another schedule out of
an existing Schedule.
✓ There may be some schedules that are not Conflict-Serializable but still gives a
consistent result because Conflict-Serializability becomes limited when the
Precedence Graph of a schedule contains a loop/cycle.
✓ But, what if a schedule’s precedence graph contains a cycle/loop and is giving
consistent result.
✓ So, to address such cases we brought the concept of View-Serializability because we
did not want to confine only to Conflict-Serializability.
✓ A schedule is said to be View-Serializable if it is view equivalent to a Serial Schedule
(where no interleaving of transactions is possible).
✓ To check whether a given schedule is view serializable, we need to check whether the
given schedule is View Equivalent or not.
Method 1
View Equivalent
Two schedules T1 and T2 are said to be view equivalent, if they satisfy all the following
conditions:
1. Initial Read: If Ti reads the initial value of object A in S1, it must also read the initial value
of A in S2.
For example, if transaction T1 reads a data item X before transaction T2 in schedule S1 then
In schedule S2, T1 should read X before T2.

Note: Here initial read means the first read operation on a data item, for example, a data item
X can be read multiple times in a schedule but the first read operation on X is called the initial
read.

2. Final Write: If Ti reads a value of A written by Tj in S1, it must also read the value of A
written by Tj in S2.
For example, a data item X is last written by Transaction T1 in schedule S1. In S2, the last
write operation on X should be performed by the transaction T1.

3. Update Read: For each data object A, the transaction (if any) that performs the final write
on A in S1 must also perform the final write on A in S2.
For example, In schedule S1, T3 performs a read operation on A after the write operation on
A by T2 then in S2, T3 should read the A after T2 performs write on A.
Example: Verify whether the below schedules S and S1 are view equivalent or not.

Step 1: Initial Read


• The initial read operation in S is done by T1 and in S1 it is also done by T1 .
Step 2: Final Write
• The final write operation in S is done by T3 and in S1, it is also done by T3.
Step 3: Updated Read
• In both schedules S and S1, there is no read except the initial read that's why we don't
need to check that condition.
• The first schedule S1 satisfies all three conditions, so we don't need to check another
schedule.
• Hence, view equivalent serial schedule is: T1 → T2 → T3
Example: Prove whether the given schedule is View-Serializable or not?

Step-1: Initial Read


• In schedule S1, transaction T1 first reads the data item X. In S2 also transaction T1
first reads the data item X.
• Lets check for Y. In schedule S1, transaction T1 first reads the data item Y. In S2 also
the first read operation on Y is performed by T1.
• We checked for both data items X & Y and the initial read condition is satisfied in
S1 & S2.
Step-2: Final Write
• In schedule S1, the final write operation on X is done by transaction T2. In S2 also
transaction T2 performs the final write on X.
• Lets check for Y. In schedule S1, the final write operation on Y is done by transaction
T2. In schedule S2, final write on Y is done by T2.
• We checked for both data items X & Y and the final write condition is satisfied in
S1 & S2.
Step-3: Update Read:
• In S1, transaction T2 reads the value of X, written by T1. In S2, the same transaction
T2 reads the X after it is written by T1.
• In S1, transaction T2 reads the value of Y, written by T1. In S2, the same transaction
T2 reads the value of Y after it is updated by T1.
• The update read condition is also satisfied for both the schedules.
Since all the three conditions are satisfied, which means S1 and S2 are view equivalent. Also,
as we know that the schedule S2 is the serial schedule of S1, thus we can say that the schedule
S1 is view serializable schedule.
Note: All view serializable schedules are conflict serializable but all conflict serializable
schedules may or may not be view serializable.
Method 2
• If the given schedule is non-conflict serializable, then it may or may not be view
serializable. So we need to look at the below cases.
• Blind write: Performing the Writing operation (updation), without reading
operation, such write operation is known as a blind write.
• If no blind write exists, then the schedule must be a non-View-Serializable
schedule.
• If there exists any blind write, then, in that case, the schedule may or may not be
view serializable.
• If it does not contain any blind-write, we can surely state that the schedule would
not be View-Serializable.
Example: Check whether the given schedule S is view serializable or not?

We know, if a schedule is conflict serializable, the it is surely view serializable.


✓ So, let us check whether the given schedule is conflict serializable or not.
Step-01:
✓ List all the conflicting operations and determine the dependency between the
transactions-
R1(A) , W3(A) (T1 → T3)
R2(A) , W3(A) (T2 → T3)
R2(A) , W1(A) (T2 → T1)
W3(A) , W1(A) (T3 → T1)
Step-02:
• Draw the precedence graph.

• Clearly, there exists a cycle in the precedence graph.


• Therefore, the given schedule S is not conflict serializable.
Now,
• Since, the given schedule S is not conflict serializable, so, it may or may not be view
serializable.
• To check whether S is view serializable or not, let us use another method( blind
writes).
Checking for Blind Writes:
✓ There exists a blind write W3 (A) in the given schedule S.
✓ Therefore, the given schedule S may or may not be view serializable.
✓ Now, Let us derive the dependencies and then draw a dependency graph.
✓ Drawing a Dependency Graph-
▪ T1 firstly reads A and T3 firstly updates A. So, T1 must execute before
T3.Thus, we get the dependency T1 → T3.
▪ Final updation on A is made by the transaction T1.So, T1 must execute
after all other transactions. Thus, we get the dependency (T2, T3) → T1.
▪ There exists no write-read sequence.
Now, let us draw a dependency graph using these dependencies

Clearly, there exists a cycle in the dependency graph. Thus, we conclude that the given
schedule S is not view serializable

Example: Check whether the given schedule S is view serializable or not. If yes, then give the
serial schedule.
S : R1(A) , W2(A) , R3(A) , W1(A) , W3(A)
Step-01:
✓ List all the conflicting operations and determine the dependency between the
transactions-
R1(A) , W2(A) (T1 → T2)
R1(A) , W3(A) (T1 → T3)
W2(A) , R3(A) (T2 → T3)
W2(A) , W1(A) (T2 → T1)
W2(A) , W3(A) (T2 → T3)
R3(A) , W1(A) (T3 → T1)
W1(A) , W3(A) (T1 → T3)
Step-02:
• Draw the precedence graph

• Clearly, there exists a cycle in the precedence graph.


• Therefore, the given schedule S is not conflict serializable.
Now,
• Since, the given schedule S is not conflict serializable, so, it may or may not be view
serializable.
• To check whether S is view serializable or not, let us use another method.
Let us check for blind writes.
• Checking for Blind Writes:
• There exists a blind write W2 (A) in the given schedule S.
• Let us derive the dependencies and then draw a dependency graph.
• Drawing a Dependency Graph-
▪ T1 firstly reads A and T2 firstly updates A.
▪ So, T1 must execute before T2.
▪ Thus, we get the dependency T1 → T2.
▪ Final updation on A is made by the transaction T3.
▪ So, T3 must execute after all other transactions.
▪ Thus, we get the dependency (T1, T2) → T3.
• From write-read sequence, we get the dependency T2 → T3
Clearly, there exists no cycle in the dependency graph. Therefore, the given schedule S is view
serializable. The serialization order T1 → T2 → T3.
Recoverability
It refers to the process of undoing the changes made to the database in case of any transaction
failure due to system crash or any other reason.
Dirty read: A "dirty read" in database transactions refers to a situation where a transaction
reads data that has been modified by another transaction but has not yet been committed.
Recoverable Schedule: A schedule that can be successfully rolled back in case of any failure is
known as recoverable Schedule.
➢ A transaction performs a dirty read operation from an uncommitted transaction
and its commit operation is delayed till the uncommitted transaction either
commits or roll backs then such a schedule is known as a Recoverable Schedule.
➢ The commit operation of the transaction that performs the dirty read is delayed.
➢ This ensures that it still has a chance to recover if the uncommitted transaction
fails later.
Example: Consider the schedule below

T2 performs a dirty read operation. The commit operation of T2 is delayed till T1 commits or
roll backs. T1 commits later. T2 is now allowed to commit. In case, T1 would have failed, T2
has a chance to recover by rolling back.
Irrecoverable Schedule: A schedule that cannot be rolled back because of some transactions
already used COMMIT to make the changes permanent in database and these transactions
have used values produced by the failed transactions. These types of schedules are called
irrecoverable schedules.
A transaction performs a dirt read operation from an uncommitted transaction and commits
before the transaction from which it has read the value then such type of schedule is known
as an Irrecoverable Schedule.
Example: Consider the following schedule

Here, T2 performs a dirty read operation. T2 commits before T1. T1 fails later and roll backs.
The value that T2 read now stands to be incorrect. T2 cannot recover since it has already
committed.
The following are the two methods to check whether a schedule is recoverable or
irrecoverable.
Method-01:
All conflict serializable schedules are recoverable. All recoverable schedules may or may not
be conflict serializable.
Example: Check whether the given schedule S is conflict serializable and recoverable or not

Step-01: List all the conflicting operations and determine the dependency between the
transactions-
• R2(X) , W3(X) (T2 → T3)
• R2(X) , W1(X) (T2 → T1)
• W3(X) , W1(X) (T3 → T1)
• W3(X) , R4(X) (T3 → T4)
• W1(X) , R4(X) (T1 → T4)
• W2(Y) , R4(Y) (T2 → T4)
Step-02: Draw the precedence graph

• Clearly, there exists no cycle in the precedence graph.


• Therefore, the given schedule S is conflict serializable.
• Checking Whether S is Recoverable Or Not-
• Conflict serializable schedules are always recoverable.
• Therefore, the given schedule S is recoverable.
Method-02:
• Check if there exists any dirty read operation (Reading from an uncommitted
transaction is called as a dirty read)
• If there does not exist any dirty read operation, then the schedule is surely
recoverable.
• If there exists any dirty read operation, then the schedule may or may not be
recoverable.
If there exists a dirty read operation, then follow the following cases

Cascading Schedule: If in a schedule, failure of one transaction causes several other


dependent transactions to rollback or abort, then such a schedule is called as a Cascading
Schedule or Cascading Rollback or Cascading Abort.
Example:

• Transaction T2 depends on transaction T1.


• Transaction T3 depends on transaction T2.
• Transaction T4 depends on transaction T3.
In this schedule,
✓ The failure of transaction T1 causes the transaction T2 to rollback.
✓ The rollback of transaction T2 causes the transaction T3 to rollback.
✓ The rollback of transaction T3 causes the transaction T4 to rollback.
Such a rollback is called as a Cascading Rollback.
NOTE-If the transactions T2, T3 and T4 would have committed before the failure of transaction
T1, then the schedule would have been irrecoverable.
Cascadeless Schedule: If in a schedule, a transaction is not allowed to read a data item until
the last transaction that has written it is committed or aborted, then such a schedule is called
as a Cascade-less Schedule.
• Cascadeless schedule allows only committed read operations.
Example: Cascade-less schedule allows only committed read operations. However, it allows
uncommitted write operations.

Strict Schedule: If in a schedule, a transaction is neither allowed to read nor write a data item
until the last transaction that has written it is committed or aborted, then such a schedule is
called as a Strict Schedule.
• Strict schedule allows only committed read and write operations.
• Clearly, strict schedule implements more restrictions than cascadeless schedule.
• All strict schedules are cascadeless schedules.
• All cascadeless schedules are not strict schedules.
Concurrency control
In case of concurrent instruction executions to preserve atomicity, isolation and serializability,
we use ‘lock-based’ protocol.
Types of Locks:
1. Binary locks
2. Shared /exclusive locks
Binary Lock − A lock on a data item can be in two states; it is either locked or unlocked.
Shared Lock
✓ which are often denoted as lock-S(), is defined as locks that provide Read-Only access
to the information associated with them.
✓ Whenever a shared lock is used on a database, it can be read by several users, but
these users who are reading the data items will not have permission to edit it or make
any changes to the data items.
✓ A shared lock, also known as a read lock.
Exclusive Lock
✓ This lock allows both the read and write operation, Once this lock is placed on the data
no other lock can be placed on the data until Exclusive lock is released.
✓ The other name for an exclusive lock is write lock.
✓ which are often denoted as X-lock( ) or lock-x( )
Lock Compatibility Matrix
Lock Compatibility Matrix controls whether multiple transactions can acquire locks on
the same resource at the same time.
• If a resource is already locked by another transaction, then a new lock request can be
granted only if the mode of the requested lock is compatible with the mode of the
existing lock.
• Any number of transactions can hold shared locks on an item, but if any transaction
holds an exclusive lock on item, no other transaction may hold any lock on the item.
• compatible locks held by other transactions have been released. Then the lock is
granted.
Upgrading And Downgrading of Locks:
• If a transaction is holding an exclusive lock over an object. It can simply downgrade
from exclusive lock to shared lock after completion of its updation.
• Similarly, a shared lock can be upgraded to exclusive lock on data item. when there
is no other transaction is holding exclusive lock on same data item

Lock based protocols


Locking protocols are classified into 2-types, they are:
i. Simple Lock Based Protocol
ii. 2-Phase Locking Protocol
i. Simple Lock Based protocol
Simple lock-based protocols allow transactions to obtain a lock on every object before a 'write'
operation is performed. Transactions may unlock the data item after completing the
‘write’ operation.
problems with simple locking are:
1. deadlocks
2. starvation
ii. 2-Phase locking Protocol
This locking protocol divides the execution phase of a transaction into two parts. The First part
is where the transaction acquires all the locks.
As soon as the transaction releases its first lock, the second phase starts. In this phase the
transaction cannot demand any new locks; it only releases the acquired locks.
This protocol can be divided into two phases:
1. Growing Phase: a transaction obtains locks, but may not release any lock.
2. Shrinking Phase: a transaction may release locks, but may not obtain any lock.

Lock Point: The Point at which the growing phase ends, i.e., when a transaction takes the final
lock it needs to carry on its work

Types of 2-Phase Locking protocol


• Conservative (or) pre-claim locking protocol.
• Strict 2 phase locking protocol
• Rigorous 2 phase locking protocol

Conservative (or) pre-claim locking protocol:


Conservative protocols evaluate their operations and find list of data items on which they
need locks. Before initiating an execution, the transaction requests the system for all the locks
it needs.
• If all the locks are granted, the transaction executes and releases all the locks when all
its operations are over.
• If all the locks are not granted, the transaction rolls back and waits until all the locks
are granted.
• In the above schedule since in the schedule the lock on a is released by T1, it is possible
for the transaction T2 to acquire the lock on a.
• Now the transaction T2 reads the value of a which was written by transaction T1.
• This implies that if the transaction T1 aborts, the transaction T2 must be aborted for
consistency purposes.
• It means that even though a conservative two-phase protocol is used, the schedules
may not necessarily be cascadeless.

Strict Two-Phase locking protocol


• In this method all Exclusive(X) locks held by the transaction be released after the
Transaction Commits.
• The first phase of Strict-2PL is same as 2PL i.e. when the transaction starts executing,
it seeks permission for the locks it requires and acquiring all the locks in the first phase,
the transaction continues to execute normally.
• In second phase Strict-2PL does not release a lock after using it. It releases only all
exclusive locks after a transaction is committed.
• It guarantees cascadeless recoverability.

Rigorous two-phase locking protocol


✓ This protocol requires that all the share and exclusive locks to be held until the
transaction commits.
✓ It releases all the locks including shared and exclusive locks after committing the
transactions.
✓ Same as Strict 2PL but hold all locks until the transaction has already successfully
committed or aborted. There is no deadlock.
Timestamp-based protocol
Timestamp ordering protocol maintains the order of transaction based on their timestamps.
• A timestamp is a unique identifier that is being created by the DBMS when a
transaction enters the system. This timestamp can be based on the system clock or a
logical counter maintained in the system.
• Timestamp helps identifying the older transactions and gives them higher priority
compared to the newer transactions. This make sure that none of the transactions are
pending for a longer period.
• This protocol also maintains the timestamps for the last read and last write on a data.
• The timestamp of the transaction T1 is denoted as TS(T1) .
Example:
• Let’s say an old transaction T1 timestamp is TS(T1) and a new transaction T2 enters
into the system, timestamp assigned to T2 is TS(T2).
• Here TS(T1) < TS(T2) so the T1 has the higher priority because its timestamp is less
than timestamp of T2.
Read time-stamp of data-item:
o It is denoted as R_TS(A)
o R_TS(A) is the largest or youngest timestamp of a transaction that executed
the operation read(A) successfully.
Write time-stamp of data-item:
o It is denoted as W_TS(A)
o W_TS(A) is the largest or youngest timestamp of a transaction that executed
the operation write(A) successfully.
Basic Timestamp ordering protocol works as follows:
1. Check the following condition whenever a transaction Ti issues a Read (X) operation:
• If W_TS(X) >TS(Ti) then the operation is rejected.
• If W_TS(X) <= TS(Ti) then the operation is executed.
• Timestamps of all the data items are updated.
2. Check the following condition whenever a transaction Ti issues a Write(X) operation:
• If R_TS(X) > TS(Ti) then the operation is rejected.
• If W_TS(X) > TS(Ti) then the operation is rejected and Ti is rolled back otherwise
the operation is executed.
Advantages of Timestamp based protocol:
• Schedules managed using timestamp-based protocol are serializable just like the
two-phase protocols
• Since older transactions are given priority which means no transaction must wait
for longer period that makes this protocol free from deadlock.
Thomas' Write Rule
• This rule states if TS(Ti) < W_TS(A), then the operation is rejected and Ti is rolled
back.
• Time-stamp ordering rules can be modified to make the schedule view serializable.
Instead of making Ti rolled back, the 'write' operation itself is ignored and continue
the remaining operations.

Deadlocks handling
Consider two transaction t1 and t2. If t1 holds lock on data item x and t2 holds lock on data
item y now t1 refers lock over y & t2 request lock over x then deadlock situation occur when
none of the transaction are ready to release locks on x, y.

The following two techniques can be used for deadlock handling(prevention):


1. wait-die
2. wait-wound

1. wait-die:
In this scheme, if a transaction requests for a resource which is already held with a conflicting
lock by another transaction, then the DBMS simply checks the timestamp of both transactions.
It allows the older transaction to wait until the resource is available for execution.

Let us assume there are two transactions Ti and Tj and let TS(T) is a timestamp of any
transaction T. If T2 holds a lock by some other transaction and T1 is requesting for resources
held by T2 then the following actions are performed by DBMS:
1. Check if TS(Ti) < TS(Tj) - If Ti is the older transaction and Tj has held some resource,
then Ti is allowed to wait until the data-item is available for execution. That means if
the older transaction is waiting for a resource which is locked by the younger
transaction, then the older transaction is allowed to wait for resource until it is
available.
2. Check if TS(Ti) < TS(Tj) - If Ti is older transaction and has held some resource and if Tj
is waiting for it, then Tj is killed and restarted later with the random delay but with the
same timestamp.
For example:
Suppose that transaction T22, T23, T24 have time-stamps 5, 10 and 15 respectively. If
T22requests a data item held by T23 then T22 will wait. If T24 requests a data item held by
T23, then T24 will be rolled back.

2. wait wound technique:


It based on time stamp of transaction request. In wound wait scheme, if the older transaction
requests for a resource which is held by the younger transaction, then older transaction forces
younger one to kill the transaction and release the resource. After the minute delay, the
younger transaction is restarted but with the same timestamp.

If the older transaction has held a resource which is requested by the younger transaction,
then the younger transaction is asked to wait until older releases it.
It is a preemptive technique for deadlock prevention. It is a counterpart to the wait-die
scheme.

When Transaction Ti requests a data item currently held by Tj, Ti is allowed to wait only if it
has a timestamp larger than that of Tj, otherwise Tj is rolled back (Tj is wounded by Ti)
For example:

Suppose that Transactions T22, T23, T24 have time-stamps 5, 10 and 15 respectively. If
T22requests a data item held by T23, then data item will be preempted from T23 and T23 will
be rolled back. If T24 requests a data item held by T23, then T24 will wait.

Here the younger transactions are made to wait in queue& older transaction going to abort.
1. TS(T1) < TS(T2) (Older requests resource from younger) T2 is aborted, T1 gets the resource
2. TS(T1) > TS(T2) (Younger requests resource from older) T1 waits until T2 releases it

DEAD LOCK AVOIDANCE:


Wait for graph:
• We use this technique for dead lock avoidance.
• This is a simple method available to track if any deadlock situation may arise.
• For each transaction entering the system, a node is created.
• When a transaction Ti requests for a lock on an item, say X, which is held by some
other transaction Tj, a directed edge is created from Ti to Tj. If Tj releases item X, the
edge between them is dropped and Ti locks the data item.
• The system maintains this wait-for graph for every transaction waiting for some data
items held by others. The system keeps checking if there is any cycle in the graph.

Here, we can use any of the two following approaches −


• First, do not allow any request for an item, which is already locked by another
transaction. This is not always feasible and may cause starvation, where a transaction
indefinitely waits for a data item and can never acquire it.
• The second option is to roll back one of the transactions. It is not always feasible to roll
back the younger transaction, as it may be important than the older one. With the help
of some relative algorithm, a transaction is chosen, which is to be aborted. This
transaction is known as the victim and the process is known as victim selection.

SQL stored procedures and functions


A procedure is a block that can take parameters (sometimes referred to as arguments) and
be invoked.

Procedures promote reusability and maintainability. Once validated, they can be used in
number of applications. If the definition changes, only the procedure are affected, this
greatly simplifies maintenance.

KEYWORDS AND THEIR PURPOSES:

• REPLACE: It recreates the procedure if it already exists.

• PROCEDURE: It is the name of the procedure to be created.

• ARGUMENT: It is the name of the argument to the procedure. Parenthesis can be


omitted if no arguments are present.
• IN: Specifies that a value for the argument must be specified when calling the
procedure ie., used to pass values to a sub-program. This is the default parameter.

• OUT: Specifies that the procedure passes a value for this argument back to it’s calling
environment after execution ie. used to return values to a caller of the sub-program.

• INOUT: Specifies that a value for the argument must be specified when calling the
procedure and that procedure passes a value for this argument back to its calling
environment after execution.

• RETURN: It is the data type of the function’s return value because every function
must return a value, this clause is required.

Procedure and function blocks:

Procedure:

- No return.

- PROCEDURE name IS

Function:

- Returns a value

- FUNCTION name RETURN data-type IS

Note: The AS keyword is used instead of the IS keyword for creating a standalone procedure.

PROCEDURE

Syntax :

create or replace procedure <procedure name> (argument {in,out,inout} datatype) {is,as}


variable declaration;
constant declaration;
begin
PL/SQL subprogram body;
exception
exception PL/SQL block;
end;
Example Program: create a procedure to find area and circumference of circle

CREATE OR REPLACE PROCEDURE circle_area_circum (radius in number,area out number,


circumference out number) is
BEGIN
area:=3.14 * radius * radius;
circumference:=2 * 3.14 * radius;
END circle_area_circum;
/
Procedure Usage for the above:

• set serveroutput on

DECLARE
r number(10):=2;
a number(10,3):=0;
c number(10,5):=0;
BEGIN
circle_area_circum(r,a,c); --- call to procedure
dbms_output.put_line(r||' '||a||' '||c);
END;
/

Out put:
2 12.56 12.56
FUNCTION

Creating a Function

▪ A function is very similar to a procedure

▪ Both take arguments, which can be of different modes

▪ Both are different forms of PL/SQL blocks, with a declarative executable, and
exception section.

▪ Both can be stored in the database or declared within a block

▪ However, a procedure call is a PL/SQL statement by itself, while a function call is


called as part of an expression

Function Syntax

The syntax for creating a stored function is very similar to the syntax for a procedure

CREATE [OR REPLACE] FUNCTION function_name


[(argument[{IN|OUT|INOUT}] type,

argument[{IN|OUT|INOUT}] type)]
RETURN return_type {IS|AS}
Function_body
RETURN statement is used to return control to the calling environment with a value
The general syntax of the RETURN statement is
RETURN expression;
where expression is the value to be returned
Example Program:

create or replace function concatenate(pfirst in varchar2, plast in varchar2) return varchar2


is

begin
return pfirst||plast; /* returning concatenated name */
end concatenate;
/

Function Usage for the above:


set serveroutput on

Declare
fname varchar2(10):=’hello’;
lname varchar2(10):='world';
coname varchar2(20);
begin
coname:=concatenate(fname,lname);
dbms_output.put_line(coname);
end;
/

Output: helloworld

You might also like