Transaction management

47
Transaction Transaction Management Management Chapter 3 Chapter 3

description

 

Transcript of Transaction management

Page 1: Transaction management

Transaction Transaction ManagementManagement

Chapter 3Chapter 3

Page 2: Transaction management

What is a Transaction?What is a Transaction?

A logical unit of work on a databaseA logical unit of work on a database An entire programAn entire program A portion of a programA portion of a program A single commandA single command

The entire series of steps necessary to The entire series of steps necessary to accomplish a logical unit of workaccomplish a logical unit of work

Successful transactions change the database Successful transactions change the database from one CONSISTENT STATE to another from one CONSISTENT STATE to another

(One where all data integrity constraints are (One where all data integrity constraints are satisfied)satisfied)

Page 3: Transaction management

Example of a TransactionExample of a Transaction

Updating a RecordUpdating a Record Locate the Record on DiskLocate the Record on Disk Bring record into BufferBring record into Buffer Update Data in the BufferUpdate Data in the Buffer Writing Data Back to DiskWriting Data Back to Disk

Page 4: Transaction management

4 Properties of a 4 Properties of a TransactionTransaction

Atomic – All or NothingAtomic – All or Nothing

All parts of the transaction must be All parts of the transaction must be completed and committed or it must completed and committed or it must be aborted and rolled backbe aborted and rolled back

Consistent Consistent

Each user is responsible to ensure Each user is responsible to ensure that their transaction (if executed by that their transaction (if executed by itself) would leave the database in a itself) would leave the database in a consistent stateconsistent state

Page 5: Transaction management

4 Properties of a 4 Properties of a TransactionTransaction

IsolationIsolationIt indicates that action performed by a It indicates that action performed by a transaction will be hidden from outside the transaction will be hidden from outside the transaction until the transaction transaction until the transaction terminates.terminates.

DurabilityDurabilityIf a transaction has been committed, the If a transaction has been committed, the DBMS must ensure that its effects are DBMS must ensure that its effects are permanently recorded in the database permanently recorded in the database (even if the system crashes) (even if the system crashes)

(ACID properties of transaction)(ACID properties of transaction)

Page 6: Transaction management

Transaction Management Transaction Management with SQLwith SQL

SQL Statements SQL Statements Commit / Rollback Commit / Rollback When a transaction sequence is initiated When a transaction sequence is initiated

it must continue through all succeeding it must continue through all succeeding SQL statements until:SQL statements until:

1.1. A Commit Statement is ReachedA Commit Statement is Reached

2.2. A Rollback Statement is ReachedA Rollback Statement is Reached

3.3. The End of the Program is Reached The End of the Program is Reached (Commit)(Commit)

4.4. The Program is Abnormally Terminated The Program is Abnormally Terminated (Rollback)(Rollback)

Page 7: Transaction management

ExampleExampleBEGIN TRANBEGIN TRAN DECLARE @ErrorCode INT, @TranSuccessful INTDECLARE @ErrorCode INT, @TranSuccessful INT SET @TranSuccessful = 1SET @TranSuccessful = 1

INSERT INTO tblCatalog (CatalogYear) INSERT INTO tblCatalog (CatalogYear) VALUES('2002')VALUES('2002') SET @ErrorCode = @@ERROR; IF (@ErrorCode <> 0) SET @TranSuccessful = 0 –FalseSET @ErrorCode = @@ERROR; IF (@ErrorCode <> 0) SET @TranSuccessful = 0 –False

INSERT INTO tblCatalog (CatalogYear) INSERT INTO tblCatalog (CatalogYear) VALUES('2003')VALUES('2003')

SET @ErrorCode = @@ERROR; IF (@ErrorCode <> 0) SET @TranSuccessful = 0 –FalseSET @ErrorCode = @@ERROR; IF (@ErrorCode <> 0) SET @TranSuccessful = 0 –False

IF @TranSuccessful = 0IF @TranSuccessful = 0 BEGINBEGIN

ROLLBACK TRANROLLBACK TRAN RAISERROR ('Rolledback transaction: Insert Catalog Year.', 16,1)RAISERROR ('Rolledback transaction: Insert Catalog Year.', 16,1)

