Transaction Management and Concurrency Control
Database Transactions and the Consistent State
Definition of a Transaction:
A transaction is a logical unit of work that must be either entirely completed or aborted.
No intermediate or partial transaction state can exist on permanent storage; either all operations succeed, or the entire transaction fails.
Database State Transitions:
A successful transaction transitions a database from one consistent state to another consistent state.
A consistent database state is defined as one in which all data integrity constraints, relational rules, and business logic are fully satisfied.
Most real-world database transactions are composed of two or more distinct database requests, where a database request is the direct equivalent of a single SQL statement in an application program or interactive transaction.
Transaction Evaluation and Access:
Not all transactions modify or update the database; a transaction can consist solely of read operations (such as a
SELECTquery) because the database was accessed.Improperly formed or incomplete transactions can compromise database integrity catastrophically.
Integrity preservation relies on two mechanisms: user-defined enforceable constraints (provided by specific DBMS tools) and automatic integrity rules enforced by the DBMS engine.
Relational Schema of the Transaction Example (
Ch10_SaleCo):The transaction model operates on the
Ch10_SaleCodatabase structure, consisting of six relational tables with the following attributes and relationships:CUSTOMER: ContainsCUST_NUMBER(primary key),CUST_LNAME,CUST_FNAME,CUST_INITIAL,CUST_AREACODE,CUST_PHONE, andCUST_BALANCE.INVOICE: ContainsINV_NUMBER(primary key),CUST_NUMBER(foreign key referencingCUSTOMER),INV_DATE,INV_SUBTOTAL,INV_TAX,INV_TOTAL,INV_PAY_TYPE,INV_PAY_AMOUNT, andINV_BALANCE. Represents a 1:M relationship fromCUSTOMERtoINVOICE.LINE: ContainsINV_NUMBERandLINE_NUMBER(composite primary key),PROD_CODE(foreign key referencingPRODUCT),LINE_UNITS,LINE_PRICE, andLINE_AMOUNT. Represents a 1:M relationship fromINVOICEtoLINE.PRODUCT: ContainsPROD_CODE(primary key),PROD_DESCRIPT,PROD_INDATE,PROD_QOH,PROD_MIN,PROD_PRICE,PROD_DISCOUNT, andVEND_NUMBER(foreign key referencingVENDOR). Represents a 1:M relationship fromPRODUCTtoLINE.VENDOR: ContainsVEND_NUMBER(primary key),VEND_NAME,VEND_CONTACT,VEND_AREACODE,VEND_PHONE,VEND_STATE, andVEND_ORDER. Represents a 1:M relationship fromVENDORtoPRODUCT.ACCT_TRANSACTION: ContainsACCT_TRANS_NUM(primary key),ACCT_TRANS_DATE,CUST_NUMBER(foreign key referencingCUSTOMER),ACCT_TRANS_TYPE, andACCT_TRANS_AMOUNT. Represents a 1:M relationship fromCUSTOMERtoACCT_TRANSACTION.

Tracing a Complex Transaction in
Ch10_SaleCo:When customer
10016(James G. Brown) purchases a product on credit on18-Jan-12:INVOICE: Record1009is created withINV_SUBTOTAL= ,INV_TAX= ,INV_TOTAL= ,INV_PAY_TYPE=cred,INV_PAY_AMOUNT= , andINV_BALANCE= .LINE: Line1009,1is written forPROD_CODE89-WRE-Q(Hicut chain saw, 16 in.), withLINE_UNITS= ,LINE_PRICE= , andLINE_AMOUNT= .PRODUCT: Quantity on hand (PROD_QOH) for item89-WRE-Qis decremented from to .CUSTOMER: Account balance (CUST_BALANCE) for customer10016increases from to .ACCT_TRANSACTION: Transaction record10007is added on18-Jan-12forCUST_NUMBER10016withACCT_TRANS_TYPE=chargeandACCT_TRANS_AMOUNT= .If any single operation of this sequence fails, all corresponding updates across all tables must be undone to prevent data corruption.

