0% found this document useful (0 votes)
3 views70 pages

Topic 5 - Database Transaction Management

The document covers database transaction management, outlining key concepts such as transaction systems, types of transaction processing systems (batch, online, and real-time), and properties of database transactions (atomicity, consistency, isolation, and durability). It also discusses concurrency control, its purpose, potential problems (lost update, uncommitted data, inconsistent retrieval), and methods for managing concurrency through locking techniques. Additionally, it explains SQL transaction management with commands like START TRANSACTION, COMMIT, and ROLLBACK.

Uploaded by

Siva Kumar
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)
3 views70 pages

Topic 5 - Database Transaction Management

The document covers database transaction management, outlining key concepts such as transaction systems, types of transaction processing systems (batch, online, and real-time), and properties of database transactions (atomicity, consistency, isolation, and durability). It also discusses concurrency control, its purpose, potential problems (lost update, uncommitted data, inconsistent retrieval), and methods for managing concurrency through locking techniques. Additionally, it explains SQL transaction management with commands like START TRANSACTION, COMMIT, and ROLLBACK.

Uploaded by

Siva Kumar
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/ 70

DFC20123

DATABASE DESIGN
TOPIC 5
DATABASE TRANSACTION MANAGEMENT

Prepared by:
Harzulaili Bt Saleh
COURSE LEARNING OUTCOME
Upon Completion Of This Course, Students Should Be Able To:

CLO 1 :
Apply Fundamental Of Database Management System (DBMS), Relational Data
Model And Normalization Concepts In Database Development Process. ( C3, PLO 2 )
CLO 2 :

Show A Well-structured Database Using The Database Query To Manipulate A


Database With An Appropriate Commercial Database Management System (Dbms)
In Solving An Organization’s Requirements. ( P2, PLO 3 )

3
5.1.1 TRANSACTION SYSTEM
TRANSACTION?
• an action, or series of actions that are being performed by a single user
or application program, which reads or updates the contents of the
database
• can be defined as a logical unit of work on the database.
• may be an entire program, a piece of a program or a single command
(like the SQL commands such as INSERT or UPDATE) and
• may engage in any number of operations on the database
• in the database context, the execution of an application program can be
thought of as one or more transactions with non-database processing
taking place in between.

4
5.1.1 TRANSACTION SYSTEM
Example of TRANSACTION

Open_Acc (Ahmad)

OldBal = Ahmad.bal

NewBal = OldBal - 5000

Ahmad.bal = NewBal

CloseAccount(Ahmad)

5
6
5.1.2 CATEGORIES OF TRANSACTION PROCESSING SYSTEM

a) Batch transaction processing system


b) On-line transaction processing system (OLTP)
c) Real time transaction processing system

7
5.1.2 CATEGORIES OF TRANSACTION PROCESSING SYSTEM
a) Batch transaction processing system
o transactions are accumulated over a period of time and processed as
a single unit, or batch
o Batch processing is a method of processing data in which data is
collected at the time of the event.
o e.g :
i. a store may update its sales records every day after the store closes.
ii. a payroll system may process all the time cards every two weeks to determine
employee earnings and produce paychecks.
iii. An example of batch processing is the way that credit card companies process
billing. The customer does not receive a bill for each separate credit card
purchase but one monthly bill for all of that monthly purchases. The bill is
created through batch processing, where all of the data are collected and held
until the bill is processed as a batch at the end of the billing cycle.

8
5.1.2 CATEGORIES OF TRANSACTION PROCESSING SYSTEM

a) Batch transaction processing system

9
5.1.2 CATEGORIES of TRANSACTION PROCESSING SYSTEM
b) On-line transaction processing system (OLTP)
• a class of software programs capable of supporting transaction-
oriented applications on the Internet
• are used for order entry, financial transactions, customer relationship
management and retail sales
• E.g: ATM
• Such systems have a large number of users who conduct short
transactions
• All transactions are processed immediately, without delay.

10
5.1.2 CATEGORIES of TRANSACTION PROCESSING SYSTEM

b) On-line transaction processing system (OLTP)