ENDEND ELSEELSE BEGINBEGIN COMMIT TRANCOMMIT TRAN PRINT 'Successfully inserted catalog years...'PRINT 'Successfully inserted catalog years...' ENDENDGOGO

Page 8: Transaction management

Transaction LogTransaction Log

Keeps track of all transactions that update Keeps track of all transactions that update the databasethe database Record 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 Names of objects/tables affected by the

transactiontransaction Before and After Values for Updated FieldsBefore and After Values for Updated Fields Pointers to Previous and Next Transaction Log Pointers to Previous and Next Transaction Log

Entries for the same transactionEntries for the same transaction The Ending of the Transaction (Commit)The Ending of the Transaction (Commit)

Used for recovery in case of a RollbackUsed for recovery in case of a Rollback

Page 9: Transaction management

Transaction StatesTransaction States

Because failures occurs, transaction are Because failures occurs, transaction are broken up into states to handle various broken up into states to handle various situation. situation.

1.1. Active : The initial state; the transaction stays Active : The initial state; the transaction stays in this state until while it is still executing.in this state until while it is still executing.

2.2. Partially Committed : After the final Partially Committed : After the final statement has been executedstatement has been executed

3.3. Failed : after the discovery that normal Failed : after the discovery that normal execution can no longer proceedexecution can no longer proceed

4.4. Committed : after successful completion.Committed : after successful completion.

Page 10: Transaction management

5. Aborted : after the transaction has 5. Aborted : after the transaction has been rolled back the the database been rolled back the the database has been restored to its state prior has been restored to its state prior to the start of the transaction.to the start of the transaction.

Page 11: Transaction management

State diagram of a transactionState diagram of a transaction

Page 12: Transaction management

SchedulesSchedules

SchedulesSchedules – sequences that indicate the chronological order in which – sequences that indicate the chronological order in which instructions of concurrent transactions are executedinstructions of concurrent transactions are executed a schedule for a set of transactions must consist of all instructions of a schedule for a set of transactions must consist of all instructions of

those transactionsthose transactions must preserve the order in which the instructions appear in each must preserve the order in which the instructions appear in each

individual transaction.individual transaction.

Page 13: Transaction management

Example SchedulesExample Schedules

Let Let TT11 transfer $50 from transfer $50 from A A to to BB, and , and TT22 transfer 10% of the balance from transfer 10% of the balance from A A

to to B.B. The following is a serial schedule (Schedule 1 in the text), in which The following is a serial schedule (Schedule 1 in the text), in which TT11 is followed by is followed by TT22..

Page 14: Transaction management

Cont.Cont.

Let Let TT11 and and TT22 be the transactions defined previously be the transactions defined previously.. The following The following

schedule is not a serial schedule, but it is schedule is not a serial schedule, but it is equivalentequivalent to Schedule 1. to Schedule 1.

Page 15: Transaction management

Cont.Cont.

The following concurrent schedule does not preserve the value of the the The following concurrent schedule does not preserve the value of the the sum sum A A + + BB..

Page 16: Transaction management

SerializabilitySerializability

Basic Assumption – Each transaction preserves database Basic Assumption – Each transaction preserves database consistency.consistency.

Thus serial execution of a set of transactions preserves Thus serial execution of a set of transactions preserves database consistency.database consistency.

A (possibly concurrent) schedule is serializable if it is A (possibly concurrent) schedule is serializable if it is equivalent to a serial schedule. Different forms of schedule equivalent to a serial schedule. Different forms of schedule equivalence give rise to the notions of:equivalence give rise to the notions of:

1.1. conflict serializabilityconflict serializability

2.2. view serializabilityview serializability

Page 17: Transaction management

Conflict SerializabilityConflict Serializability

Instructions Instructions llii and and lljj of transactions of transactions TTii and and TTjj respectively, respectively,

conflictconflict if and only if there exists some item if and only if there exists some item QQ accessed by accessed by both both llii and and lljj, and at least one of these instructions wrote , and at least one of these instructions wrote Q.Q.

1. 1. llii = = readread((Q), lQ), ljj = = readread((QQ). ). llii and and lljj don’t conflict.don’t conflict.

