Database transaction & transaction management

Embed Size (px)

Citation preview

  • 8/7/2019 Database transaction & transaction management

    1/25

  • 8/7/2019 Database transaction & transaction management

    2/25

    TransactionsTransactionsy Transactions are a sequence of actions

    (database operations) which are executed as

    a whole:

    Either all of them execute successfully

    Or none of the them

    y Example:

    A bank transfer from one account into another

    (withdrawal + deposit)

    If either the withdrawal or the deposit fails the

    whole operation is cancelled

  • 8/7/2019 Database transaction & transaction management

    3/25

    Transaction tateTransaction tate

  • 8/7/2019 Database transaction & transaction management

    4/25

    A TransactionA Transaction

    RollbackRollback

    CommitCommit

    ReadRead WriteWrite

    WriteWriteDurableDurablestartingstarting

    statestate

    Durable,Durable,consistent,consistent,

    ending stateending state

    Collection ofCollection ofreads andreads and

    writeswrites

  • 8/7/2019 Database transaction & transaction management

    5/25

    Transactions: ExamplesTransactions: Examplesy Withdraw $100 Transfer $100Transfer $100

    1.1. Read currentRead currentbalancebalance

    2.2. New balance =New balance =currentcurrent -- 100100

    3.3. Write newWrite new

    balancebalance4.4. Dispense cashDispense cash

    1. Read savings

    2. New savings =current - 100

    3. Read checking

    4. New checking =current + 100

    5. Write savings

    6. Write checking

  • 8/7/2019 Database transaction & transaction management

    6/25

    Transactions BehaviorTransactions Behavioryy Transactions guarantee the consistency and theTransactions guarantee the consistency and the

    integrity of the databaseintegrity of the database

    All changes in a transaction are temporaryAll changes in a transaction are temporary

    Changes become final when COMMIT is executedChanges become final when COMMIT is executed

    At any time all changes can be canceled byAt any time all changes can be canceled by

    ROLLBACKROLLBACK

    yy All of the operations are executed as a whole,All of the operations are executed as a whole,

    either all of them or none of themeither all of them or none of them

  • 8/7/2019 Database transaction & transaction management

    7/25

    Transactions PropertiesTransactions Properties

    yy DBMS servers have builtDBMS servers have built--in transaction supportin transaction support

    Contemporary databases implement ACIDContemporary databases implement ACID

    transactionstransactions

    yy ACID means:ACID means:AAtomicitytomicity

    CConsistencyonsistency

    IIsolationsolation

    DDurabilityurability

  • 8/7/2019 Database transaction & transaction management

    8/25

    AtomicityAtomicityy Atomicity means that

    Transactions execute as a wholeTransactions execute as a whole

    DBMS to guarantee that either all of the tasks of aDBMS to guarantee that either all of the tasks of a

    transaction are performed or none of them aretransaction are performed or none of them areyy Atomicity example:Atomicity example:

    Transfer funds between bank accountsTransfer funds between bank accounts

    yy Either withdraw and deposit both execute successfullyEither withdraw and deposit both execute successfully

    or none of themor none of themyy In case of failure DB stays unchangedIn case of failure DB stays unchanged

  • 8/7/2019 Database transaction & transaction management

    9/25

    ConsistencyConsistencyyy ConsistencyConsistency means thatmeans that

    TheThe databasedatabase isis in a legal state when thein a legal state when thetransaction begins and when it endstransaction begins and when it ends

    OOnly valid data will be written to the databasenly valid data will be written to the database

    Transaction cannot break the rules of the database,Transaction cannot break the rules of the database,e.g. integrity constraintse.g. integrity constraints

    yy Primary, foreign, alternate keysPrimary, foreign, alternate keys

    yy Consistency exampleConsistency example

    Transaction cannot end with a duplicate primaryTransaction cannot end with a duplicate primarykey in a tablekey in a table

  • 8/7/2019 Database transaction & transaction management

    10/25

  • 8/7/2019 Database transaction & transaction management

    11/25

    DurabilityDurability

    yy DurabilityDurability means thatmeans that

    If a transaction is confirmed it become persistentIf a transaction is confirmed it become persistent

    Cannot be lost or undoneCannot be lost or undone

    EEnsured through the use of database backups andnsured through the use of database backups and

    transaction logstransaction logsyy Durability example:Durability example:

    After transfer funds and commit the power supplyAfter transfer funds and commit the power supplyis lostis lost

    Transaction stays persistentTransaction stays persistent

  • 8/7/2019 Database transaction & transaction management

    12/25

    Scheduling TransactionsScheduling Transactionsyy Serial scheduleSerial schedule the ideal casethe ideal case

    An ordering of operations of theAn ordering of operations of thetransactions so with no interleavingtransactions so with no interleaving

    Problem: Doesnt allow for as muchProblem: Doesnt allow for as muchconcurrency as wed likeconcurrency as wed like

    yy Conflicting operationsConflicting operations

    Two operations conflict if theyTwo operations conflict if they

    1) are from different transactions1) are from different transactions2) access the same item, and2) access the same item, and

    3) at least one of the transactions does a3) at least one of the transactions does awrite operation to that itemwrite operation to that item

  • 8/7/2019 Database transaction & transaction management

    13/25

    LockingLockingyyTransaction uses locks to deny accessTransaction uses locks to deny access

    to shared data by the other transactionsto shared data by the other transactions

    Most widely used approach to ensureMost widely used approach to ensureserializabilityserializability

    Generally, a transaction must claim aGenerally, a transaction must claim aread (shared) or write (exclusive) lockread (shared) or write (exclusive) lockon a data item before read or writeon a data item before read or write

    Lock prevents another transactionLock prevents another transactionfrom modifying item or even reading it,from modifying item or even reading it,in the case of a write lockin the case of a write lock

    Deadlock is possibleDeadlock is possible

  • 8/7/2019 Database transaction & transaction management

    14/25

    Locking StrategiesLocking StrategiesyyOptimistic lockingOptimistic locking

    Locks are not usedLocks are not used

    Conflicts are possible but are resolvedConflicts are possible but are resolved

    before commitbefore commitHigh concurrencyHigh concurrency scale wellscale well

    yyPessimistic lockingPessimistic locking

    Use exclusive and shared locksUse exclusive and shared locksTransactions wait for each otherTransactions wait for each other

    Low concurrencyLow concurrency does not scaledoes not scale

  • 8/7/2019 Database transaction & transaction management

    15/25

    Optimistic Locking PhasesOptimistic Locking Phasesy Three phasesRead

    yy Transaction reads the DB, doesTransaction reads the DB, doescomputations, then makes updates to acomputations, then makes updates to aprivateprivate copy of the DB (e.g. in the memorycopy of the DB (e.g. in the memory)

    Validationyy Make sure that transaction doesnt causeMake sure that transaction doesnt cause

    any integrity/consistency problemsany integrity/consistency problemsyy If no problems, transaction goes to writeIf no problems, transaction goes to write

    phasephaseyy If problems, changes are discarded andIf problems, changes are discarded and

    transaction is restartedtransaction is restarted

    Writeyy Changes are made persistent to DBChanges are made persistent to DB

  • 8/7/2019 Database transaction & transaction management

    16/25

  • 8/7/2019 Database transaction & transaction management

    17/25

    LockingLocking Basic RulesBasic Rulesyy

    If transaction has read lock on an item, theIf transaction has read lock on an item, theitem can be read but not modifieditem can be read but not modified

    yy If transaction has write lock on an item, theIf transaction has write lock on an item, theitem can be both read and modifieditem can be both read and modified

    yyReads cannot conflict, so multipleReads cannot conflict, so multipletransactions can hold read lockstransactions can hold read lockssimultaneously on the same itemsimultaneously on the same item

    yyWrite lock gives one transaction exclusiveWrite lock gives one transaction exclusive

    access to an itemaccess to an itemyy Transaction can upgrade a read lock to aTransaction can upgrade a read lock to a

    write lock, or downgrade a write lock to awrite lock, or downgrade a write lock to aread lockread lock

    yy Commits or rollbacks release the locksCommits or rollbacks release the locks

  • 8/7/2019 Database transaction & transaction management

    18/25

    DeadlockDeadlockyy What is deadlock?What is deadlock?

    When two (or more) transactions are each waitingWhen two (or more) transactions are each waiting

    for locks held by the other to be releasedfor locks held by the other to be releasedyy Breaking a deadlockBreaking a deadlock

    Only one way to break deadlock: abort one orOnly one way to break deadlock: abort one or

    more of the transactionsmore of the transactions

  • 8/7/2019 Database transaction & transaction management

    19/25

    Dealing with DeadlockDealing with DeadlockyyDeadlock preventionDeadlock preventionTransaction cant obtain a new lock if theTransaction cant obtain a new lock if the

    possibility of a deadlock existspossibility of a deadlock exists

    yyDeadlock avoidanceDeadlock avoidanceTransaction must obtain all the locks it needsTransaction must obtain all the locks it needs

    before it startsbefore it starts

    yy

    Deadlock detection and recoveryDeadlock detection and recoveryDB checks for possible deadlocksDB checks for possible deadlocks

    If deadlock is detected, one of the transactions isIf deadlock is detected, one of the transactions iskilled, then restartedkilled, then restarted

  • 8/7/2019 Database transaction & transaction management

    20/25

    Transactions and RecoveryTransactions and Recoveryyy Transactions represent basic unit of recoveryTransactions represent basic unit of recovery

    yy Recovery manager responsible for atomicity andRecovery manager responsible for atomicity anddurabilitydurability

    yy Whathappens at failure?Whathappens at failure? If transaction had not committed at failure time,If transaction had not committed at failure time,

    recovery manager has torecovery manager has to undoundo ((rollbackrollback) any effects) any effectsof that transaction for atomicityof that transaction for atomicity

    If failure occurs between commit and databaseIf failure occurs between commit and databasebuffers being flushed to secondary storage,buffers being flushed to secondary storage,recovery manager has torecovery manager has to redoredo ((rollforwardrollforward))transaction's updatestransaction's updates

  • 8/7/2019 Database transaction & transaction management

    21/25

    Recovery from CrashRecovery from Crashyy RollbackRollbackRecover to the starting state:Recover to the starting state:

    yy Take snapshot (checkpoint) of starting stateTake snapshot (checkpoint) of starting state

    E.g., initial bank balance (and all other states)E.g., initial bank balance (and all other states) And keep a redo logAnd keep a redo log

    yy Alternative: keep an undo logAlternative: keep an undo log

    E.g., bank balance changed: old value was xE.g., bank balance changed: old value was x

    yy Resume (if recoverable)Resume (if recoverable)Redo all committed actions (since lastRedo all committed actions (since last

    checkpoint)checkpoint)

    Or undo all uncommitted actionsOr undo all uncommitted actions

  • 8/7/2019 Database transaction & transaction management

    22/25

    Recovering From a CrashRecovering From a Crashyy There are 3 phases in the recovery algorithm:There are 3 phases in the recovery algorithm:AnalysisAnalysis scan the log forward to identify allscan the log forward to identify all

    transactions that were active, and all dirty pages intransactions that were active, and all dirty pages inthe buffer pool at the time of the crashthe buffer pool at the time of the crash

    RedoRedo redoes all updates to dirty pages in theredoes all updates to dirty pages in thebuffer pool, as needed, to ensure that all loggedbuffer pool, as needed, to ensure that all loggedupdates are in fact carried out and written to diskupdates are in fact carried out and written to disk

    UndoUndo all transactions th

    at were active at th

    e crash

    all transactions th

    at were active at th

    e crash

    are undone, working backwards in the logare undone, working backwards in the log

    yy Some care must be taken to handle the case of aSome care must be taken to handle the case of acrash occurring during the recovery process!crash occurring during the recovery process!

  • 8/7/2019 Database transaction & transaction management

    23/25

    Transactions and SQLTransactions and SQLyy Start a transactionStart a transaction

    BEGIN TRANSACTIONBEGIN TRANSACTION

    Some databases assume implicit startSome databases assume implicit start E.g. OracleE.g. Oracle

    yy Ending a transactionEnding a transaction

    COMMITCOMMITyy U

    sed to end a successful transaction and makeU

    sed to end a successful transaction and makechanges permanentchanges permanent

    ROLLBACKROLLBACKyy Undo changes from an aborted transactionUndo changes from an aborted transaction

    yy May be done automatically when failure occursMay be done automatically when failure occurs

  • 8/7/2019 Database transaction & transaction management

    24/25

    Transactions in SQLTransactions in SQL

    Server: ExampleServer: Exampleyy We have a table with bank accountsWe have a table with bank accounts::

    yy We use a transaction to transfer moneyWe use a transaction to transfer moneyfrom one account into anotherfrom one account into another

    CREATE TABLECREATE TABLE ACCOUNTACCOUNT((id int NOT NULL,id int NOT NULL,balancebalance decimaldecimal NOT NULL)NOT NULL)

    CREATE OR REPLACE PROCEDURE sp_Transfer_Funds(CREATE OR REPLACE PROCEDURE sp_Transfer_Funds(

    from_account IN INT,from_account IN INT,to_account IN INT,to_account IN INT,

    ammount INammount IN NUMBERNUMBER) IS) IS

    BEGINBEGIN

    BEGIN TRANBEGIN TRAN

    ((example continuesexample continues))

  • 8/7/2019 Database transaction & transaction management

    25/25

    Transactions in SQLTransactions in SQL

    Server: Example (2)Server: Example (2)yy UPDATE ACCOUNT set balance = balanceUPDATE ACCOUNT set balance = balance -- ammountammountyy WHERE id = from_account;WHERE id = from_account;

    yy IF SQL%ROWCOUNTIF SQL%ROWCOUNT 11 THENTHEN

    yy ROLLBACK;ROLLBACK;

    yy RAISE_APPLICATION_ERROR(RAISE_APPLICATION_ERROR(--20001, 'Invalid src20001, 'Invalid srcaccount!');account!');

    yy END IF;END IF;

    yy UPDATE ACCOUNT set balance = balance + ammountUPDATE ACCOUNT set balance = balance + ammount

    yy WHERE id = to_account;WHERE id = to_account;

    yy

    IF SQL%ROWCOUNTIF SQL%ROWCOUNT 11 THENTHENyy ROLLBACK;ROLLBACK;

    yy RAISE_APPLICATION_ERROR(RAISE_APPLICATION_ERROR(--20002, 'Invalid dst20002, 'Invalid dst

    account!');account!');

    yy END IF;END IF;

    yy COMMIT;COMMIT;

    yy END;END;