31
Transaction Transaction control and control and isolation levels isolation levels in Oracle in Oracle Evgeniya Kotzeva Vereo Technologies www.vereo.bg academy.devbg.org www.devbg.org

Transaction control and isolation levels in Oracle Evgeniya Kotzeva Vereo Technologies Vereo Technologies academy.devbg.org

Embed Size (px)

Citation preview

Transaction control Transaction control and isolation levels and isolation levels

in Oraclein OracleEvgeniya KotzevaEvgeniya Kotzeva

Vereo Technologieswww.vereo.bg

Vereo Technologieswww.vereo.bg

academy.devbg.orgacademy.devbg.org www.devbg.orgwww.devbg.org

ContentsContents

• TransactionTransaction controlcontrol

• Data Concurrency and Consistency Data Concurrency and Consistency in a Multiuser Environmentin a Multiuser Environment

• LockingLocking

Database TransactionDatabase Transaction

A database transaction consists of one of A database transaction consists of one of thethe following:following:

• DML statements which constitute one DML statements which constitute one consistentconsistent change to the datachange to the data

• One DDL statementOne DDL statement

• One DCL statementOne DCL statement

Oracle Transaction TypesOracle Transaction Types

TypeType DescriptionDescription

Data manipulation Data manipulation language (DMLlanguage (DML))

Consists of any number of DML Consists of any number of DML statements that the Oracle statements that the Oracle server treats as a single entity server treats as a single entity or a logical unit of workor a logical unit of work

Data definition Data definition languagelanguage

(DDL)(DDL)

Consists of only one DDL Consists of only one DDL statementstatement

Data control languageData control language

(DCL)(DCL)

Consists of only one DCL Consists of only one DCL statementstatement

Transaction boundariesTransaction boundaries

A transaction begins with A transaction begins with the first executable SQL the first executable SQL statement.statement.

A transaction ends with A transaction ends with one of the following one of the following events:events:

• A COMMIT or A COMMIT or ROLLBACK statement is ROLLBACK statement is issuedissued

• A DDL or DCL statement A DDL or DCL statement executes (automatic executes (automatic commit)commit)

• The user exits The user exits iiSQL*PlusSQL*Plus

• The system crashesThe system crashes

Advantages of COMMITAdvantages of COMMITand ROLLBACKand ROLLBACK

With COMMIT and ROLLBACK statements, you With COMMIT and ROLLBACK statements, you can:can:

• Ensure data consistencyEnsure data consistency

• Preview data changes before making changesPreview data changes before making changes

permanentpermanent

• Group logically related operationsGroup logically related operations

Controlling transactionControlling transaction

COMMIT transactionCOMMIT transaction

BeforeBefore COMMIT COMMIT

• generated rollback generated rollback segment records in buffers segment records in buffers in the SGAin the SGA

• generated redo log entries generated redo log entries in the redo log buffer of in the redo log buffer of the SGA.the SGA.

• The changes have been The changes have been made to the database made to the database buffers of the SGA.buffers of the SGA.

AfterAfter COMMIT COMMIT

• The internal transaction The internal transaction table for the associated table for the associated rollback segment records rollback segment records updated with SCNupdated with SCN

• LGWR writes SGA redo LGWR writes SGA redo log entries to the online log entries to the online redo log fileredo log file

• Oracle releases locksOracle releases locks

• Oracle marks the Oracle marks the transaction complete.transaction complete.

ROLLBACK transactionROLLBACK transaction

ROLLBACKROLLBACK

• Oracle undoes all Oracle undoes all transaction changes using transaction changes using the undo tablespace or the undo tablespace or rollback segmentsrollback segments

• Oracle releases all the Oracle releases all the transaction’s locks of datatransaction’s locks of data

• The transaction endsThe transaction ends

ROLLBACK to SAVEPOINTROLLBACK to SAVEPOINT

• Oracle rolls back only the Oracle rolls back only the statements run after the statements run after the savepoint.savepoint.

• Oracle preserves the Oracle preserves the specified savepoint, but all specified savepoint, but all savepoints that were savepoints that were established after the established after the specified one are lostspecified one are lost

• Oracle releases all table Oracle releases all table and row locks acquired and row locks acquired since that savepointsince that savepoint

State of the DataState of the DataBefore COMMIT or ROLLBACKBefore COMMIT or ROLLBACK

