0% found this document useful (0 votes)
12 views62 pages

INF20010 LEC 05 Trans Concurrency VBTrans-1

Uploaded by

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

INF20010 LEC 05 Trans Concurrency VBTrans-1

Uploaded by

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

INF20010

Database Systems
Lecture 5
 Transactions
 Commit
 Rollback
 ACID properties
 Concurrency Control
 Select … For Update
 VB Transaction
2
Transactions & concurrency
 This semester you have built some databases

 You have inserted , updated , deleted and selected rows from


various tables.
 You have been the sole user
 You haven't needed to consider what happens when two users
want to update the same row at the same time
 E.g. two customers both purchase Product P009 at
the same time (and thereby change the qty_on_hand value)
3
Transactions & concurrency
 Databases: single user scenarios vs. multi user scenarios
 A DBMS has to deal with multiple concurrent transactions
 Multiple users may be execute the same transaction code at the
same time
 The code of that transaction could easily be executed two
different users simultaneously
 The same table and/or row can be used in an update
statement at the same time
 Multiple users may execute different transactions
at the same time
 The same table and/or row can be used in update
statement at the same time
4
Transactions & concurrency
 Imagine we have a screen which enables users to purchase tickets
 The user types an Event Code and then
clicks Search
 The tickets available textbox
is populated
 Note: We do not have numbered
tickets or seating numbers.

Event
EventID Integer Primary Key,
EventName Varchar2(100),
TicketsAvailable Integer );
5
Transactions & concurrency
 The user wishes to purchase 6 tickets
 The user types the qty required and presses
the Buy button
6
Transactions & concurrency
 The SQL statements might look something like this:

SELECT TicketsAvailable INTO TicketsAvailableTextBox.Text


FROM EventTable
WHERE eventid = EventTextBox.Text

UPDATE EventTable
SET TicketsAvailable = TicketsAvailableTextBox.Text - TicketsRequiredTextBox.Text
WHERE eventid = EventTextBox.Text;

INSERT INTO TicketSalesTable (TicketSaleId, EventId, Qty)


VALUES (TicketSeq.NextVal, EventTextBox.Text, TicketsRequiredTextBox.Text)

COMMIT;
 The syntax above may need slight changes to work correctly. This is an overview of the process.
7
Transactions & concurrency
 After the sale of the tickets, the Sales Form is updated to reflect the
tickets now available
 100 at beginning – 6 sales = 94 ticket available
8
Transactions & concurrency
 You could imagine this process continuing.
 Users continue to purchase tickets
 It all seems OK.
9
Transactions & concurrency
 What happens in a multi-user environment?
 BOTH users view a Sales Form on their computer
 BOTH users search for the same Event
 BOTH users see the TicketsAvailable value for the event

USER 1 USER 2
10
Transactions & concurrency
 User1 clicks the Buy button. The SQL statements are executed
UPDATE EventTable
SET ticketsavailable = TicketsAvailableTextBox.Text - TicketsRequiredTextBox.Text;

ticketsavailable is set to 97 i.e. (100 – 3)


Before After
User 1 User 1

97
11
Transactions & concurrency
 User2 clicks the Buy button. The SQL statements are executed
UPDATE EventTable
SET ticketsavailable = TicketsAvailableTextBox.Text - TicketsRequiredTextBox.Text;

ticketsavailable is set to 92 i.e. (100 – 8)


Before After
User 2 User 2

92
12
Transactions & concurrency
 Something has gone wrong.

 11 tickets in total were purchased


by the two users.

 However, user2 has just updated


the TicketsAvailable column
and set it to a value of 92 User 2

 This is called a LOST UPDATE

92
13
Lost Update problem
 This is referred to as a Lost Update problem.

 One transaction overwrites the results of another transaction.

 This is because the system has not dealt with the possibility
of multiple users updating the same data rows at the same time.

 Lost Updates lead to a database having an inconsistent state

 Lost Updates must be avoided.


14
Lost Update problem
 The same transaction is executed twice by two different users…
 The steps in the transactions are being executed concurrently
 Trans2 is a step behind Trans1

Trans1 Trans2 Available