2. 2. llii = = readread((Q), lQ), ljj = = writewrite((QQ). They conflict.). They conflict.

3. 3. llii = = writewrite((Q), lQ), ljj = = readread((QQ). They conflict). They conflict

4. 4. llii = = writewrite((Q), lQ), ljj = = writewrite((QQ). They conflict). They conflict

Page 18: Transaction management

Conflict Serializability (Cont.)Conflict Serializability (Cont.)

If a schedule If a schedule SS can be transformed into a schedule can be transformed into a schedule S´ S´ by a series of swaps by a series of swaps of non-conflicting instructions, we say that of non-conflicting instructions, we say that SS and and S´ S´ are are conflict conflict equivalentequivalent..

We say that a schedule We say that a schedule SS is is conflict serializableconflict serializable if it is conflict equivalent if it is conflict equivalent to a serial scheduleto a serial schedule

Example of a schedule that is not conflict serializable:Example of a schedule that is not conflict serializable:

TT33 TT44

readread((QQ))writewrite((QQ))

writewrite((QQ))

We are unable to swap instructions in the above schedule to obtain either We are unable to swap instructions in the above schedule to obtain either the serial schedule < the serial schedule < TT33, , TT44 >, or the serial schedule < >, or the serial schedule < TT44, , TT33 >. >.

Page 19: Transaction management

Conflict Serializability (Cont.)Conflict Serializability (Cont.)

Schedule 3 below can be transformed into Schedule 1, a serial schedule Schedule 3 below can be transformed into Schedule 1, a serial schedule where where TT22 follows follows TT11, by series of swaps of non-conflicting instructions. , by series of swaps of non-conflicting instructions.

Therefore Schedule 3 is conflict serializable.Therefore Schedule 3 is conflict serializable.

Page 20: Transaction management

View SerializabilityView Serializability

Let Let SS and and S´S´ be two schedules with the same set of transactions. be two schedules with the same set of transactions. SS and and S´S´ are are view equivalentview equivalent if the following three conditions are met:if the following three conditions are met:

1.1. For each data item For each data item Q,Q, if transaction if transaction TTii reads the initial value of reads the initial value of QQ in in schedule schedule S,S, then transaction then transaction TTii must, in schedule must, in schedule S´S´, also read the , also read the initial value of initial value of Q.Q.

2.2. For each data item For each data item QQ if transaction if transaction TTii executes executes readread((Q) Q) in schedule in schedule SS, , and that value was produced by transaction and that value was produced by transaction TTjj (if any), then transaction (if any), then transaction TTii must in schedule must in schedule S´S´ also read the value of also read the value of QQ that was produced by that was produced by transaction transaction TTjj . .

3.3. For each data item For each data item QQ, the transaction (if any) that performs the final , the transaction (if any) that performs the final writewrite((QQ) operation in schedule ) operation in schedule S S must perform the finalmust perform the final writewrite((QQ) ) operation in schedule operation in schedule S´S´..

As can be seen, view equivalence is also based purely on As can be seen, view equivalence is also based purely on readsreadsand and writeswrites alone. alone.

Page 21: Transaction management

View Serializability (Cont.)View Serializability (Cont.)

A schedule A schedule SS is is view serializableview serializable it is view equivalent to a serial schedule. it is view equivalent to a serial schedule. Every conflict serializable schedule is also view serializable.Every conflict serializable schedule is also view serializable. Schedule 9 (from text) — a schedule which is view-serializable but Schedule 9 (from text) — a schedule which is view-serializable but not not

conflict serializable.conflict serializable.Every view serializable schedule that is not conflictEvery view serializable schedule that is not conflict serializable has serializable has blind writes.blind writes.

Page 22: Transaction management

Recoverable SchedulesRecoverable Schedules

Need to address the effect of transaction failures on concurrently Need to address the effect of transaction failures on concurrently running transactions.running transactions.

RecoverableRecoverable scheduleschedule — if a transaction — if a transaction TTjj reads a data items previously reads a data items previously

written by a transaction written by a transaction TTi i , the commit operation of , the commit operation of TTii appears before the appears before the

commit operation of commit operation of TTjj..

