Sunday, April 28, 2013

Oracle 11g Flashback


This article is about usage of Flashback Technology in Oracle database 11g.

Topics:
· Overview of Oracle Flashback Technology
· Configuring Your Database for Oracle Flashback Technology
· Using Oracle Flashback Query (SELECT AS OF)
· Using Oracle Flashback Version Query
· Using Oracle Flashback Transaction Query
· Using Oracle Flashback Transaction Query with Oracle Flashback Version Query
· Using DBMS_FLASHBACK Package
· Using Flashback Transaction
· Using Flashback Data Archive (Oracle Total Recall.
· General Guidelines for Oracle Flashback Technology
· Performance Guidelines for Oracle Flashback Technology

Overview of Oracle Flashback Technology
A group of Oracle Database features that allow to query past states of database objects or to return database objects to a previous state without applying point-in-time media recovery.
With flashback features, you can:
· Perform queries that return past dat
· Perform queries that return metadata that shows a detailed history of changes to the database
· Recover tables or rows to a previous point in time
· Automatically track and archive transactional data changes
· Roll back a transaction and its dependent transactions while the database remains online

Oracle Flashback features uses the Automatic Undo Management (AUM) system to obtain metadata and istorical data for transactions. They rely on undo data, which are records of the effects of individual transactions. For example, if a user runs an UPDATE statement to change a salary from 1000 to 1100, then Oracle Database stores the value 1000 in the undo data.

Undo data is persistent and survives a database shutdown. By using flashback features, you can use undo data to query past data or recover from logical damage. Besides using it in flashback features, Oracle Database uses undo data to perform these actions:
· Roll back active transactions
· Recover terminated transactions by using database or process recovery
· Provide read consistency for SQL queries

Oracle Flashback Query
Use this feature to retrieve data for an earlier time that you specify with the AS OF clause of the SELECT statement.

Oracle Flashback Version Query
Use this feature to retrieve metadata and historical data for a specific time interval (for example, to view all the rows of a table that ever existed during a given time interval). Metadata for each row version includes start and end time, type of change operation, and identity of the transaction that created the row version. To create an Oracle Flashback Version Query, use the VERSIONS BETWEEN clause of the SELECT statement.

Oracle Flashback Transaction Query
Use this feature to retrieve metadata and historical data for a given transaction or for all transactions in a given time interval. To perform an Oracle Flashback Transaction Query, select from the static data dictionary view FLASHBACK_TRANSACTION_QUERY.

DBMS_FLASHBACK Package
Use this feature to set the internal Oracle Database clock to an earlier time so that you can examine data that was current at that time, or to roll back a transaction and its dependent transactions while the database remains online.

Flashback Transaction
Use Flashback Transaction to roll back a transaction and its dependent transactions while the database remains online. This recovery operation uses undo data to create and run the corresponding compensating transactions that return the affected data to its original state.

Flashback Data Archive (Oracle Total Recall)
Use Flashback Data Archive to automatically track and archive both regular queries and Oracle Flashback Query, ensuring SQL-level access to the versions of database objects without getting a snapshot-too-old error.

Database Administration Features
These flashback features are primarily for data recovery. Typically, you use these features only as a database administrator.

Oracle Flashback Table
Use this feature to restore a table to its state at a previous point in time. You can restore a table while the database is on line, undoing changes to only the specified table.

Oracle Flashback Drop
Use this feature to recover a dropped table. This feature reverses the effects of aDROP TABLE statement.

Oracle Flashback Database
Use this feature to quickly return the database to an earlier point in time, by undoing all of the changes that have taken place since then. This is fast, because you do not have to restore database backups.

Configuring Your Database for Oracle Flashback Technology
Before you can use flashback features in your application, you or your database administrator must perform the configuration tasks described in these topics:
· Configuring Your Database for Automatic Undo Managemen.
· Configuring Your Database for Oracle Flashback Transaction Query
· Configuring Your Database for Flashback Transaction
· Enabling Oracle Flashback Operations on Specific LOB Columns
· Granting Necessary Privileges.

Configuring Your Database for Automatic Undo Management
To configure your database for Automatic Undo Management (AUM), you or your database administrator must:
· Create an undo tablespace with enough space to keep the required data for flashback operations.
The more often users update the data, the more space is required. The database administrator usually calculates the space requirement.
· To enable AUM, Set these database initialization parameters:
o UNDO_MANAGEMENT=AUTO
o UNDO_TABLESPACE=UNDOTBS1
o UNDO_RETENTION=1440
For a fixed-size undo tablespace, Oracle Database automatically tunes the system to give the undo tablespace the best possible undo retention.

For an automatically extensible undo tablespace, Oracle Database retains undo data longer than the longest query duration and the low threshold of undo retention specified by the UNDO_RETENTION parameter.
· Specify the RETENTION GUARANTEE clause for the undo tablespace to ensure that unexpired undo data is not discarded.

Configuring Your Database for Oracle Flashback Transaction Query
To configure your database for the Oracle Flashback Transaction Query feature, you or your database administrator must:
· Ensure that Oracle Database is running with version 10.0 compatibility.
· Enable supplemental logging:
· ALTER DATABASE ADD SUPPLEMENTAL LOG DATA;

Configuring Your Database for Flashback Transaction
To configure your database for the Flashback Transaction feature, you or your database administrator must:
· With the database mounted but not open, enable ARCHIVELOG
· ALTER DATABASE ARCHIVELOG
· Open at least one archive log:
· ALTER SYSTEM ARCHIVE LOG CURRENT;
· If not done, enable minimal and primary key supplemental logging:
· ALTER DATABASE ADD SUPPLEMENTAL LOG DATA;
· ALTER DATABASE ADD SUPPLEMENTAL LOG DATA (PRIMARY KEY) COLUMNS;
· If you want to track foreign key dependencies, enable foreign key supplemental logging:
· ALTER DATABASE ADD SUPPLEMENTAL LOG DATA (FOREIGN KEY) COLUMNS;

Enabling Oracle Flashback Operations on Specific LOB Columns
To enable flashback operations on specific LOB columns of a table, use the ALTER TABLE statement with the RETENTION option.
Because undo data for LOB columns can be voluminous, you must define which LOB columns to use with flashback operations.

Granting Necessary Privileges
You or your database administrator must grant privileges to users, roles, or applications that must use these flashback features.

For Oracle Flashback Query and Oracle Flashback Version Query
To allow access to specific objects during queries, grant FLASHBACK and SELECT privileges on those objects.
To allow queries on all tables, grant the FLASHBACK ANY TABLE privilege.

For Oracle Flashback Transaction Query

Grant the SELECT ANY TRANSACTION privilege.
To allow execution of undo SQL code retrieved by an Oracle Flashback Transaction Query, grant SELECT, UPDATE, DELETE, and INSERT privileges for specific tables.

For DBMS_FLASHBACK Package
To allow access to the features in the DBMS_FLASHBACK package, grant the EXECUTE privilege on DBMS_FLASHBACK.

For Flashback Data Archive (Oracle Total Recall)
To allow a specific user to enable Flashback Data Archive on tables, using a specific Flashback Data Archive, grant the FLASHBACK ARCHIVE object privilege on that Flashback Data Archive to that user. To grant the FLASHBACK ARCHIVE object privilege, you must either be logged on as SYSDBA or have FLASHBACK ARCHIVE ADMINISTER system privilege.

To allow execution of these statements, grant the FLASHBACK ARCHIVE ADMINISTER system privilege:
· CREATE FLASHBACK ARCHIVE
· ALTER FLASHBACK ARCHIVE
· DROP FLASHBACK ARCHIVE
To grant the FLASHBACK ARCHIVE ADMINISTER system privilege, you must be logged on as SYSDBA.

To create a default Flashback Data Archive, using either the CREATE FLASHBACK ARCHIVE or ALTER FLASHBACK ARCHIVE statement, you must be logged on as SYSDBA

To disable Flashback Data Archive for a table that has been enabled for Flashback Data Archive, you must either be logged on as SYSDBA or have the FLASHBACK ARCHIVE ADMINISTER system privilege.
Using Oracle Flashback Query (SELECT AS OF)
To use Oracle Flashback Query, use a SELECT statement with an AS OF clause. Oracle Flashback Query retrieves data as it existed at an earlier time. The query explicitly references a past time through a time stamp or System Change Number (SCN). It returns committed data that was current at that point in time.

Uses of Oracle Flashback Query include:
· Recovering lost data or undoing incorrect, committed changes.
For example, if you mistakenly delete or update rows, and then commit them, you can immediately undo the mistake.
· Comparing current data with the corresponding data at an earlier time.
· Checking the state of transactional data at a particular time.

For example, you can verify the account balance of a certain day.
· Simplifying application design by removing the need to store some kinds of temporal data.

Oracle Flashback Query lets you retrieve past data directly from the database.
· Applying packaged applications, such as report generation tools, to past data.
· Providing self-service error correction for an application, thereby enabling users to undo and correct their errors.

With a CREATE TABLE AS SELECT or INSERT INTO TABLE SELECT statement. For example, this query reinserts into table employees the rows that existed an hour ago:

INSERT INTO employees
(SELECT * FROM employees
AS OF TIMESTAMP (SYSTIMESTAMP - INTERVAL '60' MINUTE)
MINUS SELECT * FROM employees);
SYSTIMESTAMP refers to the time zone of the database host environment.

Using Oracle Flashback Version Query
Use Oracle Flashback Version Query to retrieve the different versions of specific rows that existed during a given time interval. A row version is created whenever a COMMIT statement is executed.
Specify Oracle Flashback Version Query using the VERSIONS BETWEEN clause of the SELECT statement. The syntax is:
VERSIONS {BETWEEN {SCN | TIMESTAMP} start AND end}

Oracle Flashback Version Query returns a table with a row for each version of the row that existed at any time during the specified time interval. Each row in the table includes pseudocolumns of metadata about the row version. This information can reveal when and how a particular change (perhaps erroneous) occurred to your database.
A typical use of Oracle Flashback Version Query:
SELECT versions_startscn, versions_starttime,
versions_endscn, versions_endtime,
versions_xid, versions_operation,
last_name, salary
FROM employees
VERSIONS BETWEEN TIMESTAMP
TO_TIMESTAMP('2008-12-18 14:00:00', 'YYYY-MM-DD HH24:MI:SS')
AND TO_TIMESTAMP('2008-12-18 17:00:00', 'YYYY-MM-DD HH24:MI:SS')
WHERE first_name = 'John';

You can use VERSIONS_XID with Oracle Flashback Transaction Query to locate this transaction's metadata, including the SQL required to undo the row change and the user responsible for the change.
Using Oracle Flashback Transaction Query
Use Oracle Flashback Transaction Query to retrieve metadata and historical data for a given transaction or for all transactions in a given time interval. it queries the static data dictionary view FLASHBACK_TRANSACTION_QUERY,

The column UNDO_SQL shows the SQL code that is the logical opposite of the DML operation performed by the transaction, there are cases where the SQL_UNDO code is not the exact opposite of the original transaction. For example, a SQL_UNDO INSERT operation might not insert a row back in a table at the same ROWID from which it was deleted.
This statement uses Oracle Flashback Version Query as a subquery to associate each row version with the LOGON_USER responsible for the row data change:
SELECT xid, logon_user
FROM flashback_transaction_query
WHERE xid IN (
SELECT versions_xid FROM employees VERSIONS BETWEEN TIMESTAMP
TO_TIMESTAMP('2003-07-18 14:00:00', 'YYYY-MM-DD HH24:MI:SS') AND
TO_TIMESTAMP('2003-07-18 17:00:00', 'YYYY-MM-DD HH24:MI:SS')
);
Using Oracle Flashback Transaction Query with Oracle Flashback Version Query

In this example, a database administrator does this:
DROP TABLE emp;
CREATE TABLE emp (
empno NUMBER PRIMARY KEY,
empname VARCHAR2(16),
salary NUMBER
);
INSERT INTO emp (empno, empname, salary) VALUES (111, 'Mike', 555);
COMMIT;
DROP TABLE dept;
CREATE TABLE dept (
deptno NUMBER,
deptname VARCHAR2(32)
);
INSERT INTO dept (deptno, deptname) VALUES (10, 'Accounting');
COMMIT;
Nowemp and dept have one row each. In terms of row versions, each table has one version of one row. Suppose that an erroneous transaction deletes empno 111 from table emp:

UPDATE emp SET salary = salary + 100 WHERE empno = 111;
INSERT INTO dept (deptno, deptname) VALUES (20, 'Finance');
DELETE FROM emp WHERE empno = 111;
COMMIT;

Next, a transaction reinserts empno 111 into the emp table with a new employee name:
INSERT INTO emp (empno, empname, salary) VALUES (111, 'Tom', 777);
UPDATE emp SET salary = salary + 100 WHERE empno = 111;
UPDATE emp SET salary = salary + 50 WHERE empno = 111;
COMMIT;

SELECT versions_xid XID, versions_startscn START_SCN,
versions_endscn END_SCN, versions_operation OPERATION,
empname, salary
FROM emp
VERSIONS BETWEEN SCN MINVALUE AND MAXVALUE
WHERE empno = 111;
Results are similar to:
XID START_SCN END_SCN O EMPNAME SALARY
---------------- ---------- ---------- - ---------------- ----------
09001100B2200000 10093466 I Tom 927
The database administrator identifies transaction 030002002B210000 as the erroneous transaction and uses Oracle Flashback Transaction Query to audit all changes made by this transaction:

SELECT xid, start_scn, commit_scn, operation, logon_user, undo_sql
FROM flashback_transaction_query
WHERE xid = HEXTORAW('000200030000002D');
Results are similar to:
XID START_SCN COMMIT_SCN OPERATION LOGON_USER
---------------- ---------- ---------- --------- ----------------------------
UNDO_SQL
--------------------------------------------------------------------------------
030002002B210000 10093452 10093459 DELETE HR
insert into "HR"."EMP"("EMPNO","EMPNAME","SALARY") values ('111','Mike','655');
030002002B210000 10093452 10093459 INSERT HR
delete from "HR"."DEPT" where ROWID = 'AAATjuAAEAAAAJrAAB';
030002002B210000 10093452 10093459 UPDATE HR
update "HR"."EMP" set "SALARY" = '555' where ROWID = 'AAATjsAAEAAAAJ7AAA';
030002002B210000 10093452 10093459 BEGIN HR

To make the result of the next query easier to read, the database administrator uses these SQL*Plus commands:
COLUMN operation FORMAT A9
COLUMN table_name FORMAT A10
COLUMN table_owner FORMAT A11
To see the details of the erroneous transaction and all subsequent transactions, the database administrator performs this query:
SELECT xid, start_scn, commit_scn, operation, table_name, table_owner
FROM flashback_transaction_query
WHERE table_owner = 'HR'
AND start_timestamp >=
TO_TIMESTAMP ('2002-04-16 11:00:00','YYYY-MM-DD HH:MI:SS');
Results are similar to:
XID START_SCN COMMIT_SCN OPERATION TABLE_NAME TABLE_OWNER
---------------- ---------- ---------- --------- ---------- -----------
02000E0074200000 10093435 10093446 INSERT DEPT HR
030002002B210000 10093452 10093459 DELETE EMP HR

Using DBMS_FLASHBACK Package
The DBMS_FLASHBACK package provides the same functionality as Oracle Flashback Query, but Oracle Flashback Query is sometimes more convenient.
You must have the EXECUTE privilege on the DBMS_FLASHBACK package.
To use the DBMS_FLASHBACK package in your PL/SQL code:
1. Specify a past time by invoking either DBMS_FLASHBACK.ENABLE_AT_TIME or DBMS_FLASHBACK.ENABLE_AT_SYSTEM_CHANGE_NUMBER.
2. Perform regular queries (that is, queries without special flashback-feature syntax such as AS OF). Do not perform DDL or DML operations.
The database is queried at the specified past time.
3. Return to the present by invoking DBMS_FLASHBACK.DISABLE.
You must invoke DBMS_FLASHBACK.DISABLE before invoking DBMS_FLASHBACK.ENABLE_AT_TIME or DBMS_FLASHBACK.ENABLE_AT_SYSTEM_CHANGE_NUMBER again. You cannot nest enable/disable pairs.
To use a cursor to store the results of queries, open the cursor before invoking DBMS_FLASHBACK.DISABLE. After storing the results and invoking DBMS_FLASHBACK.DISABLE, you can:
· Perform INSERT or UPDATE operations to modify the current database state by using the stored results from the past.
· Compare current data with the past data. After invoking DBMS_FLASHBACK.DISABLE, open a second cursor. Fetch from the first cursor to retrieve past data; fetch from the second cursor to retrieve current data. You can store the past data in a temporary table and then use set operators such as MINUS or UNION to contrast or combine the past and current data.

Using Flashback Transaction
The DBMS_FLASHBACK.TRANSACTION_BACKOUT procedure rolls back a transaction and its dependent transactions while the database remains online. This recovery operation uses undo data to create and run the compensating transactions that return the affected data to its original state.
The transactions being rolled back are subject to these restrictions:
· They cannot have performed DDL operations that changed the logical structure of database tables.
· They cannot use Large Object (LOB) Data Types,
o BFILE
o BLOB
o CLOB
o NCLOB
· They cannot use features that LogMiner does not support.