• The previous state of the dataThe previous state of the data can be recoveredcan be recovered..

• The current userThe current user can reviewcan review the results of thethe results of the DML operations by using the SELECT statement.DML operations by using the SELECT statement.

• Other usersOther users can not viewcan not view the results of the DML the results of the DML statements by the current user.statements by the current user.

• The affected rowsThe affected rows are lockedare locked

• Other usersOther users cannot changecannot change the data within the the data within the affected rows.affected rows.

State of the Data after COMMITState of the Data after COMMIT

• Data changes are made Data changes are made permanentpermanent in the in the database.database.

• The previous state of the data The previous state of the data is permanently lostis permanently lost..

• All users All users can viewcan view the results. the results.

• Locks on the affected rows Locks on the affected rows are releasedare released; those ; those rows are available for other users to manipulate.rows are available for other users to manipulate.

• All savepoints All savepoints are erasedare erased..

Distributed databaseDistributed database

• Distributed transaction Distributed transaction is a transaction that is a transaction that includes one or more statements that update data includes one or more statements that update data on two or more distinct nodes of a distributed on two or more distinct nodes of a distributed database database

• A A two-phase commit two-phase commit mechanism guaranteesmechanism guarantees the the data consistent in all nodes. data consistent in all nodes.

Autonomous transactionAutonomous transactionss

• Autonomous transactions are independent Autonomous transactions are independent transactions that can be called from within another transactions that can be called from within another transactiontransaction

• An autonomous transaction lets you leave the An autonomous transaction lets you leave the context of the calling transaction context of the calling transaction

• You can call autonomous transactions from within You can call autonomous transactions from within a PL/SQL block by using the pragma a PL/SQL block by using the pragma AUTONOMOUS_TRANSACTION.AUTONOMOUS_TRANSACTION.

Data Concurrency and Data Concurrency and ConsistencyConsistency

• Data concurrency Data concurrency means that many users can means that many users can access data at the same time.access data at the same time.

• Data consistency Data consistency means that each user sees a means that each user sees a consistent view of the data, including visible consistent view of the data, including visible changes made by the user’s own transactions and changes made by the user’s own transactions and transactions of other users.transactions of other users.

The isolation models preventsThe isolation models prevents

• Dirty readsDirty reads

• Nonrepeatable (fuzzy) readsNonrepeatable (fuzzy) reads

• Phantom readsPhantom reads

Isolation levels (SQL92) controlsIsolation levels (SQL92) controls

Isolation Isolation

LevelLevel

Dirty Dirty ReadRead

Nonrepeatable Nonrepeatable ReadRead

Phantom Phantom ReadRead

Read Read uncommitteduncommitted

YY YY YY

Read committedRead committed NN YY YY

Repeatable readRepeatable read NN NN YY

SerializableSerializable NN NN NN

Oracle isolation levelsOracle isolation levels

Read committedRead committed Each query executed by a transaction Each query executed by a transaction sees only data that was committed sees only data that was committed before the query began (Oracle default before the query began (Oracle default isolation level)isolation level)

SerializableSerializable Serializable transactions see only those Serializable transactions see only those changes that were committed at the changes that were committed at the time the transaction began, plus its own time the transaction began, plus its own changeschanges

Read-onlyRead-only The transaction sees only those The transaction sees only those changes that were committed at the changes that were committed at the time the transaction began and do not time the transaction began and do not allow any DML statementallow any DML statement

Multiversion Concurrency ControlMultiversion Concurrency Control

• Statement-level read consistencyStatement-level read consistency

The data returned by a single query comes from a The data returned by a single query comes from a single point in time — the time that the query single point in time — the time that the query beganbegan

• Transaction-level read consistencyTransaction-level read consistency

When a transaction executes in serializable mode, When a transaction executes in serializable mode, all data accesses reflect the state of the database all data accesses reflect the state of the database as of the time the transaction beganas of the time the transaction began

Transactions and Read Transactions and Read ConsistencyConsistency

““Snapshot too old”Snapshot too old”

When commit or rollback has been executed, When commit or rollback has been executed, the pre-images can be overwritten the pre-images can be overwritten even if even if they are needed to provide a read-they are needed to provide a read-consistent view to another query.consistent view to another query.