Transaction Properties (ACID and Serializability)
Atomicity:
Requires that all operations of a transaction must be completed to completion.
If any single operation within the logical unit of work cannot be completed, the entire transaction is aborted and rolled back.
Consistency:
Represents the permanence of a database's consistent state.
A transaction transforms the database from one valid state to another without violating any established integrity constraints.
Isolation:
Dictates that data used during the execution of one transaction cannot be accessed or used by a second transaction until the first transaction is completed.
Prevents concurrent transactions from seeing intermediate, uncommitted states.
Durability:
Ensures that once transaction changes are committed, they cannot be undone or lost, even in the event of a subsequent system or physical hardware failure.
Serializability:
Ensures that the concurrent execution of several transactions yields the exact same state and results as if the transactions were executed sequentially (serially) one after another.
Essential in multiuser environments where concurrent transactions overlap in time.
Transaction Management with SQL and the Transaction Log
ANSI Standards and Transaction Boundaries:
SQL transaction management is governed by ANSI standards.
Transaction support relies on two core SQL statements:
COMMIT: Saves all database alterations permanently to storage.ROLLBACK: Aborts the transaction and restores the database to its previous consistent state.A transaction sequence continues executing until one of four terminal conditions is met:
A
COMMITstatement is reached.A
ROLLBACKstatement is reached.The normal end of program execution is reached (which triggers an automatic commit in many environments).
The program terminates abnormally (which triggers an automatic rollback).
The Transaction Log Structure and Role:
The transaction log records all database modifications to support transaction recovery and concurrency control.
The log stores:
A record for the beginning of the transaction (
START).For each transaction operation component:
The type of operation performed (
INSERT,UPDATE,DELETE).The names of the tables and objects affected.
The specific row identifier (
ROW ID).The attribute modified.
The "Before Value" (state prior to update, used for undo/rollback).
The "After Value" (state following the update, used for redo).
Pointers to the previous log entry (
PREV PTR) and next log entry (NEXT PTR) belonging to that exact transaction number.
A record for the ending of the transaction (
COMMIT).A transaction number (
TRX_NUM) automatically assigned by the DBMS.
Detailed Transaction Log Walkthrough:
A transaction (
TRX_NUM= ) updating inventory and balance is logged through sequential transaction log records (TRL_ID):Record :
TRX_NUM= ,PREV PTR=Null,NEXT PTR= ,OPERATION=START,TABLE=****Start Transaction.Record :
TRX_NUM= ,PREV PTR= ,NEXT PTR= ,OPERATION=UPDATE,TABLE=PRODUCT,ROW ID=1558-QW1,ATTRIBUTE=PROD_QOH,BEFORE VALUE= ,AFTER VALUE= .Record :
TRX_NUM= ,PREV PTR= ,NEXT PTR= ,OPERATION=UPDATE,TABLE=CUSTOMER,ROW ID=10011,ATTRIBUTE=CUST_BALANCE,BEFORE VALUE= ,AFTER VALUE= .Record :
TRX_NUM= ,PREV PTR= ,NEXT PTR=Null,OPERATION=COMMIT,TABLE=**** End of Transaction.
Concurrency Control Anomalies and the Scheduler
Core Purpose of Concurrency Control:
Concurrency control coordinates the simultaneous execution of transactions in a multiprocessing, multiuser database.
The objective is to enforce serializability, preventing data corruption across concurrent access pathways.
The Scheduler:
A specialized DBMS program that establishes the exact ordering in which operations of concurrent transactions are executed.
Interleaves operations to achieve high performance while strictly preserving isolation and serializability.
Yields a serializable schedule, which is an interleaved execution sequence whose final database state matches that of a strict serial execution.
Anomalies from Uncontrolled Concurrent Execution:
Lost Updates:
Occurs when two concurrent transactions update the same data element simultaneously, causing one update to overwrite and destroy the other.
Consider initial inventory :
Transaction : Purchase 100 units ().
Transaction : Sell 30 units ().
In correct serial execution, reads , updates to , and writes . Then reads , updates to , and writes . Stored value is correctly .
In an interleaved lost update schedule:
Time 1: reads
PROD_QOH().Time 2: reads
PROD_QOH().Time 3: computes .
Time 4: computes .
Time 5: writes
PROD_QOH().Time 6: writes
PROD_QOH().Result: 's update of adding 100 units is lost, leaving the stored value at .
Uncommitted Data (Dirty Reads):
Occurs when two transactions execute concurrently, and the second transaction accesses uncommitted data updated by the first transaction, which subsequently rolls back.
Example: updates
PROD_QOHby adding 100 units. reads the uncommitted value and deducts 30 units. If rolls back its operation, the database contains values derived from an update that technically never occurred.Inconsistent Retrievals:
Occurs when a transaction calculates summary aggregates while concurrent transactions are actively updating the target data elements.
A reading transaction accesses some data rows before they are updated and other rows after they are updated, producing inconsistent and erroneous summary computations.
Detailed Case Study:
Total initial inventory across six products is units.
calculates:
SELECT SUM(PROD_QOH) FROM PRODUCT.corrects a data entry mistake by moving 10 units: updates product
1546-QQ2() and updates1558-QW1(), followed byCOMMIT.Interleaved sequence yielding an inconsistent retrieval:
Time 1: reads
11QER/31(), running total = .Time 2: reads
13-Q2/P2(), running total = .Time 3: reads
1546-QQ2().Time 4: computes .
Time 5: writes
1546-QQ2().Time 6: reads
1546-QQ2(), running total = .Time 7: reads
1558-QW1(), running total = .Time 8: reads
1558-QW1().Time 9: computes .
Time 10: writes
1558-QW1().Time 11: commits.
Time 12: reads
2232-QTY(), running total = .Time 13: reads
2232-QWE(), final total = .Result: records an erroneous sum of instead of the actual invariant total of , because it captured
1546-QQ2after its update and1558-QW1before its update.
Concurrency Control with Locking Methods
Locking Concepts:
A lock guarantees exclusive use of a data item to a transaction, preventing other transactions from accessing inconsistent intermediate states.
Pessimistic Locking: An operational philosophy based on the assumption that conflicts between concurrent transactions are highly probable, requiring proactive locks.
Lock Manager: The internal DBMS module responsible for assigning, maintaining, and releasing locks requested by transactions.
Lock Granularity Levels:
Lock granularity indicates the level of data isolation applied by the DBMS lock mechanism:
Database-Level Lock:
Locks the entire database, preventing any concurrent access by other transactions.
Prevents concurrent execution even if transactions access completely different tables (e.g., updating Table A locks out updating Table B until finishes).