11
5.1.2 CATEGORIES OF TRANSACTION PROCESSING SYSTEM
c) Real time transaction processing system
• transactions are processed immediately as they occur without any
delay to accumulate transactions
• the records in the system always reflect the current status
• e.g: airline ticket reservations
• When you book a ticket and select a seat, that booking is made
right away, and nobody else can get that same seat even a
second later.
• Any changes you make to your reservation are also updated in
real time.

Airline Hotel Car


Reservations Reservations Rentals

12
5.1.2 CATEGORIES OF TRANSACTION PROCESSING SYSTEM
c) Real time transaction processing system

13
5.1.3 PROPERTIES OF DATABASE TRANSACTION

14
5.1.3 PROPERTIES OF DATABASE TRANSACTION
• ATOMICITY
All transaction must remain whole. That is, it must completely succeed
or completely fail.
A transaction is an atomic unit. Hence, all the instructions within a
transaction will successfully execute, or none of them will execute.
E.g: The following transaction transfers 20 dollars from Alice’s bank
account to Bob’s bank account. If any of the instructions fail, the entire
transaction should abort and rollback.

15
• CONSISTENCY
A database is initially in a consistent state, and it should remain
consistent after every transaction.
For example:
1. in an application that transfers funds from one account to
another, the consistency property ensures that the total value of
funds in both the accounts is the same at the start and end of each
transaction.
2. Suppose that the transaction in the previous example fails after
Write(A_b) and the transaction is not rolled back; then, the
database will be inconsistent as the sum of Alice and Bob’s money,
after the transaction, will not be equal to the amount of money
they had before the transaction.

16
5.1.3 PROPERTIES OF DATABASE TRANSACTION
• ISOLATION
Each transaction should carry out its work independently of any other
transaction that might occur at the same time.
If the multiple transactions are running concurrently, they should not be
affected by each other. The result should be the same as the result
obtained if the transactions were running sequentially.
For example:
1. in an application that transfers funds from one account to another, the
isolation property ensures that another transaction sees the transferred
funds in one account or the other, but not in both, nor in neither.
2. Suppose B_bal is initially 100. If a context switch occurs after B_bal *= 20,
then the changes should only be visible to T2 once T1 commits. This ensures
consistency in the data and prevents incorrect results.

17
• DURABILITY
Changes that have been committed to the database should remain
even in the case of software and system failure
For Example:
1. In An Application That Transfers Funds From One Account To
Another. The Durability Property Ensures That The Changes Made To
Each Account Will Not Be Reversed.
2. For instance, if Bob’s account contains $120, this information
should not disappear upon system or software failure.

18
19
5.1.4 PERFORM TRANSACTION USING SQL STATEMENT

• A database transaction consists of one or more statements.


• Specifically, a transaction consists of one of the following:
– One DDL statement
– One or more DML statements that together constitute an
atomic change to the database
• A transaction has a beginning and an end.

20
5.1.5 USE START TRANSACTION & COMMIT

• START TRANSACTION OR BEGIN


– A transaction begins when the first executable
SQL statement is encountered.
– The command :
• START TRANSACTION

21
5.1.5 USE START TRANSACTION & COMMIT

• Ends the current transaction and saves any


changes made to tables, table memo files, or
index files included in a transaction.
– The command :
• END TRANSACTION

22
5.1.5 USE START TRANSACTION & COMMIT

• A COMMIT statement is reached, in which case all changes


permanently recorded within the database. The COMMIT
statement automatically ends the SQL transaction
• A ROLLBACK statement is reached, in which case all the changes
are aborted and the database is rolled back to its previous
consistent state.
• The end of program is successfully reached, in which case all
changes are permanently recorded within the database. This action
is equivalent to COMMIT
• The program is abnormally terminated, in which case the changes
made in the database are aborted and the database is rolled back
to its previous consistent state. This action is equivalent to
ROLLBACK 23
5.1.5 USE START TRANSACTION & COMMIT

EXAMPLE:

START TRANSACTION

UPDATE customers
SET ContactName=‘Jenn’
WHERE CustomerId = ‘XYZ’;

COMMIT TRANSACTION

These statement will writes directly to disk.

24
5.1.5 USE START TRANSACTION & COMMIT

EXAMPLE:

START TRANSACTION

