transaction management chapter 9(2)

Upload: taraka-rama-rao

Post on 10-Apr-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/8/2019 Transaction Management Chapter 9(2)

    1/31

  • 8/8/2019 Transaction Management Chapter 9(2)

    2/31

  • 8/8/2019 Transaction Management Chapter 9(2)

    3/31

  • 8/8/2019 Transaction Management Chapter 9(2)

    4/31

  • 8/8/2019 Transaction Management Chapter 9(2)

    5/31

    4 Properties of a Transaction4 Properties of a Transaction

    IsolationIsolation The final effects of multiple simultaneous The final effects of multiple simultaneoustransactions must be the same as if they weretransactions must be the same as if they wereexecuted one right after the otherexecuted one right after the otherDurability Durability If a transaction has been committed, the DBMSIf a transaction has been committed, the DBMSmust ensure that its effects are permanently must ensure that its effects are permanently recorded in the database (even if the systemrecorded in the database (even if the systemcrashes)crashes)

  • 8/8/2019 Transaction Management Chapter 9(2)

    6/31

    Transaction Management wit h SQL Transaction Management wit h SQL

    SQL StatementsSQL Statements Commit / Rollback Commit / Rollback When a transaction sequence is initiated it must When a transaction sequence is initiated it must

    continue through all succeeding SQL statementscontinue through all succeeding SQL statementsuntil:until:1.1. A Commit Statement is Reached A Commit Statement is Reached2.2. A Rollback Statement is Reached A Rollback Statement is Reached3.3. The End of the Program is Reached (Commit) The End of the Program is Reached (Commit)4.4. The Program is A bnormally Terminated (Rollback) The Program is A bnormally Terminated (Rollback)

  • 8/8/2019 Transaction Management Chapter 9(2)

    7/31

    Ex ampleEx ampleBEGIN TRA NBEGIN TRA N

    DEC LAR E @E rror C ode IN T, @TranSuccessful IN TDEC LAR E @E rror C ode IN T, @TranSuccessful IN TSE T @TranSuccessful = 1SE T @TranSuccessful = 1

    IN SE RT IN TO tbl C atalog ( C atalogYear)IN SE RT IN TO tbl C atalog ( C atalogYear) VALU E S('2002') VALU E S('2002')

    SE T @ E rror C ode = @@ E RROR; IF (@ E rror C ode 0) S E T @TranSuccessful = 0SE T @ E rror C ode = @@ E RROR; IF (@ E rror C ode 0) S E T @TranSuccessful = 0 F alseF alse

    IN SE RT IN TO tbl C atalog ( C atalogYear)IN SE RT IN TO tbl C atalog ( C atalogYear) VALU E S('2003') VALU E S('2003')

    SE T @ E rror C ode = @@ E RROR; IF (@ E rror C ode 0) S E T @TranSuccessful = 0SE T @ E rror C ode = @@ E RROR; IF (@ E rror C ode 0) S E T @TranSuccessful = 0 F alseF alse

    IF @TranSuccessful = 0IF @TranSuccessful = 0BEGINBEGIN

    ROLLBA CK TRA NROLLBA CK TRA NRA I SE RROR ('Rolledback transaction: I nsert C atalog Year.', 16,1)RA I SE RROR ('Rolledback transaction: I nsert C atalog Year.', 16,1)

    ENDEND

    E LSEE LSEBEGINBEGIN

    C OMM I T TRA NC OMM I T TRA NPR IN T 'Successfully inserted catalog years...'PR IN T 'Successfully inserted catalog years...'

    ENDENDG OG O

  • 8/8/2019 Transaction Management Chapter 9(2)

    8/31

    Transaction Log Transaction Log

    K eeps track of all transactions that update the databaseK eeps track of all transactions that update the databaseRecord for the beginning of the transactionRecord for the beginning of the transaction

    Type of operation (insert / update / delete) Type of operation (insert / update / delete)Names of objects/tables affected by the transactionNames of objects/tables affected by the transactionBefore and A fter Values for U pdated FieldsBefore and A fter Values for U pdated FieldsPointers to Previous and Next Transaction Log Entries forPointers to Previous and Next Transaction Log Entries forthe same transactionthe same transaction

    The Ending of the Transaction (Commit) The Ending of the Transaction (Commit)U sed for recovery in case of a Rollback U sed for recovery in case of a Rollback

  • 8/8/2019 Transaction Management Chapter 9(2)

    9/31

    C oncurrency C ontrolC oncurrency C ontrol

    Coordination of simultaneous transactionCoordination of simultaneous transactionexecution in a multiprocessing database systemexecution in a multiprocessing database systemEnsure transaction serializability in a multiEnsure transaction serializability in a multi--useruserdatabasedatabaseLack of Concurrency Control can create dataLack of Concurrency Control can create dataintegrity and consistency problems:integrity and consistency problems:

    Lost U pdatesLost U pdatesU ncommitted DataU ncommitted DataInconsistent RetrievalsInconsistent Retrievals

  • 8/8/2019 Transaction Management Chapter 9(2)

    10/31

    Lost UpdatesLost Updates Time Time Jacks Trans Jacks Trans Jills Trans Jills Trans BalanceBalance T1 T1 BeginBegin T2 T2 Read BalanceRead Balance BeginBegin 10001000

    T3 T3 Read BalanceRead Balance 10001000 T4 T4 Bal = BalBal = Bal 50 (950)50 (950) 10001000 T5 T5 Write Bal (950) Write Bal (950) Bal = Bal + 100Bal = Bal + 100

    (1100)(1100)

    950950

    T6 T6 CommitCommit 950950 T7 T7 Write Bal (1100) Write Bal (1100) 11001100 T8 T8 CommitCommit 11001100

  • 8/8/2019 Transaction Management Chapter 9(2)

    11/31

    Uncommitted D ataUncommitted D ata Time Time DepositDeposit InterestInterest BalBal T1 T1 Begin TransactionBegin Transaction 10001000 T2 T2 Read Bal (1000)Read Bal (1000) 10001000

    T3 T3 Bal = Bal + 1000 (2000)Bal = Bal + 1000 (2000) 10001000 T4 T4 Write Bal (2000) Write Bal (2000) Begin TransactionBegin Transaction 20002000 T5 T5 Read Bal (2000)Read Bal (2000) 20002000

    T6 T6 Bal = Bal*1.05 (2100)Bal = Bal*1.05 (2100) 20002000 T7 T7 Rollback Rollback 10001000 T8 T8 Write Bal (2100) Write Bal (2100) 21002100 T9 T9 CommitCommit 21002100

  • 8/8/2019 Transaction Management Chapter 9(2)

    12/31

    I nconsistent RetrievalsI nconsistent Retrievals Time Time SumBalSumBal Transfer Transfer Bal ABal A Bal BBal B Bal CBal C SumSum

    T1 T1 Begin TransBegin Trans 50005000 50005000 50005000

    T2 T2 Sum = 0Sum = 0 Begin TransBegin Trans 50005000 50005000 50005000

    T3 T3 Read Bal A (5000)Read Bal A (5000) 50005000 50005000 50005000

    T4 T4 Sum = Sum +Sum = Sum +Bal A (5000)Bal A (5000)

    Read Bal A (5000)Read Bal A (5000) 50005000 50005000 50005000

    T5 T5 Read BalB (5000)Read BalB (5000) Bal A = Bal A Bal A = Bal A --1000 (4000)1000 (4000) 50005000 50005000 50005000

    T6 T6 Sum = Sum+BalBSum = Sum+BalB(10000)(10000)

    Write Bal A (4000) Write Bal A (4000) 40004000 50005000 50005000

    T7 T7 Read BalCRead BalC 40004000 50005000 50005000

    T8 T8 BalC =BalC + 1000 (6000)BalC =BalC + 1000 (6000) 40004000 50005000 50005000

    T9 T9 Write BalC (6000) Write BalC (6000) 40004000 50005000 60006000 T10 T10 Read BalCRead BalC CommitCommit 40004000 50005000 60006000

    T11 T11 Sum=Sum + BalCSum=Sum + BalC(16000)(16000)

    40004000 50005000 60006000

    T12 T12 Write Sum (16000) Write Sum (16000) 40004000 50005000 60006000 1600016000

    T13 T13 CommitCommit 40004000 50005000 60006000 1600016000

  • 8/8/2019 Transaction Management Chapter 9(2)

    13/31

    Serial Ex ecution of TransactionsSerial Ex ecution of Transactions

    Serial Execution of transaction means that theSerial Execution of transaction means that thetransactions are performed one after another.transactions are performed one after another.

    No interaction between transactionsNo interaction between transactions -- NoNoConcurrency Control ProblemsConcurrency Control ProblemsSerial Execution will never leave the database inSerial Execution will never leave the database inan inconsistent statean inconsistent state Every Serial Execution isEvery Serial Execution isconsidered correct (Even if a different orderconsidered correct (Even if a different order

    would cause different results) would cause different results)

  • 8/8/2019 Transaction Management Chapter 9(2)

    14/31

    SerializabilitySerializability

    If 2 Transactions are only reading data itemsIf 2 Transactions are only reading data items They do not conflict They do not conflict Order is unimportantOrder is unimportant

    If 2 Transactions operate (Read/Write) onIf 2 Transactions operate (Read/Write) onSeparate Data ItemsSeparate Data Items They do not conflict They do not conflict Order is unimportantOrder is unimportant

    If 1 Transaction Writes to a Data Item andIf 1 Transaction Writes to a Data Item and A nother Reads or Writes to the Same Data Item A nother Reads or Writes to the Same Data Item The Order of Execution IS Important The Order of Execution IS Important

  • 8/8/2019 Transaction Management Chapter 9(2)

    15/31

    T h e Sch eduler T h e Sch eduler

    Special DBMS Program to establish the order of Special DBMS Program to establish the order of operations in which concurrent transactions areoperations in which concurrent transactions areexecutesexecutesInterleaves the execution of database operationsInterleaves the execution of database operationsto ensure:to ensure:

    Serializability Serializability Isolation of TransactionsIsolation of Transactions

  • 8/8/2019 Transaction Management Chapter 9(2)

    16/31

    T h e Sch eduler T h e Sch eduler

    Bases its actions on Concurrency ControlBases its actions on Concurrency Control A lgorithms (Locking / Time Stamping) A lgorithms (Locking / Time Stamping)

    Ensures the CPU

    is used efficiently (Scheduling Ensures the CPU

    is used efficiently (Scheduling Methods)Methods)Facilitates Data IsolationFacilitates Data Isolation Ensure that 2Ensure that 2transactions do not update the same data at thetransactions do not update the same data at thesame timesame time

  • 8/8/2019 Transaction Management Chapter 9(2)

    17/31

    C oncurrency C ontrol Algorit h msC oncurrency C ontrol Algorit h ms

    Locking Locking A Transaction locks a database object to prevent A Transaction locks a database object to prevent

    another object from modifying the objectanother object from modifying the object

    Time Time--Stamping Stamping A ssign a global unique time stamp to each A ssign a global unique time stamp to eachtransactiontransaction

    OptimisticOptimistic A ssumption that most database operations do A ssumption that most database operations donot conflictnot conflict

  • 8/8/2019 Transaction Management Chapter 9(2)

    18/31

    LockingLocking

    Lock guarantees exclusive use of data item toLock guarantees exclusive use of data item tocurrent transactioncurrent transaction

    Prevents reading Inconsistent DataPrevents reading Inconsistent DataLock Manager is responsible for assigning andLock Manager is responsible for assigning andpolicing the locks used by the transactionpolicing the locks used by the transaction

  • 8/8/2019 Transaction Management Chapter 9(2)

    19/31

    Locking G ranularityLocking G ranularity

    Indicates the level of lock useIndicates the level of lock useDatabase LevelDatabase Level Entire Database is LockedEntire Database is Locked

    Table Level Table Level Entire Table is LockedEntire Table is LockedPage LevelPage Level Locks an Entire DiskpageLocks an Entire Diskpage(Most Frequently U sed)(Most Frequently U sed)Row LevelRow Level Locks Single Row of TableLocks Single Row of TableField LevelField Level Locks a Single A ttribute of aLocks a Single A ttribute of aSingle Row (Rarely Done)Single Row (Rarely Done)

  • 8/8/2019 Transaction Management Chapter 9(2)

    20/31

    Types of Locks: Types of Locks:BinaryBinary

    Binary LocksBinary Locks Lock with 2 StatesLock with 2 StatesLockedLocked No other transaction can use that objectNo other transaction can use that objectU nlockedU nlocked A ny transaction can lock and use object A ny transaction can lock and use object

    A ll Transactions require a Lock and U nlock Operation for Each A ll Transactions require a Lock and U nlock Operation for EachObject A ccessed (Handled by DBMS)Object A ccessed (Handled by DBMS)

    Eliminates Lost U pdatesEliminates Lost U pdates Too Restrictive to Yield Optimal Concurrency Conditions Too Restrictive to Yield Optimal Concurrency Conditions

  • 8/8/2019 Transaction Management Chapter 9(2)

    21/31

    Types of Locks: Types of Locks:Sh ared / Ex clusive LocksSh ared / Ex clusive Locks

    Indicates the Nature of the Lock Indicates the Nature of the Lock Shared Lock Shared Lock Concurrent Transactions are granted RE A DConcurrent Transactions are granted RE A Daccess on the basis of a common lock access on the basis of a common lock Exclusive Lock Exclusive Lock A ccess is reserved for the transaction that A ccess is reserved for the transaction thatlocked the objectlocked the object3 States: U nlocked, Shared (Read), Exclusive (Write)3 States: U nlocked, Shared (Read), Exclusive (Write)More Efficient Data A ccess SolutionMore Efficient Data A ccess SolutionMore Overhead for Lock ManagerMore Overhead for Lock Manager

    Type of lock needed must be known Type of lock needed must be known3 Operations:3 Operations:

    Read_Lock Read_Lock Check to see the type of lock Check to see the type of lock Write_Lock Write_Lock Issue a Lock Issue a Lock U nlock U nlock Release a Lock Release a Lock

    A llow U pgrading / Downgrading of Locks A llow U pgrading / Downgrading of Locks

  • 8/8/2019 Transaction Management Chapter 9(2)

    22/31

    Problems wit h LockingProblems wit h Locking

    Transaction Schedule May Not be Serializable Transaction Schedule May Not be SerializableCan be solved with 2Can be solved with 2--Phase Locking Phase Locking

    May Cause DeadlocksMay Cause Deadlocks A deadlock is caused when 2 transactions wait for A deadlock is caused when 2 transactions wait foreach other to unlock dataeach other to unlock data

  • 8/8/2019 Transaction Management Chapter 9(2)

    23/31

    Two P h ase Locking Two P h ase Locking

    Defines how transactions A cquire and RelinquishDefines how transactions A cquire and RelinquishLocksLocks

    1.1. Growing PhaseGrowing Phase The transaction acquires all locks The transaction acquires all locks(doesnt unlock any data)(doesnt unlock any data)

    2.2. Shrinking PhaseShrinking Phase The transaction releases locks The transaction releases locks(doesnt lock any additional data)(doesnt lock any additional data)

    Transactions acquire all locks it needs until it reaches Transactions acquire all locks it needs until it reacheslocked pointlocked point When locked, data is modified and locks are released When locked, data is modified and locks are released

  • 8/8/2019 Transaction Management Chapter 9(2)

    24/31

    D eadlocksD eadlocks

    Occur when 2 transactions exist in the following mode:Occur when 2 transactions exist in the following mode: T1 = access data item X and Y T1 = access data item X and Y T2 = A ccess data items Y and X T2 = A ccess data items Y and X

    If T1 does not unlock Y, T2 cannot beginIf T1 does not unlock Y, T2 cannot beginIf T2 does not unlock X, T1 cannot continueIf T2 does not unlock X, T1 cannot continue

    T1 & T2 wait indefinitely for each other to unlock data T1 & T2 wait indefinitely for each other to unlock dataDeadlocks are only possible if a transactions wants anDeadlocks are only possible if a transactions wants anExclusive Lock (No Deadlocks on Shared Locks)Exclusive Lock (No Deadlocks on Shared Locks)

  • 8/8/2019 Transaction Management Chapter 9(2)

    25/31

    C ontrolling D eadlocksC ontrolling D eadlocks

    PreventionPrevention A transaction requesting a new lock is A transaction requesting a new lock isaborted if there is the possibility of a deadlock aborted if there is the possibility of a deadlock

    Transaction is rolled back, Locks are released, Transaction is rolled back, Locks are released,

    Transaction is rescheduled Transaction is rescheduledDetectionDetection Periodically test the database for deadlocks.Periodically test the database for deadlocks.If a deadlock is found, abort / rollback one of theIf a deadlock is found, abort / rollback one of thetransactionstransactionsA voidance

    A voidance Requires a transaction to obtain all locksRequires a transaction to obtain all locksneeded before it can executeneeded before it can execute requires locks to berequires locks to be

    obtained in successionobtained in succession

  • 8/8/2019 Transaction Management Chapter 9(2)

    26/31

    Time Stamping Time StampingCreates a specific order in which the transactions areCreates a specific order in which the transactions areprocessed by the DBMSprocessed by the DBMS2 Main Properties2 Main Properties

    1.1. U niquenessU niqueness A ssumes that no equal time stamp value can exist A ssumes that no equal time stamp value can exist(ensures serializability of the transactions)(ensures serializability of the transactions)

    2.2. Monotonicity Monotonicity Ensures that time stamp values always increasesEnsures that time stamp values always increasesA ll operations within the same transaction have the same time A ll operations within the same transaction have the same timestampstampIf Transactions conflict, one is rolled back and rescheduledIf Transactions conflict, one is rolled back and rescheduledEach value in Database requires 2 A dditional Fields: LastEach value in Database requires 2 A dditional Fields: Last

    Time Read / Last Time U pdated Time Read / Last Time U pdatedIncreases Memory Need and Processing OverheadIncreases Memory Need and Processing Overhead

  • 8/8/2019 Transaction Management Chapter 9(2)

    27/31

    Time Stamping Sc h emes Time Stamping Sc h emes

    Wait / Die Scheme Wait / Die Scheme The older transaction will wait The older transaction will wait The younger transaction will be rolled back The younger transaction will be rolled back

    Wound / Wait Scheme Wound / Wait Scheme The older transaction will preempt (wound) The older transaction will preempt (wound)

    the younger transaction and roll it back the younger transaction and roll it back The younger transaction waits for the older The younger transaction waits for the older

    transaction to release the lockstransaction to release the locks Without time Without time--out values, Deadlocks may be createdout values, Deadlocks may be created

  • 8/8/2019 Transaction Management Chapter 9(2)

    28/31

    Optimistic Met h odOptimistic Met h od

    Most database operations do not conflictMost database operations do not conflictNo locking or time stamping No locking or time stamping

    Transactions execute until commit Transactions execute until commitRead PhaseRead Phase Read database, execute computations, makeRead database, execute computations, makelocal updates (temporary update file)local updates (temporary update file)

    Validate Phase Validate Phase Transaction is validated to ensure changes Transaction is validated to ensure changes will not effect integrity of database will not effect integrity of database

    If ValidatedIf Validated Go to Write PhaseGo to Write PhaseIf Not ValidatedIf Not Validated Restart Transaction and discard initial changesRestart Transaction and discard initial changes

    Write Phase Write Phase Commit Changes to databaseCommit Changes to databaseGood for Read / Query Databases (Few U pdates)Good for Read / Query Databases (Few U pdates)

  • 8/8/2019 Transaction Management Chapter 9(2)

    29/31

    D atabase RecoveryD atabase RecoveryRestore a database from a given state to a previous consistentRestore a database from a given state to a previous consistentstatestateA tomic Transaction Property ( A ll or None) A tomic Transaction Property ( A ll or None)Backup Levels:Backup Levels:

    Full BackupFull BackupDifferential BackupDifferential Backup

    Transaction Log Backup Transaction Log BackupDatabase / System Failures:Database / System Failures:

    Software (O.S., DBMS, A pplication Programs, Viruses)Software (O.S., DBMS, A pplication Programs, Viruses)

    Hardware (Memory Chips, Disk Crashes, Bad Sectors)Hardware (Memory Chips, Disk Crashes, Bad Sectors)Programming Exemption ( A pplication Program rollbacks)Programming Exemption ( A pplication Program rollbacks) Transaction ( A borting transactions due to deadlock detection) Transaction ( A borting transactions due to deadlock detection)External (Fire, Flood, etc)External (Fire, Flood, etc)

  • 8/8/2019 Transaction Management Chapter 9(2)

    30/31

    Transaction Recovery Transaction RecoveryRecover Database by using data in the Transaction Log Recover Database by using data in the Transaction Log

    Write Write-- A head A head--Log Log Transaction logs need to be written before Transaction logs need to be written beforeany database data is updatedany database data is updatedRedundant Transaction LogsRedundant Transaction Logs Several copies of log on differentSeveral copies of log on differentdevicesdevicesDatabase BuffersDatabase Buffers Buffers are used to increase processing timeBuffers are used to increase processing timeon updates instead of accessing data on disk on updates instead of accessing data on disk Database CheckpointsDatabase Checkpoints Process of writing all updated buffers toProcess of writing all updated buffers to

    disk disk While this is taking place, all other requests are not While this is taking place, all other requests are notexecutesexecutesScheduled several times per hourScheduled several times per hourCheckpoints are registered in the transaction log Checkpoints are registered in the transaction log

  • 8/8/2019 Transaction Management Chapter 9(2)

    31/31