Table-Level Lock:
Locks an entire table, preventing concurrent transactions from updating rows in the locked table, while allowing access to other tables.
If updates row 5 of Table A and requests row 30 of Table A, is forced to wait until unlocks Table A.

Page-Level Lock:
Locks an entire physical diskpage (a storage allocation unit containing multiple rows across one or more tables).
If updates row 1 on Page 1, and updates row 5 on Page 2 and row 2 on Page 1, obtains access to Page 2 but must wait to access Page 1 until completes.

Row-Level Lock:
Locks only individual rows within a table.
Concurrent transactions can simultaneously access different rows of the same table even if they reside on the same diskpage (e.g., locks row 1 and locks row 2 concurrently).
Provides high concurrency but incurs significant system lock management overhead.

* **Field-Level Lock:**
* Locks specific attributes (columns) within a single row.
* Allows concurrent transactions to update the same row at the same time, provided they alter different fields within that row.
* Yields maximal concurrency with maximal DBMS overhead.
Lock Types:
Binary Lock:
Has two states: locked () or unlocked ().
When an object is locked by a transaction, no other transaction can read or write to it.
Example execution: locks
PRODUCT, readsPROD_QOH(), computes , writes , and unlocksPRODUCT. Then locksPRODUCT, readsPROD_QOH(), computes , writes , and unlocksPRODUCT.Exclusive Lock:
Access is reserved exclusively for the transaction holding the lock.
Must be issued whenever a transaction intends to perform a write or update operation; no other transaction can read or write the locked object.
Shared Lock:
Granted to concurrent transactions that require read-only access to a data item.
Multiple transactions can hold shared locks on the same object simultaneously; no updates are permitted until all shared locks are released.
Two-Phase Locking (2PL) Protocol
Definition and Guarantee:
Two-phase locking defines explicit rules governing how transactions acquire and relinquish locks.
Guarantees serializability of concurrent schedules.
Does not prevent deadlocks from occurring.
The Two Distinct Phases:
Growing Phase:
The transaction acquires all required locks sequentially without releasing any locks on any data item.
Locked Point:
The specific instant at which the transaction has acquired every lock necessary to complete its operations.
Shrinking Phase:
The transaction releases all acquired locks sequentially.
Once the first lock is released, the transaction cannot request or acquire any new locks.