The following schedule is not recoverable if The following schedule is not recoverable if TT99 commits immediately after commits immediately after

the read.the read. If If TT88 should abort, should abort, TT99 would have read (and possibly shown to the user) an would have read (and possibly shown to the user) an

inconsistent database state. Hence database must ensure that schedules are inconsistent database state. Hence database must ensure that schedules are recoverablerecoverable

Page 23: Transaction management

Cascading ScheduleCascading Schedule

Every cascadeless schedule is also recoverableEvery cascadeless schedule is also recoverable It is desirable to restrict the schedules to those that are It is desirable to restrict the schedules to those that are

cascadelesscascadeless CascadelessCascadeless schedulesschedules — cascading rollbacks cannot occur; — cascading rollbacks cannot occur;

for each pair of transactions for each pair of transactions TTii and and TTjj such that such that TTjj reads a data reads a data

item previously written by item previously written by TTii, the commit operation of , the commit operation of TTii

appears before the read operation of appears before the read operation of TTjj..

Page 24: Transaction management

Cascadeless Schedules (Cont.)Cascadeless Schedules (Cont.)

Cascading rollbackCascading rollback – a single transaction failure leads to a series of – a single transaction failure leads to a series of transaction rollbacks. Consider the following schedule where none of the transaction rollbacks. Consider the following schedule where none of the transactions has yet committed (so the schedule is recoverable)transactions has yet committed (so the schedule is recoverable)

If If TT1010 fails, fails, TT1111 and and TT1212 must also be rolled back. must also be rolled back. Can lead to the undoing of a significant amount of workCan lead to the undoing of a significant amount of work

Page 25: Transaction management

Concurrency ControlConcurrency Control Coordination of simultaneous transaction Coordination of simultaneous transaction

execution in a multiprocessing database execution in a multiprocessing database systemsystem

Ensure transaction serializability in a Ensure transaction serializability in a multi-user databasemulti-user database

Lack of Concurrency Control can create Lack of Concurrency Control can create data integrity and consistency problems:data integrity and consistency problems: Lost UpdatesLost Updates Uncommitted DataUncommitted Data Inconsistent RetrievalsInconsistent Retrievals

Page 26: Transaction management

Lost UpdatesLost UpdatesTimTim

eeJack’s TransJack’s Trans Jill’s TransJill’s Trans BalanBalan

cece

T1T1 BeginBegin

T2T2 Read BalanceRead Balance BeginBegin 10001000

T3T3 Read BalanceRead Balance 10001000

T4T4 Bal = Bal – 50 Bal = Bal – 50 (950)(950)

10001000

T5T5 Write Bal (950)Write Bal (950) Bal = Bal + Bal = Bal + 100 (1100)100 (1100)

950950

T6T6 CommitCommit 950950

T7T7 Write Bal Write Bal (1100)(1100)

11001100

T8T8 CommitCommit 11001100

Page 27: Transaction management

Uncommitted DataUncommitted DataTimTimee

DepositDeposit InterestInterest BalBal

T1T1 Begin TransactionBegin Transaction 10010000

T2T2 Read Bal (1000)Read Bal (1000) 10010000

T3T3 Bal = Bal + 1000 Bal = Bal + 1000 (2000)(2000)

10010000

T4T4 Write Bal (2000)Write Bal (2000) Begin Begin TransactionTransaction

20020000

T5T5 Read Bal (2000)Read Bal (2000) 20020000

T6T6 Bal = Bal*1.05 Bal = Bal*1.05 (2100)(2100)

20020000

T7T7 RollbackRollback 10010000

T8T8 Write Bal (2100)Write Bal (2100) 21021000

T9T9 CommitCommit 21021000

Page 28: Transaction management

Inconsistent RetrievalsInconsistent RetrievalsTimeTime SumBalSumBal TransferTransfer Bal Bal

AABal Bal BB

Bal Bal CC

SumSum

T1T1 Begin TransBegin Trans 50050000

50050000

50050000

T2T2 Sum = 0Sum = 0 Begin TransBegin Trans 50050000

50050000

50050000

T3T3 Read BalA (5000)Read BalA (5000) 50050000

50050000

50050000

T4T4 Sum = Sum + Sum = Sum + BalA (5000)BalA (5000)