Tickets
Begin 100
read Available Tickets (AT) Begin 100
DOPL (AT) -- 100 is shown read Available Tickets (AT) 100
AT = AT - 3 -- AT is now 97
Write AT -- 97 written to table 97
DOPL(AT) -- 100 is shown
AT = AT - 8 -- AT is now 92
Write AT -- 92 written to table 92
Commit --change is permanent 92
Commit --change is permanent 92
15
Using a Locking strategy
 DBMSs have the ability to lock rows in tables.
 There are generally two types of locking mechanism

 Shared Locks
 While a row has a Shared Lock placed on it
 The row can be read by other transactions
 The row cannot be updated by other transactions

 Exclusive Locks
 While a row has a Exclusive Lock placed on it
 The row cannot be read by other transactions
 The row cannot be updated by other transactions
16
Lock Granularity
 Lock Granularity
 This refers to how large a section of the database you need to lock.

 Possible options include:


 Database (overkill)
 Table, Index (avoid using this)
 Predicate
 E.g. Use a condition such as WHERE prodid = 'P205';
 Row
17
Uncommitted Read / Dirty Read problem
 Imagine that we change the previous scenario slightly
 When a user clicks the BUY button
 We update tickets available by the required quantity
 We check that the credit card details supplied by the
customer are valid and that there are enough funds.
 If there credit authorisation fails then

Rollback the transaction
 Otherwise

Commit the transaction
18
Uncommitted Read / Dirty Read problem
 Imagine the TicketsAvailable value for event EV1 is 10
 USER 1
 Required Tickets : 8
 Clicks Buy
 Update TicketsAvailable value. Set it to 2
 Waiting for credit authorization …

 USER 2
 Required Tickets : 5
 Sees that only 2 TicketsAvailable
 Exit Sales Form. User misses out on tickets for the event
19
Uncommitted Read / Dirty Read problem
 But wait…
 User 1's credit authorization fails. The credit limit is exceeded!
 USER 1
 Rollback the transaction

All updates created by the transaction are reveresed

TicketsAvailable value 10
 USER 2
 Has no knowledge of this
 User misses out on tickets for the event
 Users 2 had read data that was not committed
 This is known as an Uncommitted Read or Dirty Read

This is dangerous. Unstable data is being used.

The database is not in a Consistent State yet
20
Transaction Isolation
 There are various techniques used to stop transactions
interfering with each other

 Some techniques can be implemented automatically by the DBMS


 Some techniques require the programmer to do most of the work
via code

 Sometimes a combination of both is required.

 The complexity of the transaction will influence the approach

 We need to discuss the topic of Transaction Isolation


21
ACID Properties of a Transaction
 Atomicity
 A transaction is indivisible. Performed in its entirety or not at all.
 Implemented by COMMIT and ROLLBACK

 Consistency
 A transaction takes database from one consistent state to another.
 Implemented by database integrity constraints.

 Isolation
 Transactions are isolated from one another. A transaction that

works correctly in isolation is guaranteed to work correctly


when run concurrently with other transactions.
 Often implemented by locking

 Durability
 Ensures the results of a committed transaction cannot be lost, even

in the event of failure.


 Implemented by transaction logging and recovery
22
Serial Transactions
 How can we be sure a transaction will work correctly in a multiuser
environment?
 One way could be to run Transactions in a Serial sequence.
 Only one transaction ever occurs at a time
 Transaction 2 cannot begin until Transaction 1 is finished
Begin

Transaction 1 End

Begin

Transaction 2 End

Begin

Transaction 3 End
23
Isolation and Serializability
 Two transaction can be executed in perfect isolation if they run serially.
 Each transaction is consistent and isolated from all others

 Isolation is guaranteed
 the schedule is guaranteed to be correct for all applications.

 Running transactions as strictly serially causes problems


 Low throughput

 Poor response time

 Essentially, the DBMS is not allowed do two things at once

 DBMSs never run transactions serially


24
Isolation and Serializability
 To improve efficiency, transactions are often interleaved.
 Transactions run concurrently T1 Step 1
T2 Step 1
T1 Step 2
T2 Step 2
T1 Step 3
 The operations of one transaction can be freely T2 Step 3