Governing Rules of 2PL:
Two transactions cannot hold conflicting locks on the same data item.
No unlock operation can precede any lock operation within the same transaction.
No data are affected or updated until all locks are fully obtained.
Deadlocks and Deadlock Handling
Deadlock Mechanics:
A deadlock occurs when two or more transactions wait indefinitely for each other to release locks on required data items.
Deadlocks can occur only if at least one transaction requests an exclusive lock on an item; shared locks alone cannot generate deadlocks.
Sequential creation of deadlock:
Time 0: Data and Data are Unlocked.
Time 1: requests and receives
LOCK(X)( is Locked).Time 2: requests and receives
LOCK(Y)( is Locked).Time 3: requests
LOCK(Y)and is placed inWAITstate.Time 4: requests
LOCK(X)and is placed inWAITstate.Times 5-9+: Both and remain permanently in
WAITstate awaiting lock releases from each other.
Deadlock Control Techniques:
Prevention:
The DBMS evaluates transactions before granting locks and aborts or reschedules any transaction that could induce a deadlock condition.
Recommended when the probability of deadlock is high.
Detection:
The DBMS allows locks freely and periodically scans wait-for dependencies to identify deadlocks.
If a deadlock cycle is detected, one transaction (the victim) is rolled back and rescheduled.
Recommended when the probability of deadlock is low.
Avoidance:
The DBMS dynamically assesses resource allocation states to ensure a circular wait condition cannot materialize.
Concurrency Control via Timestamping and Optimistic Methods
Timestamping Methods:
Assigns a globally unique timestamp to every transaction upon entry into the DBMS.
Produces an explicit serialization order in which transactions are scheduled and executed.
Two essential properties of timestamps:
Uniqueness: Ensures no two transactions receive identical timestamp values.
Monotonicity: Ensures timestamp values strictly increase over time.
Wait/Die and Wound/Wait Schemes:
Consider transaction (timestamp , older) and transaction (timestamp , younger):
Wait/Die Scheme:
If requests a lock owned by : waits until finishes and releases the lock.
If requests a lock owned by : dies (rolls back) and is rescheduled using its original timestamp.
Wound/Wait Scheme:
If requests a lock owned by : preempts (wounds/rolls back) , and is rescheduled using its original timestamp.
If requests a lock owned by : waits until completes and releases the lock.
Optimistic Concurrency Control:
Operates on the premise that the vast majority of database operations do not conflict with one another.
Requires no locking or timestamping overhead during data processing.
Transactions execute completely without restrictions using private local working copies of the data.
Executes through three distinct phases:
Read Phase: The transaction reads data from the database and performs computations inside private local workspace buffers.
Validation Phase: The DBMS verifies whether the transaction's updates conflict with any concurrently committed transactions.
Write Phase: If validation is successful, changes are permanently written to the database; if validation fails, changes are discarded and the transaction is restarted.
Database Recovery Management
Foundations of Recovery:
Database recovery restores a database from a compromised or inconsistent state to a previous consistent state.
Grounded entirely in the atomic transaction property: all parts of a transaction are treated as a single indivisible unit.
If a transaction cannot complete, it is aborted and all changes made to the database are rolled back.
Key Architectural Components and Protocols:
Write-Ahead-Log (WAL) Protocol: Guarantees that transaction log entries are physically written to disk storage before actual database data buffers are updated on disk.
Redundant Transaction Logs: Duplicates log files across physical media to ensure hardware disk failures do not impair recovery capability.
Buffers: Temporary high-speed storage areas located in primary memory (RAM) used to hold database pages.
Checkpoints: Periodic DBMS operations where all updated memory buffers (dirty buffers) and active log records are physically flushed to disk storage.
Transaction Recovery Techniques:
Deferred-Write Technique (Deferred Update):
The physical database on disk is not updated during transaction execution; updates are written solely to the transaction log.
The database is physically updated only after the transaction reaches its commit point.
Recovery rules following system failure:
If transaction committed before the last checkpoint: Do nothing (updates are already safely on disk).
If transaction committed after the last checkpoint: Use the transaction log to redo the transaction.
If transaction was active or had a
ROLLBACKoperation: Do nothing (no physical updates were ever written to the disk database).
Write-Through Technique (Immediate Update):
The physical database on disk is updated immediately during transaction execution before reaching commit.
Recovery rules following system failure:
If transaction committed before the last checkpoint: Do nothing.
If transaction committed after the last checkpoint: Redo the transaction using "after" values from the transaction log.
If transaction had a
ROLLBACKor was active/uncommitted at crash: Roll back and undo the changes using "before" values from the transaction log.
Analysis of Recovery Log Case Example:
A transaction log tracking recovery operations across three transactions (, , ) separated by a checkpoint and crash:
Record :
TRX_NUM= ,OPERATION=START.Record :
TRX_NUM= ,UPDATEPRODUCT54778-2T,PROD_QOHfrom to .Record :
TRX_NUM= ,UPDATECUSTOMER10011,CUST_BALANCEfrom to .Record :
TRX_NUM= ,OPERATION=COMMIT.Record :
TRX_NUM= ,OPERATION=START.Record :
TRX_NUM= ,INSERTINVOICE1009, values1009,10016, ....Record :
TRX_NUM= ,INSERTLINE1009,1, values1009,1, 89-WRE-Q,1, ....Record :
TRX_NUM= ,UPDATEPRODUCT89-WRE-Q,PROD_QOHfrom to .Record :
OPERATION=CHECKPOINT.Record :
TRX_NUM= ,UPDATECUSTOMER10016,CUST_BALANCEfrom to .Record :
TRX_NUM= ,INSERTACCT_TRANSACTION10007, values1007,18-JAN-2012, ....Record :
TRX_NUM= ,OPERATION=COMMIT.Record :
TRX_NUM= ,OPERATION=START.Record :
TRX_NUM= ,UPDATEPRODUCT2232/QWE,PROD_QOHfrom to .Record :
TRX_NUM= ,OPERATION=COMMIT.Following Record , an abrupt system
CRASHoccurs.Recovery actions on system reboot:
Transaction committed prior to the checkpoint at ; no action is required.
Transaction and Transaction committed after checkpoint ; their operations must be redone using log "after" values to guarantee durability.