You are on page 1of 27

1

Database Application Development


SSK 3408

Chapter 4
Transaction
Introduction
An application might face problems such as:
a power failure
a hardware crash
some accidently unplugs a cable, etc.

Such problems can be minimized by:


implementing backup and recovery procedures
storing duplicate data to different drives
Installing uninterruptible power supplies (UPS)

Nevertheless, failure at the wrong time can have


serious consequences.
Issues of Transaction Failure
A transaction is a set of changes that must all be
made together.
For example, transaction for transferring money
from savings account to a current account consists of:
Subtract
money form savings account
Add money to current account

What happen if the machine crashes after


subtracting the money but before adding the
money to current account?????
Illustration of Transferring Money

Transaction Savings Accounts


1. Subtract $1000 from savings.
(machine crashes) Salmi: 5340.92
2. Add $1000 to Checking. 4340.92
(money disappears) $1000
Checking Accounts

Salmi: 1424.27
Transaction Issues
How do we know that both operations are in the
same transaction?
And, how does the computer know that both
operation must be completed together?
How do we tell the computer system which
operations belong to a transaction?
Transaction Issues ..cont.
Business rules define what operations should be in a
transaction.
The application developer responsible to tell the
computer system which operation belong in a
transaction.
By marking the start and the end of transaction in your
code.
When the computer sees the start marking, it first writes
all the changes to a log file. When it reaches the end
mark, it makes the actual changes to the data in the
correspond tables.
Defining Transaction
The computer needs to be told which changes must
be grouped into a transaction.
Turn on transaction processing.

Signify a transaction start.

Signify the end.

Success: save all changes


Failure: cancel all changes
Must be set in module code.
ORACLE : Microsoft Access:
Start Transaction BeginTrans
Commit CommitTrans
Rollback RollbackTrans

7
SQL Transaction Code
8

CREATE FUNCTION TransferMoney(Amount Currency, AccountFrom Number,


AccountTo Number) RETURNS NUMBER
curBalance Currency;
BEGIN
DECLARE HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
Return -2; -- flag for completion error
END;
START TRANSACTION; -- optional
SELECT CurrentBalance INTO curBalance
FROM Accounts WHERE (AccountID = AccountFrom);
IF (curBalance < Amount) THEN
RETURN -1; -- flag for insufficient funds
END IF
UPDATE Accounts
SET CurrentBalance = CurrentBalance Amount
WHERE AccountID = AccountFrom;
UPDATE Accounts
SET CurrentBalance = CurrentBalance + Amount
WHERE AccountID = AccountTo;
COMMIT;
RETURN 0; -- flag for success
END;
SAVEPOINT
9
SAVEPOINT
start StartOptional commit
Required elements Risky steps
time
Partial
rollback

START TRANSACTION;
SELECT
UPDATE
SAVEPOINT StartOptional;
UPDATE
UPDATE
If error THEN
ROLLBACK TO SAVEPOINT StartOptional;
END IF
COMMIT;
Example:
START TRANSACTION;
SELECT * FROM EMPLOYEE;
UPDATE EMPLOYEE SET SALARY = SALARY * 1.05
UPDATE TOTAL SET SAL =
SAVEPOINT StartOptional;
INSERT INTO PAYSLIP VALUES (SELECT EMPID, , SALARY * 1.05)
If error THEN
ROLLBACK TO SAVEPOINT StartOptional;
END IF
COMMIT;
Concurrent Access
Concurrent Access Two processes
Multiple users or processes Receive payment ($200)
changing the same data at Place new order ($150)
the same time.
Initial balance $800
Final data will be wrong!
Result should be $800 -200
Force sequential + 150 = $750
Locking Interference result is either
Delayed, batch updates $600 or $950

Receive Payment Customers


Place New Order
ID Balance
Jones $800
1) Read balance 800 3) Read balance 800
2) Subtract pmt -200 $600 5) Add order 150
4) Save new bal. 600 $950 6) Write balance 950
11
Concurrent Access Steps

Receive Payment Balance Place New Order


1. Read balance 800 800
2. Subtract Pmt. -200 3. Read balance 800
600
4. Save balance 600 5. Add order 150
950 6. Write balance 950

12
Pessimistic Locks: Serialization
13

One answer to concurrent access is to prevent it.


When a transaction needs to alter data, it places a SERIALIZABLE lock
on the data used, so no other transactions can even read the data until
the first transaction is completed.

SET TRANSACTION SERIALIZABLE, READ WRITE


Customers
Receive Payment Place New Order
ID Balance
Jones $800 3) Read balance
1) Read balance 800
$600 Receive error
2) Subtract pmt -200
message that it is
4) Save new bal. 600
locked.
SQL Pessimistic Locks: Serialization
14