Read BalA (5000)Read BalA (5000) 50050000

50050000

50050000

T5T5 Read BalB (5000)Read BalB (5000) BalA = BalA -1000 BalA = BalA -1000 (4000)(4000)

50050000

50050000

50050000

T6T6 Sum = Sum+BalB Sum = Sum+BalB (10000)(10000)

Write BalA (4000)Write BalA (4000) 40040000

50050000

50050000

T7T7 Read BalCRead BalC 40040000

50050000

50050000

T8T8 BalC =BalC + 1000 BalC =BalC + 1000 (6000)(6000)

40040000

50050000

50050000

T9T9 Write BalC (6000)Write BalC (6000) 40040000

50050000

60060000

T10T10 Read BalCRead BalC CommitCommit 40040000

50050000

60060000

T11T11 Sum=Sum + Sum=Sum + BalC (16000)BalC (16000)

40040000

50050000

60060000

T12T12 Write Sum Write Sum (16000)(16000)

40040000

50050000

60060000

1600160000

T13T13 CommitCommit 40040000

50050000

60060000

1600160000

Page 29: Transaction management

Serial Execution of Serial Execution of TransactionsTransactions

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

No interaction between transactions - No interaction between transactions - No Concurrency Control ProblemsNo Concurrency Control Problems

Serial Execution will never leave the Serial Execution will never leave the database in an inconsistent state database in an inconsistent state Every Serial Execution is considered Every Serial Execution is considered correct (Even if a different order would correct (Even if a different order would cause different results)cause different results)

Page 30: Transaction management

SerializabilitySerializability

If 2 Transactions are only reading data items If 2 Transactions are only reading data items – They do not conflict – They do not conflict Order is Order is unimportantunimportant

If 2 Transactions operate (Read/Write) on If 2 Transactions operate (Read/Write) on Separate Data Items Separate Data Items

– – They do not conflict They do not conflict Order is Order is unimportantunimportant

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

Page 31: Transaction management

The SchedulerThe Scheduler

Special DBMS Program to establish Special DBMS Program to establish the order of operations in which the order of operations in which concurrent transactions are concurrent transactions are executesexecutes

Interleaves the execution of Interleaves the execution of database operations to ensure:database operations to ensure:

SerializabilitySerializability

Isolation of TransactionsIsolation of Transactions

Page 32: Transaction management

The SchedulerThe Scheduler

Bases its actions on Concurrency Bases its actions on Concurrency Control Algorithms (Locking / Time Control Algorithms (Locking / Time Stamping)Stamping)

Ensures the CPU is used efficiently Ensures the CPU is used efficiently (Scheduling Methods)(Scheduling Methods)

Facilitates Data Isolation Facilitates Data Isolation Ensure Ensure that 2 transactions do not update the that 2 transactions do not update the same data at the same timesame data at the same time

Page 33: Transaction management

Concurrency Control Concurrency Control AlgorithmsAlgorithms

LockingLockingA Transaction “locks” a database object to A Transaction “locks” a database object to

prevent another object from modifying prevent another object from modifying the objectthe object

Time-StampingTime-StampingAssign a global unique time stamp to Assign a global unique time stamp to each transactioneach transaction

OptimisticOptimisticAssumption that most database Assumption that most database operations do not conflictoperations do not conflict

Page 34: Transaction management

LockingLocking

Lock guarantees exclusive use of Lock guarantees exclusive use of data item to current transactiondata item to current transaction

Prevents reading Inconsistent DataPrevents reading Inconsistent Data Lock Manager is responsible for Lock Manager is responsible for

assigning and policing the locks assigning and policing the locks used by the transactionused by the transaction

Page 35: Transaction management

Locking GranularityLocking Granularity

Indicates the level of lock useIndicates the level of lock use Database Level – Entire Database is Database Level – Entire Database is

LockedLocked Table Level – Entire Table is LockedTable Level – Entire Table is Locked Page Level – Locks an Entire Diskpage Page Level – Locks an Entire Diskpage

(Most Frequently Used)(Most Frequently Used) Row Level – Locks Single Row of TableRow Level – Locks Single Row of Table Field Level – Locks a Single Attribute Field Level – Locks a Single Attribute

