Lesson4 Transactions

Embed Size (px)

Citation preview

  • 8/2/2019 Lesson4 Transactions

    1/22

    3/18/20

    Transactions

    Contents

    Transaction Concept

    Transaction State

    1. Introduction To transaction Processing

    1.1 Single User VS Multi User Systems

    One criteria to classify Database isaccording to number of user that

    concurrently connect to the system.

    Single User: only one user use the system

    in each time

    Multi User: many users use the system in

    the same time

  • 8/2/2019 Lesson4 Transactions

    2/22

    3/18/20

    Example of transaction

    Let Ti be a transaction that transfermoney from account A (5000) to accountB. The transaction can be defined as Ti: read (A) (withdraw from A)

    A := A 5000

    write (A); (update A)

    read (B) (deposit B)

    B := B + 5000

    write (B) (update B)

    Why recovery is needed?

    Transaction submitted for execution

    DBMS is responsible for making sure thateither

    All operationsin transaction are completedsuccessfully and the changes is recordedpermanently in the database.

    The DBMS must not permit some operations

    of a transaction T to be applied to the DB whileothers of T are not.

    (will cause inconsistency)

    Failures Type

    Generally classified as

    Transaction Failure

    System Failure

    Media Failure

  • 8/2/2019 Lesson4 Transactions

    3/22

    3/18/20

    Reasons for a transaction fails

    in the middle of executionAcomputer failure (System crash) media

    failures

    A transaction or system error: logical programerror

    Load error or exception conditions detected bythe transaction :no data for the transaction

    Concurrency control enforcement: by concurrencycontrol method

    Disk failure

    Physical problems and catastrophes: ex. Powerfailure, fire, overwrite disk

    Transaction or system error

    Some operation in transaction may cause it to

    fail, such as integer overflow or divide by zero.

    May occur because of erroneous parameter

    values

    Logical programming

    User may interrupt during execution

    Local error or exception conditions

    detected by transaction During transaction execution, conditions may

    occur that necessitate cancellation of the

    transaction

    Ex. Data for the transaction may not found

    Exception should be programmed (not be

    consider failure)

  • 8/2/2019 Lesson4 Transactions

    4/22

    3/18/20

    Concurrency control

    enforcement The concurrency control method may

    decide to abort the transaction, Because of violent serializability

    Because several transaction are in state of

    deadlock

    Transaction states and

    additional Operation For recovery purpose, the system needs

    to keep track of when the transaction

    starts,

    terminates,

    and commits or aborts.

    What information that the recoverymanager keep track?

    Transaction states and

    additional Operation The recovery manager keep track of the followings

    Begin_transaction: mark the beginning of transactionexecute

    Read or write: specified operations on the databaseitem that executes as part of transaction

    End_transaction: specifies that operations have endedand marks the end of execution (Necessary to check)

    The change can be committed

    Or whether the transaction has to aborted

    Commit_Transaction: successful end (will not undo)

    Rollback: unsuccessful end (undone)

  • 8/2/2019 Lesson4 Transactions

    5/22

    3/18/20

    State of transaction

    Active, the initial state; the transaction staysin this state while it is executing.

    Partially committed, after the final statementhas been executed

    Failed, after the discovery that normalexecution can no longer proceed.

    Aborted, after the transaction has been rolledbacked and the database has been restored toits state prior to the start of transaction.

    Committed, after successful completion

    State diagram of a transition

    A transaction must be in one of these states.

    Partially

    Committed

    Aborted(Terminate)

    Active

    Begin

    Transaction

    Read

    Write

    Abort

    Failed

    committedCommit

    The transaction has committed only if it has

    entered the committed state.

    The transaction has aborted only if it has

    entered the aborted state.

    The transaction is said to have terminated if

    has either committed or aborted.

  • 8/2/2019 Lesson4 Transactions

    6/22

    3/18/20

    The System Log

    The system maintain log by keep track of all

    transactions that effect the database. Log is kept on Disk.

    Effected only by disk or catastrophic failure

    Keep Log records

    Log records

    T is transaction ID

    (Start_transaction, T) start transaction

    (Write_item, T, X, old_value, new_value)

    transaction write/update item x

    (Read_item, T, X) transaction read item X

    (Commit, T) complete operation of T

    (Abort, T) terminate transaction T

    System Log (cont.)

    Log file keep track

    start transaction complete transaction

    System fail occur

    Restart system, system will recovery

    Redo transaction that already commit

    Undo no commit transaction

  • 8/2/2019 Lesson4 Transactions

    7/22

    3/18/20

    Commit point of a transaction

    When is the transaction T reach its commit

    point?

    Answeris when all its operations that access

    the database have been executed successfully

    and the effect of all the transaction operations

    on the database have been recorded in the

    log.

    The transaction is said to be committed

    (Cont.)

    At committed point

    Write [commit] in log file

    Failure occur

    Search in log file looking for all transactions T, that

    have write [Start_Transaction ,T]

    If no commit, Rollback transaction

    If commit found, Redo transaction

    Desirable properties of

    transaction : ACID properties To ensure integrity of data, we require that

    the database system maintain the following

    properties of the transactions:

    Atomicity.

    Consistency preservation.

    Isolation.

    Durability or permanency.

  • 8/2/2019 Lesson4 Transactions

    8/22

    3/18/20

    ACID Atomicity. Either all operations of the

    transaction are reflected properly in thedatabase, or none are.

    Consistency. Execution of a transaction inisolations (that is, with no other transactionexecuting concurrently)

    Isolation. Even though multiple transactionsmay execute concurrently, the systemguarantees that, for every pair of transactions Tiand Tj, it appears to Ti that

    either Tj finished execution before T i started,

    or Tj started execution after Ti finished.

    Thus, each transaction is unaware of othertransactions executing concurrently in the system.

    Durability. After a transaction completessuccessfully, the changes it has made to the

    database persist, even if there are systemfailures.

    (The changes must not be lost because of any failure)

    Atomicity

    Atomicity. Either all operations of the transactionare reflected properly in the database, or noneare.

    State before the execution of transaction Ti

    The value of A = 50,000

    The value of B = 100

    Failure occur (ex. Hardware failure)

    Failure happen after the WRITE(A) operation

    (at this moment A = 50000 5000 = 45000)

    And the value of B = 100 (inconsistency state)

    In consistency state A = 45000 and B = (5100)

  • 8/2/2019 Lesson4 Transactions

    9/22

    3/18/20

    (cont.)

    Idea behind ensuring atomicity is

    following:

    The database system keeps track of the old

    values of any data on which a transaction

    performs a write

    If the transaction does not complete, the

    DBMS restores the old values to make it

    appear as though the transaction have

    never execute.

    Consistency

    Consistency.

    The consistency requirement here is that thesum of A and B be unchanged by theexecution of the transaction.

    Without consistency requirement, moneycould be created or destroyed by thetransaction.

    It can be verified,

    If the database is consistency before an executionof the transaction, the database remainsconsistent after the execution of the transaction.

    Durability or permanency

    Durability or permanency. After a transaction

    completes successfully, the changes it hasmade to the database persist, even if thereare system failures.

    These changes must not be lost because of anyfailure

    ensures that, transaction has been committed, thattransactions updates do not get lost, even if there is

    a system failure

  • 8/2/2019 Lesson4 Transactions

    10/22

    3/18/20

    Isolation

    Isolation. Even though multiple transactions mayexecute concurrently, the system guarantees that,

    for every pair of transactions Ti and Tj,

    it appears to Ti that either Tj finished execution before Tistarted,

    or Tj started execution after Ti finished.

    Thus, each transaction is unaware of other transactionsexecuting concurrently in the system.

    ( Execution of transaction should not beinterfered with by any other transactionsexecuting concurrently )

    Concurrent Executions

    Transaction processing permit

    Multiple transactions to run concurrently.

    Multiple transactions to update data concurrently

    Cause

    Complications with consistency of data

    Reason for allowing concurrency

    Improved throughputof transactions

    and system resource utilization

    Reduced waiting time of transactions

  • 8/2/2019 Lesson4 Transactions

    11/22

    3/18/20

    Possible Problems

    Lost update problem

    Temporary update problem

    Incorrect summary problem

    Example transaction

    Transfer money from

    account A to B

    Read_item(A)

    A := A 50

    Write_item(A)

    Read_item(B)

    B := B + 50

    Write_item(B)

    Transfer 10% of A to

    Account B

    Read_item(A)

    temp := 0.1*A

    A:= A-temp

    Write_item(A)

    Read_item(B)

    B := B + temp

    Write_item(B)

    Lost update problem

    T1 T2

    Read_item(A)

    A := A

    50Read_item(A)

    temp := 0.1*A

    A:= A-temp

    Write_item(A)

    Read_item(B)

    Write_item(A)

    Read_item(B)

    B := B + 50

    Write_item(B)

    B := B + temp

    Write_item(B)

    A = 1000, B =2000

    A = 950

    A = 950

    temp = 95

    A=950-95

    = 855A = 950

    B = 2000

    A = 855

    B = 2000

    B = 2050

    B = 2050

    B = 2095

    B = 2095

    A = 1000

  • 8/2/2019 Lesson4 Transactions

    12/22

    3/18/20

    Temporary update problem

    T1 T2

    - Write_item(R)

    Read_item(R) -

    - RollBack

    R = 1000

    R = 1000

    R = 3000

    R = 3000

    Inconsistency problem

    T1 T2

    Read_item(A)

    SUM = Sum+A

    Read_item(B)

    SUM = A + B

    Read_item(C)

    C = C - 10

    Write_item(C)

    Read_item(A)

    A = A + 10

    Write_item(A)

    COMMIT

    Read_item(C)

    SUM = SUM + C

    A = 40 , B = 50, C = 30

    A = 40

    Sum = 40

    B = 50

    SUM = 40+50

    = 90

    C = 30

    C = 30-10 =20

    C = 20

    A = 40

    A = 40+10 =50

    A = 50

    C = 20

    Sum = 90 + 20 = 110

    A+B+C = 40+50+30 = 120

    After

    A+B+C = 50+50+20 = 120

    Contents

    Transaction control in oracle Data Concurrency and Consistency in

    a Multiuser Environment

    Locking

  • 8/2/2019 Lesson4 Transactions

    13/22

    3/18/20

    Database Transaction

    A database transaction consists of one of

    the following:

    DML statements which constitute one

    consistent change to the data

    One DDL statement

    One DCL statement

    Oracle Transaction Types

    Type Description

    Data manipulationlanguage (DML)

    Consists of any number ofDML statements that theOracle server treats as asingle entity or a logical unitof work

    Data definitionlanguage

    (DDL)

    Consists of only one DDLstatement

    Data controllanguage

    (DCL)

    Consists of only one DCLstatement

    Transaction boundaries

    A transaction

    begins with the

    first executable

    SQL statement.

    A transaction ends with

    one of the followingevents:

    A COMMIT or ROLLBACK

    statement is issued

    A DDL or DCL statement

    executes (automatic

    commit)

    The user exits iSQL*Plus

    The system crashes

  • 8/2/2019 Lesson4 Transactions

    14/22

    3/18/20

    Advantages of COMMIT

    and ROLLBACK

    With COMMIT and ROLLBACK statements, you

    can:

    Ensure data consistency

    Preview data changes before making changes

    permanent

    Group logically related operations

    Controlling transaction

    COMMIT transaction

    Before COMMIT

    generated rollback segment

    records in buffers in the

    SGA

    generated redo log entries

    in the redo log buffer of the

    SGA.

    The changes have been

    made to the database

    buffers of the SGA.

    After COMMIT

    The internal transaction

    table for the associated

    rollback segment records

    updated with SCN

    LGWR writes SGA redo log

    entries to the online redo

    log file

    Oracle releases locks

    Oracle marks the

    transaction complete.

  • 8/2/2019 Lesson4 Transactions

    15/22

    3/18/20

    ROLLBACK transaction

    ROLLBACK

    Oracle undoes all

    transaction changes usingthe undo tablespace or

    rollback segments

    Oracle releases all the

    transactions locks of data

    The transaction ends

    ROLLBACK to SAVEPOINT

    Oracle rolls back only thestatements run after thesavepoint.

    Oracle preserves thespecified savepoint, but allsavepoints that wereestablished after thespecified one are lost

    Oracle releases all table androw locks acquired sincethat savepoint

    State of the Data

    Before COMMIT or ROLLBACK

    The previous state of the datacan be

    recovered.

    The current usercan reviewthe results of the

    DML operations by using the SELECT statement.

    Other userscan not viewthe results of the DML

    statements by the current user.

    The affected rowsare locked

    Other userscannot changethe data within the

    affected rows.

    State of the Data after COMMIT

    Data changes are madepermanentin the

    database.

    The previous state of the data is permanentlylost.

    All users can viewthe results.

    Locks on the affected rows are released; thoserows are available for other users tomanipulate.

    All savepoints are erased.

  • 8/2/2019 Lesson4 Transactions

    16/22

    3/18/20

    Distributed database

    Distributed transaction is a transaction that

    includes one or more statements that update

    data on two or more distinct nodes of a

    distributed database

    A two-phase commit mechanism guarantees

    the data consistent in all nodes.

    Autonomous transactions

    Autonomous transactions are independent

    transactions that can be called from within

    another transaction

    An autonomous transaction lets you leave the

    context of the calling transaction

    You can call autonomous transactions from

    within a PL/SQL block by using the pragma

    AUTONOMOUS_TRANSACTION.

    Data Concurrency and Consistency

    Data concurrency means that many users can

    access data at the same time.

    Data consistency means that each user sees a

    consistent view of the data, including visible

    changes made by the users own transactions

    and transactions of other users.

  • 8/2/2019 Lesson4 Transactions

    17/22

    3/18/20

    The isolation models prevents

    Dirty reads

    Nonrepeatable (fuzzy) reads

    Phantom reads

    Isolation levels (SQL92) controls

    Isolation

    Level

    DirtyRead

    NonrepeatableRead

    PhantomRead

    Readuncommitted

    Y Y Y

    Read committed N Y Y

    Repeatable read N N Y

    Serializable N N N

    Oracle isolation levels

    Read committed Each query executed by a transactionsees only data that was committedbefore the query began (Oracle defaultisolation level)

    Serializable Serializable transactions see only thosechanges that were committed at thetime the transaction began, plus its ownchanges

    Read-only The transaction sees only thosechanges that were committed at thetime the transaction began and do notallow any DML statement

  • 8/2/2019 Lesson4 Transactions

    18/22

    3/18/20

    Multiversion Concurrency Control

    Statement-level read consistency

    The data returned by a single query comes from

    a single point in time the time that the query

    began

    Transaction-level read consistency

    When a transaction executes in serializable

    mode, all data accesses reflect the state of the

    database as of the time the transaction began

    Transactions and Read Consistency

    Snapshot too old

    When commit or rollback has been executed,

    the pre-images can be overwritten even if they

    are needed to provide a read-consistent view

    to another query.

    "Snapshot too old" simply means that pre-

    images which the query needs to maintain a

    read-consistent view have been overwritten.

  • 8/2/2019 Lesson4 Transactions

    19/22

    3/18/20

    Common recommendations

    Common recommendations to reduce the possibility of

    "snapshot too old" are:

    Keep transactions as fast as possible Increase the size/number of rollback segments

    Do notspecify an OPTIMAL size for your rollback

    segments.

    Increase the size of UNDO_RETENTION parameter(amount of committed undo information to retain in the database)

    Avoid executing long-running queries when

    transactions which update the table are also

    executing.

    Set the Isolation Level

    You can set the isolation level of a transaction byusing one of these statements at thebeginning of a transaction:

    SET TRANSACTION ISOLATION LEVELREAD COMMITTED;

    SET TRANSACTION ISOLATION LEVELSERIALIZABLE;

    SET TRANSACTION ISOLATION LEVELREAD ONLY;

    Serializable Transaction Failure

  • 8/2/2019 Lesson4 Transactions

    20/22

    3/18/20

    Modes of Locking

    Exclusive lock

    The mode prevents the associates resource frombeing shared

    Share lock

    The mode allows the associated resource to be

    shared, depending on the operations involved

    Deadlock

    Types of Locks

    Lock Description

    DML locks (data locks) DML locks protect data

    For example, table locks lockentire tables, rowlocks lockselected rows.

    DDL locks (dictionary locks) DDL locks protect thestructure of schema objects

    Internal locks and latches Internal locks and latchesprotect internal databasestructures such as datafiles

  • 8/2/2019 Lesson4 Transactions

    21/22

    3/18/20

    Table Locks

    RS: row share

    RX: row exclusive

    S: share

    SRX: share row

    exclusive

    X: exclusive

    Data Lock Escalation

    A transaction holds exclusive row locks for all

    rows inserted, updated, or deleted within the

    transaction. Because row locks are acquired at

    the highest degree of restrictiveness, no lock

    conversion is required or performed.

    Oracle automatically converts a table lock of

    lower restrictiveness to one of higher

    restrictiveness as appropriate

    MS SQL Isolation Levels

    Microsoft SQL Server 2005 Oracle

    SELECT ... WITH (UPDLOCK) SELECT... FOR UPDATE

    READ COMMITTED withsnapshots

    READ COMMITTED

    SNAPSHOT SERIALIZABLE

    SNAPSHOT READ ONLY

    READ UNCOMMITTED No Equivalent

    READ COMMITTED with locking No Equivalent

    REPEATABLE READ No Equivalent

    SERIALIZABLE No Equivalent

  • 8/2/2019 Lesson4 Transactions

    22/22

    3/18/20

    DB2 Isolation Levels

    Isolation levels

    Repeatable Read (RR)

    Read Stability (RS) Cursor Stability (CS)

    Uncommitted Read (UR)

    Levels of locking

    Tablespace

    Table

    Row