T1 End
interleaved with another so long as they T2 Step 4
T2 End
do not conflict (do not operate on the same data)

 Two transactions can run concurrently (at the same time) so long as the
effect is the same as executing true serial execution.

 This is called Serializable Concurrency

 Serializable Concurrency is the strongest level of isolation


25
Example Transaction
 Consider a simple transaction that processes an order.

vprodId := 'P001'; PRODUCT(prodId,qty)


vSalesQty := 10;
SALES(ordId,prodId,OrderQty)
1. -- Read qty
SELECT qty INTO vQty
FROM PRODUCT WHERE ProdId = vProdId;
1
2. --Calculate new qty
vQty:= vQty – vSalesQty ;

3. --Update qoh
2 UPDATE PRODUCT SET qty = vQty
WHERE ProdId = vProdId ;

4. --Insert order
3 INSERT INTO SALES VALUES(SSeq.Nextval,vProdId,vOrderQty);

4
26
SERIALIZABLE Example
 Imagine two customers both purchasing products at the same time
 Results in two transactions are run concurrently
 TA for the purchase of product P001
 TB for the purchase of product P001

 Various schedules are possible for interleaving the operations.

1 2 3 4 1 2 3 4 Serial (1)
1 2 3 1 4 2 3 4 Serializable (1)
1 2 3 1 2 4 3 4 Serializable (2)
1 2 3 4 1 2 3 4 Serial (2)
27
Testing Schedules for SERIALIZABILITY
 Transactions which run under SERIALIZABLE isolation level
leave the database in the same consistent state as a serial schedule
(no anomalies).

 For example,
1 2 3 1 2 4 3 4

produces the same result as


1 2 3 4 1 2 3 4

 The DBMS can freely interleave the transactions in this way.


28
SERIALIZABLE Example
 Sometimes transactions are NOT serializable
 The values written by TA have an affect on a the value read by TB
 READs or WRITEs from TA cannot be exchanged with WRITES of the same item from TB.
 If there is a cycle of data dependencies (RW, WW, WR), the schedule is not serializable.

1 2 1 3 4 2 3 4 Not Serializable
qty
R 2 R W 4 2 W 4 TA TB
qty
29
Isolation Levels
 Serializability provides a conservative definition of correctness
 For a particular application there might be many
acceptable non-serializable schedules
 Requiring serializability might degrade performance

 DBMSs offer a variety of isolation levels:


 SERIALIZABLE is the most stringent
 Lower levels of isolation give better performance
 Be careful:

Lower levels might allow incorrect schedules

However lower levels might be adequate for some applications
30
Concurrency Problems
 Databases do not normally run in ’SERIALIZABLE’ mode.
 SERIALIZABLE is good for consistency, bad for performance.
 Large organisations use DBMSs that are optimised for performance
(Oracle, DB2, MS SQLServer...)
 They do not use SERIALIZABLE as default.
 This means the db programmer has to be aware of possible problems.
 The most severe of the possible concurrency problems
(or ’anomalies’) is the Lost Update.
31
Concurrency Control
 Concurrency Control is the component of the DBMS that is
responsible for maintaining transaction isolation.

 Database operations arrive at Concurrency Control


 the order of operations is generally not serializable.

 Concurrency control preserves the order of database operations


 within transactions
 but not between transactions.

 Ideally, Concurrency Control should allow only correct schedules.


 A correct schedule is one that is serializable and strict.
32
Concurrency Control
 Concurrency Control attempts to reorder the arriving interleaved
schedule into a serializable schedule by:
 Delaying servicing a request - causes a transaction to wait.
 Refuses to service a request - causes transaction to abort.

 Actions taken by Concurrency Control have performance costs.


 Delaying increases response time.
 Aborting reduces throughput.
33
Concurrency Control
Arriving schedule Altered schedule
(from transactions) Concurrency Control
(to processing engine)

 Concurrency control cannot see entire schedule:


 It sees one request at a time and must decide whether to allow it to be
serviced.

 Strategy: Do not service a request if:


 It violates strictness or serializability