of a Single Row (Rarely Done)of a Single Row (Rarely Done)

Page 36: Transaction management

Types of Locks: Types of Locks: BinaryBinary

Binary Locks – Lock with 2 StatesBinary Locks – Lock with 2 States Locked – No other transaction can use that objectLocked – No other transaction can use that object Unlocked – Any transaction can lock and use objectUnlocked – Any transaction can lock and use object

All Transactions require a Lock and Unlock All Transactions require a Lock and Unlock Operation for Each Operation for Each

Object Accessed (Handled by DBMS)Object Accessed (Handled by DBMS)

Eliminates Lost UpdatesEliminates Lost Updates Too Restrictive to Yield Optimal Concurrency Too Restrictive to Yield Optimal Concurrency

ConditionsConditions

Page 37: Transaction management

Types of Locks:Types of Locks:Shared / Exclusive LocksShared / Exclusive Locks

Indicates the Nature of the LockIndicates the Nature of the Lock Shared Lock – Concurrent Transactions are granted Shared Lock – Concurrent Transactions are granted

READ access on the basis of a common lockREAD access on the basis of a common lock Exclusive Lock – Access is reserved for the Exclusive Lock – Access is reserved for the

transaction that locked the objecttransaction that locked the object 3 States: Unlocked, Shared (Read), Exclusive 3 States: Unlocked, Shared (Read), Exclusive

(Write)(Write) More Efficient Data Access SolutionMore Efficient Data Access Solution More Overhead for Lock ManagerMore Overhead for Lock Manager

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

Read_Lock – Check to see the type of lockRead_Lock – Check to see the type of lock Write_Lock – Issue a LockWrite_Lock – Issue a Lock Unlock – Release a LockUnlock – Release a Lock

Allow Upgrading / Downgrading of LocksAllow Upgrading / Downgrading of Locks

Page 38: Transaction management

Problems with LockingProblems with Locking

Transaction Schedule May Not be Transaction Schedule May Not be SerializableSerializable Can be solved with 2-Phase LockingCan be solved with 2-Phase Locking

May Cause DeadlocksMay Cause Deadlocks A deadlock is caused when 2 A deadlock is caused when 2

transactions wait for each other to transactions wait for each other to unlock dataunlock data

Page 39: Transaction management

Two Phase LockingTwo Phase Locking

Defines how transactions Acquire and Defines how transactions Acquire and Relinquish LocksRelinquish Locks

1.1. Growing Phase – The transaction acquires Growing Phase – The transaction acquires all locks (doesn’t unlock any data)all locks (doesn’t unlock any data)

2.2. Shrinking Phase – The transaction releases Shrinking Phase – The transaction releases locks (doesn’t lock any additional data)locks (doesn’t lock any additional data)

Transactions acquire all locks it needs Transactions acquire all locks it needs until it reaches locked pointuntil it reaches locked point

When locked, data is modified and locks When locked, data is modified and locks are releasedare released

Page 40: Transaction management

DeadlocksDeadlocks Occur when 2 transactions exist in the Occur when 2 transactions exist in the

following mode:following mode:T1 = access data item X and YT1 = access data item X and YT2 = Access data items Y and XT2 = Access 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 T1 & T2 wait indefinitely for each other to unlock datadata

Deadlocks are only possible if a transactions Deadlocks are only possible if a transactions wants an Exclusive Lock (No Deadlocks on wants an Exclusive Lock (No Deadlocks on Shared Locks)Shared Locks)

Page 41: Transaction management

Controlling DeadlocksControlling Deadlocks Prevention – A transaction requesting a new Prevention – A transaction requesting a new

lock is aborted if there is the possibility of a lock is aborted if there is the possibility of a deadlock – Transaction is rolled back, Locks deadlock – Transaction is rolled back, Locks are released, Transaction is rescheduledare released, Transaction is rescheduled

Detection – Periodically test the database Detection – Periodically test the database for deadlocks. If a deadlock is found, for deadlocks. If a deadlock is found, abort / rollback one of the transactionsabort / rollback one of the transactions