CREATE FUNCTION ReceivePayment (


AccountID NUMBER, Amount Currency) RETURNS NUMBER
BEGIN
DECLARE HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RETURN -2;
END
SET TRANSACTION SERIALIZABLE, READ WRITE;
UPDATE Accounts
SET AccountBalance = AccountBalance - Amount
WHERE AccountNumber = AccountID;
COMMIT;
RETURN 0;
END
Serialization Effects

Receive Payment Balance Place New Order


1. Read balance 800 800
2. Subtract Pmt. -200 3. Read balance
600 Error: Blocked
4. Save balance 600 3. Read balance 600
750 4. Add order 150
5. Write balance 750

15
Transaction to Transfer Money
16

CREATE FUNCTION ReceivePayment (


AccountID NUMBER, Amount Currency) RETURNS
NUMBER
BEGIN
DECLARE HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RETURN -2;
END
SET TRANSACTION SERIALIZABLE, READ WRITE;
UPDATE Accounts
SET AccountBalance = AccountBalance - Amount
WHERE AccountNumber = AccountID;
COMMIT;
RETURN 0;
END
Deadlock
Deadlock
Two (or more) processes have placed 1) Lock Data A
locks on data and are waiting for the 3) Wait for Data B
others data.
Solutions:
Random wait time
Global lock manager Data A Data B
Two-phase commit mechanism

2) Lock Data B
4) Wait for Data A
Deadlock Sequence

Process 1 Data A Data B Process2


1. Lock Data A
Locked Locked 2. Lock Data B
3. Wait for Data B by 1 by 2
4. Wait for Data A

18
Solution 1: Random Wait Time
When a process receives a message that is must
wait for a resource:
the process wait for a random length of time,
try again,

release all existing locks (i.e. rollback statement) and

start over if cannot obtain the resource.

Easy to program but it cause a lot of time waiting


particularly when there are many active processes.
Solution 2: Global Lock Manager
A lock manager monitors every lock and wait.
If the lock manager detects a potential deadlock, it
will tell some of the processes to release their locks,
allow other processes to proceed, and then restart
the other processes.
Efficient as processes do not spent time for waiting.
However, it is implemented within DBMS itself and
the lock manager must be able to monitor every
process and its locks.
Lock Manager
21
Resource Resource Resource Resource Resource
A B C D E
Process1 Lock Wait

Process2 Wait Lock

Process3 Lock

Process4 Lock Wait

Process5 Wait

Process6 Wait Lock

Process7 Wait Wait


Solution 3: Two-phase commit
The DBMS handles concurrent access and deadlock
resolution automatically.
When write code to change data, the DBMS still tries
to handle the situation automatically.
However, the DBMS may rely on the developer to
back out your transaction.
Some systems may simply generate an error when the
second process attempts to access the data and it is
the developer responsibility to catch the error and
handle the problem.
Optimistic Locks
23

Pessimistic locks and handling deadlocks was


relatively standard in many systems for several
years.
However, as computer system performance
increase, DBMS can process transaction faster
and resulting in a lower probability of
concurrency problems, a new approach seems to
gain favor.
Optimistic locks assume that collisions are rare
and unlikely to arise.
Optimistic Locks
24

Allow all code to read any data (no locks)


When code tries to write a new value
Check to see if the existing value is different from the
one you were given earlier
If it is different, someone changed the database
before you finished, so it is a collision--raise an error
Reread the value and try again

It can improve performance, but it requires us to


deal with the collisions.
Optimistic Locks for Simple Update
25

(1) Read the balance


(2) Add the new order value
(3) Write the new balance
(4) Check for errors
(5) If there are errors, go back to step (1).
Optimistic Locks with SQL
26

CREATE FUNCTION ReceivePayment (


AccountID NUMBER, Amount Currency) RETURNS NUMBER
oldAmount Currency;
testEnd Boolean = FALSE;
BEGIN
DO UNTIL testEnd = TRUE
BEGIN
SELECT Amount INTO oldAmount
WHERE AccountNumber = AccountID;

UPDATE Accounts
SET AccountBalance = AccountBalance - Amount
WHERE AccountNumber = AccountID
AND Amount = oldAmount;
COMMIT;
IF SQLCODE = 0 and nrows > 0 THEN
testEnd = TRUE;
RETURN 0;
END IF
-- keep a counter to avoid infinite loops
END
END
ACID Transactions
27

Atomicity: all changes succeed or fail together.


Consistency: all data remain internally consistent
(when committed) and can be validated by
application-defined checks.
Isolation: The system gives each transaction the
perception that it is running in isolation. There are
no concurrent access issues.
Durability: When a transaction is committed, all
changes are permanently saved even if there is a
hardware or system failure.

You might also like