UPDATE customers
SET ContactName=‘David’
WHERE CustomerId = ‘XYZ’;

ROLLBACK TRANSACTION

The ROLLBACK TRANSACTION statement “undoes” all the work since


the matching BEGIN TRANSACTION
25
5.1.5 USE START TRANSACTION & COMMIT

A transaction begins when the START


TRANSACTION statement is encountered and ends
when one of the following occurs:
– A COMMIT or ROLLBACK statement is issued
– A DDL statement, such as CREATE is issued
– The user exits the DBMS
– A machine fails or the system crashes

26
CONCURRENCY CONTROL

• Concurrency - allow many transactions to access the


same data at the same time

• The coordination of the simultaneous execution of transactions


in a multiprocessing database

o Objective: to ensure the serializability of transactions in a


multiuser database environment

27
5.1.6 PURPOSE OF CONCURRENCY CONTROL

• Purpose :
• to ensure that concurrent transactions do not
interfere with each other's operation.
• to ensure that several users trying to update the same
data do so in a controlled manner so that the result of
the updates is correct.
• Example:
Several reservation clerks try to assign a hotel room; the
DBMS should ensure that only one clerk could access each
hotel room at a time for assignment to a customer.

28
5.1.6 PURPOSE OF CONCURRENCY CONTROL

• Process of managing simultaneous operations on the


database without having them interfere with one another
• Prevents interference when two or more users access
database simultaneously and at least one updates data
• Interleaving of operations may produce incorrect results

29
5.1.7 PROBLEMS OF CONCURRENCY CONTROL

a. Lost update
b. Uncommitted data
c. Inconsistent retrieval

30
A. LOST UPDATE
• Occur when two transactions, accessing the same data items,
have their operations interleaved in such a way, that one
transaction will access the data before the other has applied
any updates.

• Successfully completed update overridden by another


user
• Example:
– T1 withdrawing RM10 from an account with balx, initially RM100
– T2 depositing RM100 into same account
– Serially, final balance would be RM190

31
A. LOST UPDATE

• Loss of T2’s update avoided by preventing T1


from reading balx until after update
32
LOST UPDATE PROBLEM

33
B. UNCOMMITTED DATA

• Occurs when one transaction can see intermediate


results of another transaction before it has committed

• one transaction updates an item of the database, and


then the transaction fails for some reason.
The updated database item is accessed by another
transaction before it is changed back to the original
value

• aka Dirty Read


34
B. UNCOMMITTED DATA

• Example:
– T4 updates balx to RM200 but it aborts, so balx should be back at
original value of RM100
– T3 has read new value of balx (RM200) and uses value as basis
of RM10 reduction, giving a new balance of RM190, instead
of RM90

35
B. UNCOMMITTED DATA

• Problem avoided by preventing T3 from reading balx until after T4 commits or


aborts.
• Because of failure, the transaction is rolled back and the data item is returned
to its previous value. A second transaction accesses the updated data item
before it is returned to its original value.

36
C. INCONSISTENT RETRIEVAL
• Occurs when a transaction calculates some summary
function over a set of data while the other transactions
are updating the data
 Some data may be read after they are changed and some before they are
changed yielding inconsistent results
• aka unrepeatable read
• Example:
– T6 is totaling balances of account x (RM100), account y
(RM50), and account z (RM25).
– Meantime, T5 has transferred RM10 from balx to balz, soT6
now has wrong result (RM10 too high).

37
C. INCONSISTENT RETRIEVAL

• Problem avoided by preventing T6 from reading balx and


balz until after T5 completedupdates
38
5.1.8 CONCURRENCY CONTROL WITH LOCKING
METHOD

• One of the main techniques used to control concurrency


execution of transactions (to provide serializable execution
of transactions) is based on the concept of locking data
items

39
5.1.8 CONCURRENCY CONTROL WITH LOCKING METHOD

•Lock
 Guarantees exclusive use of a data item to a current
transaction
 T2 does not have access to a data item that is
currently being used by T1
 Transaction acquires a lock prior to data access;
the lock is released when the transaction is
complete
 Required to prevent another transaction from
reading inconsistent data

•Lock manager
 Responsible for assigning and policing the locks used