34
Pessimistic Concurrency Control
 Pessimistic Concurrency Control
 Assumes conflicts are likely.
Detects conflicts before they happen.
 Policy
For each read/write operation, a transaction requests permission
Concurrency control will either:
Allow the operation (submit it for execution)
Delay the operation until
Another tarnsaction(s) is committed or rolledback
Abort the current transaction
 Technology employed:
Locking
 Decisions are made pessimistically
Therefore a commit request is always allowed (all required db objects have

already been locked)


35
Pessimistic Concurrency Controls
 Pessimistic concurrency control
 Most useful when
 there are many updates
 High chance of transactions updating same data at the same time
 Small tables (few rows) that are frequently updated

E.g. Four concerts. Each transaction updates TicketsAvailable value in
one of 4 rows.
 Conflicts are probable
 Optimistic control (discussed next) would waste time and effort in rolling
back conflicting transactions
 Requires overhead for every operation
 Each time that a row is accessed, the system must check if the requested
row(s) is already locked by other transactions

Regardless of whether two or more transactions are actually trying to
access the same row.

The overhead is small but adds up over many operations
36
Optimistic Concurrency Controls
 Optimistic concurrency control
 Assumes that conflicts between two transactions not likely.
Detects conflicts after they happen.
 Policy

Request for database operations (read/write) are always


allowed
 Technology employed
Timestamps

 A request to commit might be denied


Transaction is aborted if it performed a non-serializable
operation
37
Pessimistic Concurrency Controls
 Optimistic concurrency control
 Most useful when
 Possibility of conflict between two transactions is very low

Large tables. Many rows. Each transaction updates a very small
percentage of the rows (perhaps 1 or 2 rows)

Or very few updates occur and mostly read-type operations.

Consider Customer Bank Account deposit or withdrawal
 How many concurrent transactions will attempt to update
your bank account balance at the same time?
 Conflict is very unlikely
38
Pessimistic Concurrency Controls
 A DBMS may offer:
 Pessimistic concurrency control
 Optimistic concurrency control
 A combination of both
 Use which ever is best suited to the requirement
39
Locks in Oracle
 Explicit Locking
 Possible on 'schema objects', i.e. tables, views, indexes
 Lock modes
 Exclusive: no one can access the object
 Shared: others can still read the object

 Locks are released at the end of the transaction


(COMMIT, ROLLBACK)
40
Locking for Transaction Isolation

 Most databases use a combination of shared and exclusive


(read/write) locks to isolate transactions from each other.
 The programmer does not have to ’set’ the locks explicitly.
 The programmer sets the ’Isolation Level’ (discussed later)
and the DBMS will get the appropriate locks.
 Most DBMSs allow explicit locking.
 But there is usually (not always) is a better way of doing it.
41
Locks in Oracle
 AVOID Explicit Locking of schema objects
LOCK TABLE PART IN SHARE MODE
Not Recommended.

 Novices do this because they have little knowledge of locking,


 So they Google 'Lock' or look up 'Lock' in the index of a text book

 In this subject we attempt to show better approaches


to currency control

NOTE: INF20010. Do not lock tables. Probable fail!


42
Locks in Oracle
 Automatic (implicit) locking
 No shared locks are used

 Oracle does exclusive row-level locking automatically when


executing DML: INSERT, UPDATE, DELETE.

 Other transactions cannot read exclusively locked rows

 Locked rows won't be released until the tranasction


 Is either commited or rolledback
43
Select for Update
 Avoiding LOST UPDATE in Oracle

 Use a SELECT statement that includes


Recommended method
the keywords FOR UPDATE.

 This 'tells' Oracle that the Selected row(s) are likely


to be updated.
 Data rows that have been selected have shared locks
 No other transaction can write to that row

 Locks are released at the end of the transaction.

Note: You are not obligated to update the locked row.


When the transaction is finished. Locks are released.
44
Lost Update problem
 Consider this code in Transaction A.
Create Procedure Upd(pamt number) As
vBalance NUMBER;
vNewBalance NUMBER;
BEGIN
SELECT Balance INTO vBalance
FROM bankcust WHERE custid = 1;
vNewBalance = vBalance + pamt;
UPDATE bankcust
SET Balance = vNewBalance WHERE
custid = 1;
End;
45
Lost Update problem
 Transaction A.