Avoidance – Requires a transaction to Avoidance – Requires a transaction to obtain all locks needed before it can obtain all locks needed before it can execute – requires locks to be obtained in execute – requires locks to be obtained in successionsuccession

Page 42: Transaction management

Time StampingTime Stamping Creates a specific order in which the transactions Creates a specific order in which the transactions

are processed by the DBMSare processed by the DBMS 2 Main Properties2 Main Properties

1.1. Uniqueness – Assumes that no equal time stamp value can Uniqueness – Assumes that no equal time stamp value can exist (ensures serializability of the transactions)exist (ensures serializability of the transactions)

2.2. Monotonicity – Ensures that time stamp values always Monotonicity – Ensures that time stamp values always increasesincreases

All operations within the same transaction have the All operations within the same transaction have the same time stampsame time stamp

If Transactions conflict, one is rolled back and If Transactions conflict, one is rolled back and rescheduledrescheduled

Each value in Database requires 2 Additional Each value in Database requires 2 Additional Fields: Last Time Read / Last Time UpdatedFields: Last Time Read / Last Time Updated

Increases Memory Need and Processing OverheadIncreases Memory Need and Processing Overhead

Page 43: Transaction management

Time Stamping SchemesTime Stamping Schemes Wait / Die SchemeWait / Die Scheme

The older transaction will waitThe older transaction will waitThe younger transaction will be rolled backThe younger transaction will be rolled back

Wound / Wait SchemeWound / Wait SchemeThe older transaction will preempt (wound) The older transaction will preempt (wound)

the younger transaction and roll it the younger transaction and roll it backback

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-out values, Deadlocks may be Without time-out values, Deadlocks may be createdcreated

Page 44: Transaction management

Optimistic MethodOptimistic Method Most database operations do not conflictMost database operations do not conflict No locking or time stampingNo locking or time stamping Transactions execute until commitTransactions execute until commit

Read Phase – Read database, execute computations, Read Phase – Read database, execute computations, make local updates (temporary update file)make local updates (temporary update file)

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

If Validated If Validated Go to Write Phase Go to Write Phase If Not Validated If Not Validated Restart Transaction and discard initial Restart Transaction and discard initial

changeschanges Write Phase – Commit Changes to databaseWrite Phase – Commit Changes to database

Good for Read / Query Databases (Few Good for Read / Query Databases (Few Updates)Updates)

Page 45: Transaction management

Database RecoveryDatabase Recovery Restore a database from a given state to a Restore a database from a given state to a

previous consistent stateprevious consistent state Atomic Transaction Property (All or None)Atomic Transaction Property (All or None) Backup Levels:Backup Levels:

Full BackupFull Backup Differential BackupDifferential Backup Transaction Log BackupTransaction Log Backup

Database / System Failures:Database / System Failures: Software (O.S., DBMS, Application Programs, Viruses)Software (O.S., DBMS, Application Programs, Viruses) Hardware (Memory Chips, Disk Crashes, Bad Sectors)Hardware (Memory Chips, Disk Crashes, Bad Sectors) Programming Exemption (Application Program Programming Exemption (Application Program

rollbacks)rollbacks) Transaction (Aborting transactions due to deadlock Transaction (Aborting transactions due to deadlock

detection)detection) External (Fire, Flood, etc)External (Fire, Flood, etc)

Page 46: Transaction management

Transaction RecoveryTransaction Recovery Recover Database by using data in the Transaction Recover Database by using data in the Transaction

LogLog Write-Ahead-Log – Transaction logs need to be Write-Ahead-Log – Transaction logs need to be

written before any database data is updatedwritten before any database data is updated Redundant Transaction Logs – Several copies of log Redundant Transaction Logs – Several copies of log

on different deviceson different devices Database Buffers – Buffers are used to increase Database Buffers – Buffers are used to increase

processing time on updates instead of accessing data processing time on updates instead of accessing data on diskon disk

Database Checkpoints – Process of writing all Database Checkpoints – Process of writing all updated buffers to disk updated buffers to disk While this is taking place, While this is taking place, all other requests are not executesall other requests are not executes Scheduled several times per hourScheduled several times per hour Checkpoints are registered in the transaction logCheckpoints are registered in the transaction log

Page 47: Transaction management