by the transactions
40
5.1.8 CONCURRENCY CONTROL WITH LOCKING METHOD

a. Lock Granularity
b. Lock Types
c. Two Phase Locking to ensure serializability
d. Deadlocks

Concurrency control and locking is the mechanism used


by DBMSs for the sharing of data.
Atomicity, consistency, and isolation are achieved through
concurrency control and locking.

41
A. LOCK GRANULARITY
• Locks may be placed at various levels (known as lock granularity)
• Some database products (Sybase, IBM’s DB2) support
multiple levels with automatic lock escalation
• Typical lock level:
• Database - entire database is locked
• File - entire database file is locked
• Table - entire table is locked
• Block or page - block/page within database file is locked
• Row - row in a table is lock
• Column - some columns within a row in the table are locked

• Locks are always placed when data is updated or deleted

42
B. LOCK TYPES
Three types of locks (lock modes) :
i. read lock (rl) – also called shared lock
ii. write lock (wl) – also called exclusive lock
iii. binary lock - a lock on a data item can be in two states; it is
either locked or unlocked.

 Allowing more than one transaction to write on the same data item
would lead the database into an inconsistent state.
 Read locks are shared because no data value is being changed.

43
C. TWO-PHASE LOCKING (2PL) TO
ENSURE SERIALIZABILITY
• Defines how transactions acquire and release locks
• Guarantees serializability, but it does not prevent deadlocks
 Growing phase, in which a transaction acquires all the
required locks without unlocking any data
 Shrinking phase, in which a transaction releases all locks and
cannot obtain any new lock

44
C. TWO-PHASE LOCKING (2PL) TO ENSURE
SERIALIZABILITY
• Governed by the following rules:
o Two transactions cannot have conflicting locks
o No unlock operation can precede a lock operation in the
same transaction
o No data are affected until all locks are obtained—that is,
until the transaction is in its locked point

45
C. TWO-PHASE LOCKING (2PL) TO ENSURE
SERIALIZABILITY
 The lock point is the moment when transitioning from the
growing phase to the shrinking phase

46
C. TWO-PHASE LOCKING (2PL) TO ENSURE
SERIALIZABILITY

47
C. TWO-PHASE LOCKING (2PL) TO ENSURE
SERIALIZABILITY
• Properties of the 2PL protocol
 Generates conflict-serializable schedules

 But schedules may cause cascading aborts


∗ If a transaction aborts after it releases a lock, it may cause
other transactions that have accessed the unlocked data
item to abort as well

48
PREVENTING LOST UPDATE USING 2PL

49
PREVENTING UNCOMMITTED DATA USING 2PL

50
PREVENTING INCONSISTENT RETRIEVAL USING 2PL

51
D. DEADLOCKS

A deadlock is a condition where two or more transactions are


waiting indefinitely for one another to give up locks.

an impasse that may result when two ( or more ) transactions are


each waiting for lock held by the other to be released

52
For example: In the student table, transaction T1 holds a lock on some rows
and needs to update some rows in the grade table. Simultaneously, transaction
T2 holds locks on some rows in the grade table and needs to update the rows
in the Student table held by Transaction T1.

53
EXAMPLE :

54
• T1 needs data items X and Y; T2 needs Y and X
• Each gets the its first piece of data but then waits to get the second
(which the other transaction is already holding)

 Possible only if one of the transactions wants to obtain an


exclusive lock on a data item
No deadlock condition can exist among shared locks

 Control through:
Prevention
Detection
Avoidance

55
• To break deadlock: abort one or more of transactions
– Deadlock transparent to user
– DBMS restarts transaction(s)

• Three techniques for handling deadlock:


– Timeouts
– Deadlock prevention
– Deadlock detection and recovery

56
5.1.9 DATABASE RECOVERY MANAGEMENT

• Ensures database is fault tolerant, and not corrupted by


software, system or media failure
• Recovery Manager
– When a DBMS is restarted after crashes, the recovery manager must
bring the database to a consistent state
– Ensures transaction atomicity and durability
– Undos actions of transactions that do not commit
– Redos actions of committed transactions during system failures and
media failures (corrupted disk).
• Recovery Manager maintains log information during normal
execution of transactions for use during crash recovery