"Snapshot too old" simply means that pre-"Snapshot too old" simply means that pre-images which the query needs to maintain a images which the query needs to maintain a read-consistent view have been overwritten.read-consistent view have been overwritten.

Common recommendations Common recommendations

Common recommendations to reduce the possibility of Common recommendations to reduce the possibility of "snapshot too old" are: "snapshot too old" are:

• Keep transactions as fast as possibleKeep transactions as fast as possible

• Increase the size/number of rollback segments Increase the size/number of rollback segments

• Do Do notnot specify an OPTIMAL size for your rollback specify an OPTIMAL size for your rollback segments. segments.

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

• Avoid executing long-running queries when transactions Avoid executing long-running queries when transactions which update the table are also executing. which update the table are also executing.

Set the Isolation LevelSet the Isolation Level

You can set the isolation level of a transaction by You can set the isolation level of a transaction by usingusing one of these statements at the beginning of one of these statements at the beginning of a transaction:a transaction:

• SET TRANSACTION ISOLATION LEVELSET TRANSACTION ISOLATION LEVEL READ COMMITTED;READ COMMITTED;

• SET TRANSACTION ISOLATION LEVEL SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;SERIALIZABLE;

• SET TRANSACTION ISOLATION LEVELSET TRANSACTION ISOLATION LEVEL READ ONLY;READ ONLY;

Serializable Transaction FailureSerializable Transaction Failure

Modes of LockingModes of Locking

• Exclusive lockExclusive lock

The mode prevents the associates resource from The mode prevents the associates resource from being shared being shared

• Share lockShare lock

The mode allows the associated resource to be The mode allows the associated resource to be shared, depending on the operations involved shared, depending on the operations involved

DeadlockDeadlock

Types of LocksTypes of Locks

LockLock DescriptionDescription

DML locksDML locks (data locks) (data locks) DML locks protect dataDML locks protect data

For example, table locks lock For example, table locks lock entire tables, rowlocks lock entire tables, rowlocks lock selected rows.selected rows.

DDL locksDDL locks (dictionary (dictionary locks)locks) DDL locks protect the DDL locks protect the structure of schema objects structure of schema objects

Internal locksInternal locks and latches and latches Internal locks and latches Internal locks and latches protect internal database protect internal database structures such as datafiles structures such as datafiles

Table LocksTable Locks

• RS: row shareRS: row share

• RX: row exclusiveRX: row exclusive

• S: shareS: share

• SRX: share row SRX: share row

exclusiveexclusive

• X: exclusiveX: exclusive

Data Lock EscalationData Lock Escalation

• A transaction holds exclusive row locks for A transaction holds exclusive row locks for all rows inserted, updated, or deleted within all rows inserted, updated, or deleted within the transaction. Because row locks are the transaction. Because row locks are acquired at the highest degree of acquired at the highest degree of restrictiveness, no lock conversion is restrictiveness, no lock conversion is required or performed.required or performed.

• Oracle automatically converts a table lock of Oracle automatically converts a table lock of lower restrictiveness to one of higher lower restrictiveness to one of higher restrictiveness as appropriaterestrictiveness as appropriate

MS SQL Isolation Levels MS SQL Isolation Levels

Microsoft SQL Server 2005Microsoft SQL Server 2005 OracleOracle

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

READ COMMITTED with READ COMMITTED with snapshotssnapshots

READ COMMITTED READ COMMITTED

SNAPSHOTSNAPSHOT SERIALIZABLE SERIALIZABLE

SNAPSHOTSNAPSHOT READ ONLY READ ONLY

READ UNCOMMITTED READ UNCOMMITTED No Equivalent No Equivalent

READ COMMITTED with lockingREAD COMMITTED with locking No Equivalent No Equivalent

REPEATABLE READREPEATABLE READ No Equivalent No Equivalent

SERIALIZABLESERIALIZABLE No EquivalentNo Equivalent

DB2 Isolation LevelsDB2 Isolation Levels

Isolation levelsIsolation levels

• Repeatable Read (RR)Repeatable Read (RR)

• Read Stability (RS)Read Stability (RS)

• Cursor Stability (CS)Cursor Stability (CS)

• Uncommitted Read (UR)Uncommitted Read (UR)

Levels of lockingLevels of locking

• TablespaceTablespace

• TableTable

• RowRow

Transactions in OracleTransactions in Oracle

Въпроси?Въпроси?