1 Create Procedure Upd(pamt number) As
2 vBalance NUMBER;
3 vNewBalance NUMBER; Question
BEGIN At the time line 8 is
4 executed, is the value
SELECT Balance INTO vBalance of vBalance the
5 FROM bankcust WHERE custidcurrent
= 1; balance
6 of cust 1?

7 vNewBalance = vBalance + pamt;


8
UPDATE bankcust
9 SET Balance = vNewBalance WHERE custid
10 = 1;
11 End;
12
46
Lost Update problem
 Transaction A
1 Create Procedure Upd(pamt number) As
vBalance NUMBER; Imagine this takes
2 place while
3 vNewBalance NUMBER; Transaction A is
4 BEGIN being executed.

5
SELECT Balance INTO vBalance
Transaction B:
FROM bankcust WHERE custid = 1; bankcust
Update
6
Set Balance = 0
7 Where custid = 1;
vNewBalance = vBalance +
Trans B is executed BEFORE line 8 is executed
pamt;
8
9 UPDATE bankcust
10 SET Balance = vNewBalance WHERE
vbalance custid
is wrong!
11 = 1; newBalance is wrong!
12 End;
47
Lost Update problem
 Transaction A
Transaction
Create Procedure Upd(pamt number) AsB set
1 the balance to 0.
2 vBalance NUMBER;
3
vNewBalance NUMBER; Yet Transaction A
BEGIN will overwrite that
4 value.
SELECT Balance INTO vBalance
5
FROM bankcust WHERE custid =A 1;Lost Update
6 will occur
7 vNewBalance = vBalance + pamt;
8
9 UPDATE bankcust
10 SET Balance = vNewBalance WHERE custid
11 = 1;
12 End;
48
SELECT... FOR UPDATE solution
 Transaction A
In this better
1 Create Procedure Upd(pamt number) As
alternative,
vBalance NUMBER; Transaction A now
2
vNewBalance NUMBER; has a FOR UPDATE
3 BEGIN clause in the
4 Select statement
SELECT Balance INTO vBalance
5 FROM bankcust WHERE custid = 1 FOR
6 UPDATE;
7
8 vNewBalance = vBalance + pamt;
9
UPDATE bankcust
10
SET Balance = vNewBalance WHERE custid =
11 1;
12 End;
49
SELECT... FOR UPDATE solution
 Transaction A
1 Create Procedure Upd(pamt number) As
vBalance NUMBER;
2
vNewBalance NUMBER;
3 BEGIN
4 SELECT Balance INTO vBalance
5 FROM bankcust WHERE custid = 1 FOR
6 UPDATE;
7
The row of+
vNewBalance = vBalance cust 1 is locked
pamt;
8
9
UPDATE bankcust
10
SET Balance = vNewBalance WHERE custid =
11 1;
12 End;
50
Lost Update problem
 Transaction B Transaction B
1 Create Procedure Upd(pamt number)
attemptsAsto execute
vBalance NUMBER; line 6
2
vNewBalance NUMBER;
3 This is impossible.
BEGIN Cust 1 has been
4 SELECT Balance INTO vBalance locked.
5 FROM bankcust WHERE custid = 1 FOR
6 UPDATE;
7
8 vNewBalance = vBalance + pamt; Transaction B
must wait...
9
UPDATE bankcust
10 Until Transaction A
SET Balance = vNewBalance WHERE custid =
releases the lock
11 1; (i.e. commit or rollback)
12 End;
51
Oracle Select ... For Update
Transaction C Transaction D
... ...
vqty PRODUCT.qty%TYPE; vqty PRODUCT.qty%TYPE;
BEGIN BEGIN
INSERT INTO SALES ...; INSERT INTO SALES ...;
SELECT QTY INTO vqty FROM PRODUCT
WHERE PRODID = '1' FOR UPDATE;

