Oracle® Database Concepts 10g Release 2 (10.2) Part Number B14220-02 |
|
|
PDF · Mobi · ePub |
This chapter defines a transaction and describes how you can manage your work using transactions.
This chapter contains the following topics:
A transaction is a logical unit of work that contains one or more SQL statements. A transaction is an atomic unit. The effects of all the SQL statements in a transaction can be either all committed (applied to the database) or all rolled back (undone from the database).
A transaction begins with the first executable SQL statement. A transaction ends when it is committed or rolled back, either explicitly with a COMMIT
or ROLLBACK
statement or implicitly when a DDL statement is issued.
To illustrate the concept of a transaction, consider a banking database. When a bank customer transfers money from a savings account to a checking account, the transaction can consist of three separate operations:
Decrement the savings account
Increment the checking account
Record the transaction in the transaction journal
Oracle must allow for two situations. If all three SQL statements can be performed to maintain the accounts in proper balance, the effects of the transaction can be applied to the database. However, if a problem such as insufficient funds, invalid account number, or a hardware failure prevents one or two of the statements in the transaction from completing, the entire transaction must be rolled back so that the balance of all accounts is correct.
Figure 4-1illustrates the banking transaction example.
A SQL statement that runs successfully is different from a committed transaction. Executing successfully means that a single statement was:
Parsed
Found to be a valid SQL construction
Run without error as an atomic unit. For example, all rows of a multirow update are changed.
However, until the transaction that contains the statement is committed, the transaction can be rolled back, and all of the changes of the statement can be undone. A statement, rather than a transaction, runs successfully.
Committing means that a user has explicitly or implicitly requested that the changes in the transaction be made permanent. An explicit request occurs when the user issues a COMMIT
statement. An implicit request occurs after normal termination of an application or completion of a data definition language (DDL) operation. The changes made by the SQL statement(s) of a transaction become permanent and visible to other users only after that transaction commits. Queries that are issued after the transaction commits will see the committed changes.
You can name a transaction using the SET
TRANSACTION
... NAME
statement before you start the transaction. This makes it easier to monitor long-running transactions and to resolve in-doubt distributed transactions.
See Also:
"Transaction Naming"If at any time during execution a SQL statement causes an error, all effects of the statement are rolled back. The effect of the rollback is as if that statement had never been run. This operation is a statement-level rollback.
Errors discovered during SQL statement execution cause statement-level rollbacks. An example of such an error is attempting to insert a duplicate value in a primary key. Single SQL statements involved in a deadlock (competition for the same data) can also cause a statement-level rollback. Errors discovered during SQL statement parsing, such as a syntax error, have not yet been run, so they do not cause a statement-level rollback.
A SQL statement that fails causes the loss only of any work it would have performed itself. It does not cause the loss of any work that preceded it in the current transaction. If the statement is a DDL statement, then the implicit commit that immediately preceded it is not undone.
Note:
Users cannot directly refer to implicit savepoints in rollback statements.See Also:
"Deadlocks"Oracle provides a means for suspending, and later resuming, the execution of large database operations in the event of space allocation failures. This enables an administrator to take corrective action, instead of the Oracle database server returning an error to the user. After the error condition is corrected, the suspended operation automatically resumes.
A statement runs in a resumable mode only when the client explicitly enables resumable semantics for the session using the ALTER
SESSION
statement.
Resumable space allocation is suspended when one of the following conditions occur:
Out of space condition
Maximum extents reached condition
Space quota exceeded condition
For nonresumable space allocation, these conditions result in errors and the statement is rolled back.
Suspending a statement automatically results in suspending the transaction. Thus all transactional resources are held through a statement suspend and resume.
When the error condition disappears (for example, as a result of user intervention or perhaps sort space released by other queries), the suspended statement automatically resumes execution.
See Also:
Oracle Database Administrator's Guide for information about enabling resumable space allocation, what conditions are correctable, and what statements can be made resumable.A transaction in Oracle begins when the first executable SQL statement is encountered. An executable SQL statement is a SQL statement that generates calls to an instance, including DML and DDL statements.
When a transaction begins, Oracle assigns the transaction to an available undo tablespace to record the rollback entries for the new transaction.
A transaction ends when any of the following occurs:
A user issues a COMMIT
or ROLLBACK
statement without a SAVEPOINT
clause.
A user runs a DDL statement such as CREATE
, DROP
, RENAME
, or ALTER
. If the current transaction contains any DML statements, Oracle first commits the transaction, and then runs and commits the DDL statement as a new, single statement transaction.
A user disconnects from Oracle. The current transaction is committed.
A user process terminates abnormally. The current transaction is rolled back.
After one transaction ends, the next executable SQL statement automatically starts the following transaction.
Committing a transaction means making permanent the changes performed by the SQL statements within the transaction.
Before a transaction that modifies data is committed, the following has occurred:
Oracle has generated undo information. The undo information contains the old data values changed by the SQL statements of the transaction.
Oracle has generated redo log entries in the redo log buffer of the SGA. The redo log record contains the change to the data block and the change to the rollback block. These changes may go to disk before a transaction is committed.
The changes have been made to the database buffers of the SGA. These changes may go to disk before a transaction is committed.
Note:
The data changes for a committed transaction, stored in the database buffers of the SGA, are not necessarily written immediately to the datafiles by the database writer (DBWn) background process. This writing takes place when it is most efficient for the database to do so. It can happen before the transaction commits or, alternatively, it can happen some time after the transaction commits.When a transaction is committed, the following occurs:
The internal transaction table for the associated undo tablespace records that the transaction has committed, and the corresponding unique system change number (SCN) of the transaction is assigned and recorded in the table.
The log writer process (LGWR) writes redo log entries in the SGA's redo log buffers to the redo log file. It also writes the transaction's SCN to the redo log file. This atomic event constitutes the commit of the transaction.
Oracle marks the transaction complete.
Note:
The default behavior is for LGWR to write redo to the online redo log files synchronously and for transactions to wait for the redo to go to disk before returning a commit to the user. However, for lower transaction commit latency application developers can specify that redo be written asynchronously and that transactions do not need to wait for the redo to be on disk.See Also:
Oracle Database Application Developer's Guide - Fundamentals for more information on asynchronous commit
"Overview of Oracle Processes" for more information about the background processes LGWR and DBWn
Rolling back means undoing any changes to data that have been performed by SQL statements within an uncommitted transaction. Oracle uses undo tablespaces (or rollback segments) to store old values. The redo log contains a record of changes.
Oracle lets you roll back an entire uncommitted transaction. Alternatively, you can roll back the trailing portion of an uncommitted transaction to a marker called a savepoint.
All types of rollbacks use the same procedures:
Statement-level rollback (due to statement or deadlock execution error)
Rollback to a savepoint
Rollback of a transaction due to user request
Rollback of a transaction due to abnormal process termination
Rollback of all outstanding transactions when an instance terminates abnormally
Rollback of incomplete transactions during recovery
In rolling back an entire transaction, without referencing any savepoints, the following occurs:
Oracle undoes all changes made by all the SQL statements in the transaction by using the corresponding undo tablespace.
Oracle releases all the transaction's locks of data.
The transaction ends.
See Also:
Oracle Database Backup and Recovery Basics for information about what happens to committed and uncommitted changes during recovery
You can declare intermediate markers called savepoints within the context of a transaction. Savepoints divide a long transaction into smaller parts.
Using savepoints, you can arbitrarily mark your work at any point within a long transaction. You then have the option later of rolling back work performed before the current point in the transaction but after a declared savepoint within the transaction. For example, you can use savepoints throughout a long complex series of updates, so if you make an error, you do not need to resubmit every statement.
Savepoints are similarly useful in application programs. If a procedure contains several functions, then you can create a savepoint before each function begins. Then, if a function fails, it is easy to return the data to its state before the function began and re-run the function with revised parameters or perform a recovery action.
After a rollback to a savepoint, Oracle releases the data locks obtained by rolled back statements. Other transactions that were waiting for the previously locked resources can proceed. Other transactions that want to update previously locked rows can do so.
When a transaction is rolled back to a savepoint, the following occurs:
Oracle rolls back only the statements run after the savepoint.
Oracle preserves the specified savepoint, but all savepoints that were established after the specified one are lost.
Oracle releases all table and row locks acquired since that savepoint but retains all data locks acquired previous to the savepoint.
The transaction remains active and can be continued.
Whenever a session is waiting on a transaction, a rollback to savepoint does not free row locks. To make sure a transaction does not hang if it cannot obtain a lock, use FOR
UPDATE
... NOWAIT
before issuing UPDATE
or DELETE
statements. (This refers to locks obtained before the savepoint to which has been rolled back. Row locks obtained after this savepoint are released, as the statements executed after the savepoint have been rolled back completely.)
You can name a transaction, using a simple and memorable text string. This name is a reminder of what the transaction is about. Transaction names replace commit comments for distributed transactions, with the following advantages:
It is easier to monitor long-running transactions and to resolve in-doubt distributed transactions.
You can view transaction names along with transaction IDs in applications. For example, a database administrator can view transaction names in Enterprise Manager when monitoring system activity.
Transaction names are written to the transaction auditing redo record, if compatibility is set to Oracle9i or higher.
LogMiner can use transaction names to search for a specific transaction from transaction auditing records in the redo log.
You can use transaction names to find a specific transaction in data dictionary views, such as V$TRANSACTION
.
Name a transaction using the SET
TRANSACTION
... NAME
statement before you start the transaction.
When you name a transaction, you associate the transaction's name with its ID. Transaction names do not have to be unique; different transactions can have the same transaction name at the same time by the same owner. You can use any name that enables you to distinguish the transaction.
In previous releases, you could associate a comment with a transaction by using a commit comment. However, a comment can be associated with a transaction only when a transaction is being committed.
Commit comments are still supported for backward compatibility. However, Oracle strongly recommends that you use transaction names. Commit comments are ignored in named transactions.
Note:
In a future release, commit comments will be deprecated.
See Also:
Oracle Database Administrator's Guide for more information about distributed transactions
Oracle Database SQL Reference for more information about transaction naming syntax
In a distributed database, Oracle must coordinate transaction control over a network and maintain data consistency, even if a network or system failure occurs.
A 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 that all database servers participating in a distributed transaction either all commit or all undo the statements in the transaction. A two-phase commit mechanism also protects implicit DML operations performed by integrity constraints, remote procedure calls, and triggers.
The Oracle two-phase commit mechanism is completely transparent to users who issue distributed transactions. In fact, users need not even know the transaction is distributed. A COMMIT
statement denoting the end of a transaction automatically triggers the two-phase commit mechanism to commit the transaction. No coding or complex statement syntax is required to include distributed transactions within the body of a database application.
The recoverer (RECO
) background process automatically resolves the outcome of in-doubt distributed transactions—distributed transactions in which the commit was interrupted by any type of system or network failure. After the failure is repaired and communication is reestablished, the RECO
process of each local Oracle database automatically commits or rolls back any in-doubt distributed transactions consistently on all involved nodes.
In the event of a long-term failure, Oracle allows each local administrator to manually commit or undo any distributed transactions that are in doubt as a result of the failure. This option enables the local database administrator to free any locked resources that are held indefinitely as a result of the long-term failure.
If a database must be recovered to a point in the past, Oracle's recovery facilities enable database administrators at other sites to return their databases to the earlier point in time also. This operation ensures that the global database remains consistent.
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, perform some SQL operations, commit or undo those operations, and then return to the calling transaction's context and continue with that transaction.
Once invoked, an autonomous transaction is totally independent of the main transaction that called it. It does not see any of the uncommitted changes made by the main transaction and does not share any locks or resources with the main transaction. Changes made by an autonomous transaction become visible to other transactions upon commit of the autonomous transactions.
One autonomous transaction can call another. There are no limits, other than resource limits, on how many levels of autonomous transactions can be called.
Deadlocks are possible between an autonomous transaction and its calling transaction. Oracle detects such deadlocks and returns an error. The application developer is responsible for avoiding deadlock situations.
Autonomous transactions are useful for implementing actions that need to be performed independently, regardless of whether the calling transaction commits or rolls back, such as transaction logging and retry counters.
You can call autonomous transactions from within a PL/SQL block. Use the pragma AUTONOMOUS_TRANSACTION
. A pragma is a compiler directive. You can declare the following kinds of PL/SQL blocks to be autonomous:
Stored procedure or function
Local procedure or function
Package
Type method
Top-level anonymous block
When an autonomous PL/SQL block is entered, the transaction context of the caller is suspended. This operation ensures that SQL operations performed in this block (or other blocks called from it) have no dependence or effect on the state of the caller's transaction context.
When an autonomous block invokes another autonomous block or itself, the called block does not share any transaction context with the calling block. However, when an autonomous block invokes a non-autonomous block (that is, one that is not declared to be autonomous), the called block inherits the transaction context of the calling autonomous block.
Transaction control statements in an autonomous PL/SQL block apply only to the currently active autonomous transaction. Examples of such statements are:
SET TRANSACTION COMMIT ROLLBACK SAVEPOINT ROLLBACK TO SAVEPOINT
Similarly, transaction control statements in the main transaction apply only to that transaction and not to any autonomous transaction that it calls. For example, rolling back the main transaction to a savepoint taken before the beginning of an autonomous transaction does not undo the autonomous transaction.