57
5.1.9 DATABASE RECOVERY MANAGEMENT

a) Database recovery
b) Transaction recovery
c) Database back-up

58
A. DATABASE RECOVERY TECHNIQUE

• Restores Database From A Given State, Usually Inconsistent,


To A Previously Consistent State
• System Must Keep Information That Enables Recovery From
Failures.
• If Transaction Operation Cannot Be Completed, Transaction
Must Be Aborted, And Any Changes To The Database Must Be
Rolled Back (Undone)

59
A. DATABASE RECOVERY TECHNIQUE

• A Typical Strategy For Recovery Includes:


• If Database Is Physically Damaged (E.G., Disk Crash), Then
Recovery Method Restores A Past Copy Of The Database
• Recovery From Non-catastrophic (Transaction) Failures May
Imply A Redo/Undo Of Some Operations (This Can Be Done
By Information Kept In The System Log).

60
A. DATABASE RECOVERY TECHNIQUE

• Database Recovery From Failures


• Example Of Failures:
• System Crash (Hardware, Software, Network Error Occurs During
Transaction Execution)
• Transaction Error(some Operation [E.G. Div By 0, Overflow] In The
Transaction May Cause It To Fail)
• Exception Conditions, Detected By The Transaction (Data Not Found)
• Concurrency Control Enforcement(serializability, Deadlock)
• Disk Failure, (Read/Write Phase)
• Physical Problems(theft)

61
B. TRANSACTION RECOVERY
Some approaches for recovery from non-catastrophic
(transaction) failures can be classified as either:

 Deferred update: (NO-UNDO, REDO)


 The database is not physically updated until after a transaction
reaches its commit point.
 UNDO is not needed
 REDO may be necessary

 Immediate update: (UNDO, NO-REDO)


 The database is physically updated before the transaction reaches to
its commit point.
 UNDO may be necessary when a transaction fails
 REDO is not needed

62
B. TRANSACTION RECOVERY
Deferred update

• Can be classified as a no-steal approach.


• It obey the following rules:
1. A transaction cannot change the database on disk until it reaches its
commit point
2. A transaction does not reach its commit point until all its update
operations are recorded in the log and the log is force-written to
disk.

Because the database is never updated on disk until after the


transaction commits, there is never the need to UNDO
any operations (that is why a deferred update is known
as NO-UNDO/REDO recovery algorithm).

63
B. TRANSACTION RECOVERY

64
B. TRANSACTION RECOVERY

Immediate update

• In immediate update techniques, although the database can be updated


immediately, update operations must be recorded in the log (on disk)
before being applied to the database.
• There is never a need to REDO any operations of committed transactions
(this is called the UNDO/ NO-REDO recovery algorithm).
• The effect of all active transactions at the time of failure must be undone.

65
B. TRANSACTION RECOVERY

Immediate update

PROCEDURE of RIU:

 UNDO all the WRITE_ITEM operations of the active


(uncommitted) transactions from the log. The operations
should be done in the reverse of the order in which they were
written into the log.
 Restart the active transactions.

66
C. DATABASE BACKUP
• A Backup, Or The Process Of Backing Up, Refers To The
Copying And Archiving Of Computer Data So It May Be Used
To Restore The Original After A Data Loss Event.

67
C. DATABASE BACK-UP

68
C. DATABASE BACKUP

• How To Back Up A Mysql Database

• Backing Up Using Phpmyadmin

• It Is Assumed That You Have Phpmyadmin Installed Since A Lot Of Web Service Providers Use It.

• To Backup Your Mysql Database Using Phpmyadmin Just Follow A Couple Of Steps:

• Open Phpmyadmin.

• Select Your Database By Clicking The Database Name In The List On The Left Of The Screen.

• Click The Export Link. This Should Bring Up A New Screen That Says View Dump Of Database (Or
Something Similar).

• In The Export Area, Click The Select All Link To Choose All Of The Tables In Your Database.

• In The Sql Options Area, Click The Right Options.

• Click On The Save As File Option And The Corresponding Compression Option And Then Click The 'Go'
Button. A Dialog Box Should Appear Prompting You To Save The File Locally.

69
70

You might also like