Time
Row is locked Transaction D is paused.
vqty := vqty – pPurchaesQty; It must wait for locks from
Transaction 1 to be released
UPDATE PRODUCT
SET QTY = vqty
WHERE PRODID = ’1’ ;
COMMIT; Row locks released
SELECT QTY INTO vqty FROM PRODUCT
WHERE PRODID = '1' FOR UPDATE;
END;
vqty := vqty – pPurchaesQty;
UPDATE PRODUCT
SET QTY = vqty
WHERE PRODID = ’1’ ;
COMMIT;
END;
52
Consider this procedure...
We want to transfer money from one customer to
another
1
Create Procedure TRANSFER_CASH (pCust1
2 NUMBER,
3 pCust2 NUMBER,
4 pAmt NUMBER) AS
5 vBal1 ACCOUNT.balance%TYPE;
6 vBal2 ACCOUNT.balance%TYPE;
BEGIN
7 SELECT balance INTO vBal1 FROM ACCOUNT
8 WHERE custid = pCust1;
SELECT balance INTO vBal2 FROM ACCOUNT
WHERE
What can we custid = the
assume about pCust2;
values held in vBal1 and vBal2 at this point in time
... especially in a multi-user environment?
ALWAYS assume that the values in vBal1 and vBal2 are out of date.
Solution: Use Select For Update.
53
Consider this procedure...
We want to transfer money from one
customer to another
9
10 vBal1 = vBal1 – 20;
11 vBal2 = vBal2 + 20;
12 UPDATE ACCOUNT
13 SET balance = vBal1 WHERE custid =
14 pCust1;
15 UPDATE ACCOUNT
SET balance = vBal2 WHERE custid =
pCust2;
What can we assume about the values held in vBal1 and vBal2 at this point in time
especially in a multi-user environment?
END;
ALWAYS assume that the values in vBal1 and vBal2 are out of date.
Solution: Use Select For Update.
55
Improved code with Select... For Update
vBal1 ACCOUNT.balance%TYPE;
vBal2 ACCOUNT.balance%TYPE;
BEGIN
SELECT balance INTO vBal1 FROM ACCOUNT
WHERE custid = pCust1 FOR UPDATE;
SELECT balance INTO vBal2 FROM ACCOUNT
WHERE custid = pCust2 FOR UPDATE;
-- At this point, no other transaction can update
these customer balances
vBal1 = vBal1 – 20;
vBal2 = vBal2 + 20;
UPDATE ACCOUNT
SET balance = vBal1 WHERE custid =
pCust1;
UPDATE ACCOUNT
SET balance = vBal2 WHERE custid =
pCust2 ;
COMMIT; -- Releases locks
END;
56
VB GUI
 This is the GUI for the Demo application
57
Reset Table - Transaction Code
 This code shows the Reset Table Transaction in the Demo application
58
Part 1…Create a Transaction Object
Create & Open a Connection

Create a Transaction Object

Pass the Connection and Transaction to a sub procedure


59
Catch an exception calls a Rollback

If the procedure is successful, then commit

If the procedure is failed, then execute rollback in Catch segment


60
Reset Procedure example code
Code for the Reset Procedure

The command must know which transaction it belongs to

 IfOracle Stored procedure fails it returns an


exception.
 Allow the exception to be thrown back to the
calling procedure
61
Throwing exceptions
A transaction may have many steps.
 One Insert in Table A
 One Update of Table B
 One Update of Table C

 Any
Error messages raised by one part of the transaction must be
handled by the code which begins and ends the transaction

 Any part of the transaction must THROW any exception back to


the higher level
62
A transaction with multiple parts
A transaction may have many steps.
 Commit and Rollback only happen at the highest level
 Individual steps must not Commit or Rollback
 Exceptions are thrown back to the top level
63
References
 Connolly T, Begg C, Database Systems, Fourth Ed, Addison/Wesley 2008
 Chapter 20
 Connolly T, Begg C, Holowczak R, Business Database Systems. Pearson/Addison-
Wesley, 2008.
 Chapter 14
 Rob P, Coronel C, Database Systems: Design, Implementation and Management,
Eighth Ed., Thomson 2008,
 Chapter 10
 Mannino, M., Database Application Development and Design, McGraw-Hill, 2004
 13.1,2

You might also like