32
Flashback: A quick view on recycle bin concept:...................... 1 Flashback Basics:......................................... 3 Choosing a Location for the Flash Recovery Area...... 4 Flash Recovery Area, ASM and OMF..................... 4 Files That Can Be Stored in the Flash Recovery Area..5 Planning the Size of the Flash Recovery Area......... 5 Enabling Flashback Database.......................... 6 Disabling Flashback Database......................... 7 Flashback Features:....................................... 7 (1) Flashback Table................................. 7 Undo Retention............................. 8 Flashback Table Privileges................. 8 Examples:..................................8 (2) Flashback row history........................... 9 (3) Flashback transaction.......................... 10 (4) Flashback database............................. 11 (5) Flashback standby database..................... 12 (6) Flashback reinstantiation...................... 13 (7) Flashback Drop:................................ 14 Exploring Flashback With More Examples:.................. 16 Example 1:.......................................... 16 Example 2:.......................................... 18 Example 3:.......................................... 18 Example 4:.......................................... 20 A quick view on recycle bin concept: First, a quick review of the basics -> There are two recyclebin views: USER_RECYCLEBIN and DBA_RECYCLEBIN. For convenience, the synonym RECYCLEBIN points to your USER_RECYCLEBIN. The recyclebin is enabled by default in 10g, but you can turn it on or off with the RECYCLEBIN initialization parameter, at the system or session level. When the recyclebin is enabled, any tables that you drop do not actually get deleted. Instead, when you drop a table, Oracle just renames the table and all its associated objects (indexes, triggers, LOB segments, etc) to a system-generated name that begins with BIN$. TCS Internal

Flashback All

Embed Size (px)

Citation preview

Page 1: Flashback All

Flashback:

A quick view on recycle bin concept:.......................................................................1Flashback Basics:..........................................................................................................3

Choosing a Location for the Flash Recovery Area....................................4Flash Recovery Area, ASM and OMF............................................................4Files That Can Be Stored in the Flash Recovery Area..............................5Planning the Size of the Flash Recovery Area............................................5Enabling Flashback Database.........................................................................6Disabling Flashback Database........................................................................7

Flashback Features:.......................................................................................................7(1) Flashback Table......................................................................................7

Undo Retention............................................................................8Flashback Table Privileges......................................................8Examples:.....................................................................................8

(2) Flashback row history...........................................................................9(3) Flashback transaction.........................................................................10(4) Flashback database.............................................................................11(5) Flashback standby database.............................................................12(6) Flashback reinstantiation...................................................................13(7) Flashback Drop:....................................................................................14

Exploring Flashback With More Examples:...........................................................16Example 1:..........................................................................................................16Example 2:..........................................................................................................18Example 3:..........................................................................................................18Example 4:..........................................................................................................20

A quick view on recycle bin concept:

First, a quick review of the basics -> There are two recyclebin views: USER_RECYCLEBIN and DBA_RECYCLEBIN. For convenience, the synonym RECYCLEBIN points to your USER_RECYCLEBIN. The recyclebin is enabled by default in 10g, but you can turn it on or off with the RECYCLEBIN initialization parameter, at the system or session level.

When the recyclebin is enabled, any tables that you drop do not actually get deleted. Instead, when you drop a table, Oracle just renames the table and all its associated objects (indexes, triggers, LOB segments, etc) to a system-generated name that begins with BIN$.

For example, consider this simple table:

SQL> create table tst (col varchar2(10), row_chng_dt date);

Table created.

SQL> insert into tst values ('Version1', sysdate);

1 row created.

SQL> select * from tst;

TCS Internal

Page 2: Flashback All

COL ROW_CHNG---------- --------Version1 16:10:03

If the RECYCLEBIN initialization parameter is set to ON (the default in 10g), then dropping this table will place it in the recyclebin:

SQL> drop table tst;

Table dropped.

SQL> select object_name, original_name, type, can_undrop as "UND", can_purge as "PUR", droptime from recyclebin;

OBJECT_NAME ORIGINAL_NAME TYPE UND PUR DROPTIME------------------------------ ------------- ----- --- --- -------------------BIN$HGnc55/7rRPgQPeM/qQoRw==$0 TST TABLE YES YES 2006-09-01:16:10:12

All that happened to the table when we dropped it was that it got renamed. The table data is still there and can be queried just like a normal table:

SQL> alter session set nls_date_format='HH24:MI:SS' ;

Session altered.

SQL> select * from "BIN$HGnc55/7rRPgQPeM/qQoRw==$0";

COL ROW_CHNG---------- --------Version1 16:10:03

Since the table data is still there, it's very easy to "undrop" the table. This operation is known as a "flashback drop". The command is FLASHBACK TABLE... TO BEFORE DROP, and it simply renames the BIN$... table to its original name:

SQL> flashback table tst to before drop;

Flashback complete.

SQL> select * from tst ;

COL ROW_CHNG---------- --------Version1 16:10:03

SQL> select * from recyclebin ;

no rows selected

It's important to know that after you've dropped a table, it has only been renamed; the table segments are still sitting there in your tablespace, unchanged, taking up space. This space still counts against your user tablespace quotas, as well as filling up the tablespace. It will not be reclaimed until you get the table out of the recyclebin. You can remove an object from the recyclebin by restoring it, or by purging it from the recyclebin.

TCS Internal

Page 3: Flashback All

SQL> select object_name, original_name, type, can_undrop as "UND", can_purge as "PUR", droptime from recyclebin;

OBJECT_NAME ORIGINAL_NAME TYPE UND PUR DROPTIME------------------------------ ------------- ----- --- --- -------------------BIN$HGnc55/7rRPgQPeM/qQoRw==$0 TST TABLE YES YES 2006-09-01:16:10:12

SQL> purge table "BIN$HGnc55/7rRPgQPeM/qQoRw==$0";

Table purged.

SQL> select * from recyclebin ;

no rows selected

You have several purge options. You can also purge everything from the USER_RECYCLEBIN using PURGE RECYCLEBIN; a user with DBA privileges can purge everything from all recyclebins using DBA_RECYCLEBIN; and finally, you can purge recyclebin objects by schema and user with PURGE TABLESPACE USER.

Unless you purge them, Oracle will leave objects in the recyclebin until the tablespace runs out of space, or until you hit your user quota on the tablespace. At that point, Oracle purges the objects one at a time, starting with the ones dropped the longest time ago, until there is enough space for the current operation. If the tablespace data files are AUTOEXTEND ON, Oracle will purge recyclebin objects before it autoextends a datafile.

i.e. to summarize:

A recycle bin contains all the dropped database objects until,

- You permanently drop them with the PURGE command.- Recover the dropped objects with the UNDROP command.- There is no room in the tablespace for new rows or updates to existing rows.- The tablespace needs to be extended.

Note: Objects kept in SYSTEM tablespace shall not be renamed

Reference:

http://www.orafaq.com/node/31 http://www.orafaq.com/node/968

Flashback Basics:

Intro: The Flash Recovery Area feature lets you set up a location on disk where the database can create and manage a variety of backup and recovery-related files on your behalf.

Using a flash recovery area simplifies the ongoing administration of your database by automatically naming recovery-related files, retaining them as long as they are needed for restore and recovery activities, and deleting them when they are no longer needed to restore your database and space is needed for some other backup and recovery-related purpose.

TCS Internal

Page 4: Flashback All

Your long-term backup and recovery administration can be greatly simplified by using a flash recovery area. Use of the flash recovery area is strongly recommended. You may want to set up a flash recovery area as one of the first steps in implementing your backup strategy.

How does is work – the engineering behind it!!

Ok, in order for flashback database to work you need to configure a flash recovery area.

In this space, Oracle will store a couple of things

a) pre-checkpoint images of blocks (on a rotating basis, not EVERY pre-checkpoint image needs to go here)

b) archived redo

To understand the process, let's pretend it is 12:00 noon and we wish to flashback the database to 9am that morning (three hours ago). Now, if you were to look at the datafiles on disk as of 12:00 - you would find database blocks that

a) haven't been touched since 9am - the image ON DISK in the datafile predates 9am this morning.

b) have been modified and checkpointed - the image ON DISK in the datafile is older than 9am - the blocks are "as of" some time between 9am and noon

Now, the blocks in A) are "ok" of course - we need do nothing special with them yet. The blocks in B) however are problematic, we need to put them back to a point in time prior to 9am this morning. For this, we find the "newest" pre-checkpoint image of that block in the flash recovery area that is older than 9am (eg: presume there could be an 8am, 8:30am, 9:01am, 9:30am and so on copy of that block in the flash recovery area - we would go for the 8:30am version). We replace the image of the block in the datafile with that version (the 8:30am version). We do that for all of the blocks that were checkpointed to disk AFTER 9am that morning.

Now, we take the archives from the flash recovery area and catch all of them up - apply the redo - to 9am - any block that was modified prior to 9am and needed to have the redo applied to catch it up - will have that done.

Now - we do an "open database reset logs" and normal instance recovery takes place...

that is it in a nutshell - we find old images of the blocks that pre-date the flashback time, we put them in place, we roll them forward as far as we need to with archived redo and open reset logs. Just like a full database restore - and point in time recovery would have done, but without the full database restore.

Imp Note: The logical-level flashback features of Oracle are not dependent upon RMAN, and are available whether or not RMAN is part of your backup strategy.

Choosing a Location for the Flash Recovery Area

When setting up a flash recovery area, you must choose a location (a directory or Automatic Storage Management disk group) to hold the files. The flash recovery area cannot be stored on a raw file system.

TCS Internal

Page 5: Flashback All

You must also determine a disk quota for the flash recovery area, the maximum space to be used for all files stored there. You must choose a location large enough to accommodate the required disk quota. When the disk space limit is approached, Oracle can delete nonessential files to make room for new files, subject to the limitations of the retention policy.

The flash recovery area should be on a separate disk from the database area, where active database files such as data files, control files, and online redo logs are stored. Keeping the flash recovery area on the same disk as the database area exposes you to loss of both your live database files and backups in the event of a media failure.

Note:

There are special considerations for choosing a location for the flash recovery area in a RAC environment. The location must be on a cluster file system, ASM or a shared directory configured through NFS. The location and disk quota must be the same on all instances.

Flash Recovery Area, ASM and OMF

The flash recovery area is closely related to and can be used in conjunction with two other Oracle features: Oracle Managed Files and Automatic Storage Management.

Oracle Managed Files (OMF) is a service that automates naming, location, creation and deletion of database files such as control files, redo log files, datafiles and others, based on a few initialization parameters. It can simplify many aspects of the DBA's work by eliminating the need to devise your own policies for such details.

The flash recovery area is built on top of OMF, so the flash recovery area can be stored anywhere Oracle-managed files can. Oracle Managed Files can be used on top of a traditional file system supported by the host operating system (for example, VxFS etc).

The flash recovery area can also be used with Oracle's Automatic Storage Management (ASM). ASM consolidates storage devices into easily managed disk groups and provides benefits such as mirroring and striping without requiring a third-party logical volume manager.

Even if you choose not to set up the flash recovery area in ASM storage, you can still use Oracle Managed Files to manage your backup files in an ASM disk group. You will lose one of the major benefits of the flash recovery area, the automatic deletion of files no longer needed to meet your recoverability goals as space is needed for more recent backups. However, the other automatic features of OMF will still function.

Note:

When storing backup files, using OMF on top of Automatic Storage Management without using a flash recovery area is supported but discouraged. It is awkward to directly manipulate files under Automatic Storage Management.

Files That Can Be Stored in the Flash Recovery Area

The files in the flash recovery area can be classified as permanent or transient. The only permanent files (assuming these are configured to be stored in the flash recovery area) are multiplexed copies of the current control file and online redo logs. These cannot be deleted without causing the instance to fail. All other files are transient, because Oracle will generally eventually delete these files, at some point after they become obsolete under the retention policy

TCS Internal

Page 6: Flashback All

or have been backed up to tape. Transient files include archived redo logs, datafile copies, control file copies, control file autobackups, and backup pieces.

Note:

The Oracle Flashback Database feature, which provides an convenient alternative to point-in-time recovery, generates flashback logs, which are also considered transient files and must be stored in the flash recovery area. However, unlike other transient files, flashback logs cannot be backed up to other media. They are automatically deleted as space is needed for other files in the flash recovery area.

Planning the Size of the Flash Recovery Area

The larger the flash recovery area is, the more useful it becomes. Ideally, the flash recovery area should be large enough to contain all of the following files:

A copy of all datafiles

Incremental backups, as used by your chosen backup strategy

Online redo logs

Archived redo logs not yet backed up to tape

Control files

Control file autobackups (which include copies of the control file and SPFILE)

If providing this much space is impractical, it is best to create an area large enough to keep a backup of the most important tablespaces and all the archived logs not yet copied to tape. At an absolute minimum, the flash recovery area must be large enough to contain the archived logs that have not been copied to tape.

To determine the disk quota and current disk usage in the flash recovery area, query the view V$RECOVERY_FILE_DEST.

Formulas for estimating a useful flash recovery area size depend upon several factors in your backup and recovery strategy.

Whether your database has a small or large number of data blocks that change frequently;

Whether you store backups only on disk, or on disk and tape;

Whether you use a redundancy-based retention policy, or a recovery window-based retention policy;

Whether you plan to use Flashback Database or guaranteed restore points as alternatives to point-in-time recovery to recover from logical errors.

Enabling Flashback Database

TCS Internal

Page 7: Flashback All

You can enable Flashback Database using the following steps:

1.1 Make sure the database is in archive mode.

1.2 Configure the recovery area by setting the two parameters:

- db_recovery_file_dest (2nd)alter system set db_recovery_file_dest = ‘/backup’

- db_recovery_file_dest_size (1st)alter system set db_recovery_file_dest_size = 500M

Remember:

(1) If you configure "db_recovery_file_dest" parameter then all archive log files are generated in FLASH RECOVERY AREA (db_recovery_file_dest). On the other hand, you cannot set "log_archive_dest" and “log_archive_duplex_dest” parameters with "db_recovery_file_dest" or "log_archive_dest_n" parameters (& vice versa that if you have log_archive_dest or log_archive_duplex_dest set up in a database, it won’t let you set db_recovery_file_dest parameter (ORA16019))

(2) LOG_ARCHIVE_DEST is implicitly set to USE_DB_RECOVERY_FILE_DEST (meaning that archived redo log files will be sent to the flash recovery area) if you create a recovery area and do not set any other local archiving destinations.

Ex:

SQL> archive log listDatabase log mode Archive ModeAutomatic archival EnabledArchive destination USE_DB_RECOVERY_FILE_DESTOldest online log sequence 41Next log sequence to archive 43Current log sequence 43

(3) Oracle Corporation recommends that DB_RECOVERY_FILE_DEST not be the same as DB_CREATE_FILE_DEST or any of the DB_CREATE_ONLINE_LOG_DEST_n parameters. A warning will appear in the alert log if DB_RECOVERY_FILE_DEST is the same as any of the other parameters listed here.

1.3 Open the database in MOUNT EXCLUSIVE mode and turn on the flashback feature: SQL> STARTUP MOUNT;

SQL> ALTER DATABASE FLASHBACK ON;

1.4 Set the Flashback Database retention target:

- db_flashback_retention_target (default 1440 min; range 0 to 231

-1)

This parameter specifies that how far back in time (upper limit in min) the database can be flashed back. How far back one can flashback a database depends on how much flashback data Oracle has kept in the flash recovery area.

TCS Internal

Page 8: Flashback All

1.5 Determine if Flashback Database is enabled:

SQL> select flashback_on from v$database;

FLASHBACK_ON

------------

YES

Disabling Flashback Database

2.1 Issue the following command to disable Flashback Database:

SQL> ALTER DATABASE FLASHBACK OFF;

Flashback Features:

Flashback table - lets you recover a table to a time in the past (using undo data) Flashback row history/ flashback query - lets you query and restore data rows to a

point in time (using undo data) Flashback transaction/ flashback query - lets you query and restore data rows to a

point in time (using undo data) Flashback database - enables you to take the entire database to a past point in time

(using flashback logs) Flashback standby database – same as above Flashback reinstantiation - Flashback drop - lets you retrieve accidentally dropped tables and indexes (using the

recycle bin)

Most of the above features rely on undo data, records of the effects of each update to an Oracle database and values overwritten in the update. Used primarily for such purposes as providing read consistency for SQL queries and rolling back transactions, these undo records contain the information required to reconstruct data as it stood at a past time and all changes since that time.

(1) Flashback Table

Flashback Table allows you to recover a table or tables to a specific point in time without restoring a backup. When you use the Flashback Table feature to restore a table to a specific point in time, all associated objects, such as indexes, constraints, and triggers will be restored.

Flashback Table operations are not valid for the following object types:

- Tables that are part of a cluster- Materialized views- Advanced Queuing tables- Static data dictionary tables- System tables- Partitions of a table

TCS Internal

Page 9: Flashback All

- Remote tables (via database link)

Flashback Table is extremely useful when a user accidentally inserts, deletes, or updates the wrong rows in a table. It provides a way for users to easily and quickly recover a table to a previous point in time.

However, if the following DDL commands are issued, the flashback table command does not work:

- ALTER TABLE ... DROP COLUMN- ALTER TABLE ... DROP PARTITION- CREATE CLUSTER- TRUNCATE TABLE- ALTER TABLE ... MOVE

Undo Retention

Oracle Database 10g automatically tunes undo retention by collecting database use statistics and estimating undo capacity needs for the successful completion of the queries. You can set a low threshold value for the UNDO_RETENTION parameter so that the system retains the undo for at least the time specified in the parameter, provided that the current undo tablespace has enough space. Under space constraint conditions, the system may retain undo for a shorter duration than that specified by the low threshold value in order to allow DML operations to succeed.

In order to guarantee the success of queries even at the price of compromising the success of DML operations, you can enable retention guarantee. The RETENTION GUARANTEE clause of the CREATE UNDO TABLESPACE and CREATE DATABASE statements ensures that undo information is not overwritten. This option must be used with caution, because it can cause DML operations to fail if the undo tablespace is not big enough. However, with proper settings, long-running queries can complete without risk of receiving the "snapshot too old" message, and you can guarantee a time window in which the execution of Flashback features will succeed.

To create an undo tablespace with the RETENTION GUARANTEE option, issue the following command:

CREATE UNDO TABLEAPCE undo_tbsDATAFILE '/u02/oradata/grid/undo_tbs01.dbf' SIZE 1 GRETENTION GUARANTEE;

Or, ALTER TABLESPACE UNDO_TS2 RETENTION GUARANTEE;

To check the changes done:

SELECT RETENTIONFROM DBA_TABLESPACESWHERE TABLESPACE_NAME = 'UNDO_TBS';

Flashback Table Privileges

TCS Internal

Page 10: Flashback All

You must have the FLASHBACK TABLE or FLASHBACK ANY TABLE system privilege to use the Flashback Table feature.

Examples:

Example 1: Flashback Table using SCN

This statement brings a table 'billing' back to a certain SCN number; table row movement must be enabled as a prerequisite:

SQL> FLASHBACK TABLE billing TO SCN 76230;

Example 2: Flashback Table using TIMESTAMP

This statement brings a table 'billing' back to a certain timestamp:

SQL> FLASHBACK TABLE billing TO_TIMESTAMP ('06/25/03 12:00:00','MM/DD/YY HH:MI:SS');

SQL> create table test_fb(a number) enable row movement;

Table created.

SQL> select dbms_flashback.get_system_change_number from dual;

GET_SYSTEM_CHANGE_NUMBER------------------------ 8.8959E+12

SQL> col GET_SYSTEM_CHANGE_NUMBER format 999999999999999SQL> /

GET_SYSTEM_CHANGE_NUMBER------------------------ 8895883138489

SQL> insert into test_fb values (10);

1 row created.

SQL> commit;

Commit complete.

SQL> select dbms_flashback.get_system_change_number from dual;

GET_SYSTEM_CHANGE_NUMBER------------------------ 8895883138503

SQL> insert into test_fb values (11);

TCS Internal

Page 11: Flashback All

1 row created.

SQL> commit;

Commit complete.

SQL> select dbms_flashback.get_system_change_number from dual;

GET_SYSTEM_CHANGE_NUMBER------------------------ 8895883138510

SQL> flashback table test_fb to scn 8895883138503;

Flashback complete.

SQL> select * from test_fb;

A---------- 10

SQL> flashback table test_fb to scn 8895883138510;

Flashback complete.

SQL> select * from test_fb;

A---------- 10 11

WHAT IS THERE IS A PARENT CHILD RELATIONSHIP??

SQL> create table test_fb2(a number primary key) enable row movement;

Table created.

SQL> create table test_fb2_child (b number) enable row movement;

Table created.

SQL> alter table test_fb2_child add constraint fk_test_fb_child foreign key (b) references test_fb2 (a);

Table altered.

SQL> insert into test_fb2 values (10);

1 row created.

TCS Internal

Page 12: Flashback All

SQL> insert into test_fb2_child values (11); Just to show that constraint is working indeed !! insert into test_fb2_child values (11)*ERROR at line 1:ORA-02291: integrity constraint (JP.FK_TEST_FB_CHILD) violated - parent key notfound

SQL> insert into test_fb2_child values (10);

1 row created.

SQL> commit;

Commit complete.

SQL> select dbms_flashback.get_system_change_number from dual;

GET_SYSTEM_CHANGE_NUMBER------------------------ 8895883139552

SQL> insert into test_fb2 values (111);

1 row created.

SQL> insert into test_fb2_child values (111);

1 row created.

SQL> commit;

Commit complete.

SQL> select dbms_flashback.get_system_change_number from dual;

GET_SYSTEM_CHANGE_NUMBER------------------------ 8895883139562

SQL> select * from test_fb2_child;

B---------- 10 111

SQL> flashback table test_fb2 to scn 8895883139552;flashback table test_fb2 to scn 8895883139552*ERROR at line 1:ORA-02091: transaction rolled backORA-02292: integrity constraint (JP.FK_TEST_FB_CHILD) violated - child record

TCS Internal

Page 13: Flashback All

found

SQL> flashback table test_fb2_child to scn 8895883139552;

Flashback complete.

SQL> select * from test_fb2_child;

B---------- 10

SQL> select * from test_fb2;

A---------- 10 111

(2) Flashback row history

Flashback Query was first introduced in Oracle9i to provide a way to view historical data. In Oracle 10g, this feature has been extended. You can now retrieve all versions of the rows that exist or ever existed between the time the query was issued and a point back in time. This type of query is called Flashback Row History (or Flashback Versions Query)

You can use the VERSIONS BETWEEN clauses to retrieve all historical data related to a row.

Let's take a look at the example below:

SQL> create table emp (name varchar2(10), salary number(8,2));

Table created.

SQL> insert into emp values ('DANIEL',2000);

1 row created.

SQL> commit;

Commit complete.

SQL> update emp set salary = 3000 where name = 'DANIEL';

1 row updated.

SQL> commit;

Commit complete.

SQL> select * from emp;

TCS Internal

Page 14: Flashback All

NAME SALARY

---------- ----------

DANIEL 3000

SQL> select * from emp versions between scn minvalue and maxvalue;

NAME SALARY

---------- ----------

DANIEL 3000

DANIEL 2000

As you can see, the Flashback Row History feature retrieves all committed occurrences of the row. It provides you with a way to view and repair historical data. In addition, it also provides a new way to audit the rows of a table and retrieve information about the transactions that changed the rows. You can use the transaction ID obtained from Flashback Row History to perform transaction mining using LogMiner or Flashback Transaction History (see next section) to obtain additional information about the transaction.

The VERSION BETWEEN clause does not change the query plan. You can use the clause in a SELECT statement against a view. However, you cannot use the VERSION BETWEEN clause in a view definition.

The row history data is stored in the undo tablespace. The undo_retention initialization parameter specifies how long the database will keep the committed undo information. If a new transaction needs to use undo space and there is not enough free space left, any undo information older than the specified undo retention period will be overwritten. Therefore, you may not be able to see all the row histories. However, you can set the undo tablespace option to RETENTION GUARANTEE to retain all row histories.

To verify the retention value for the tablespace, you can issue the following statement:

SQL> select tablespace_name, retention from dba_tablespaces;

TABLESPACE_NAME RETENTION------------------------------ -----------SYSTEM NOT APPLYUNDOTBS1 NOGUARANTEESYSAUX NOT APPLYTEMP NOT APPLYEXAMPLE NOT APPLYUSERS NOT APPLY

6 rows selected.

(3) Flashback transaction

TCS Internal

Page 15: Flashback All

The Flashback Transaction History feature provides a way to view changes made to the database at the transaction level. It allows you to diagnose problems in your database and perform analysis and audit transactions. You can use this feature in conjunction with the Flash Row History feature to roll back the changes made by a transaction. You can also use this feature to audit user and application transactions. The Flashback Transaction History provides a faster way to undo a transaction than LogMiner.

You can retrieve the transaction history from flashback_transaction_query view:

SQL> desc dba_transaction_query

Name Null? Type ------------------------------------ -------- ---------------- XID RAW(8) START_SCN NUMBER START_TIMESTAMP DATE COMMIT_SCN NUMBER COMMIT_TIMESTAMP DATE LOGON_USER VARCHAR2(30) UNDO_CHANGE# NUMBER OPERATION VARCHAR2(32) TABLE_NAME VARCHAR2(256) TABLE_OWNER VARCHAR2(32) ROW_ID VARCHAR2(19) UNDO_SQL VARCHAR2(4000)

SQL> select versions_xid, name, salary from emp versions between scn minvalue and maxvalue;

VERSIONS_XID NAME SALARY---------------- ---------- ----------0003000E00000FE2 DANIEL 3000 DANIEL 2000

SQL> select * from dba_transaction_query where xid = '0003000E00000FE2';

Sample o/p:

XID START_SCN START_TIMESTAMP COMMIT_SCN COMMIT_TIMESTAMP LOGON_USER UNDO_CHANGE# OPERATION TABLE_NAME TABLE_OWNER ROW_ID UNDO_SQL

---------------- --------- --------------- ---------- ---------------- ------------------------------ ------------ -------------------------------- -------------------------------------------------------------------------------- -------------------------------- ------------------- --------------------------------------------------------------------------------

0002000200000D15 889587433 8/19/2009 2:30: 8895874331 8/19/2009 2:30:0 SYS 35 INSERT WRH$_SERVICE_STAT SYS AAA8TuAADAAAEB9AAS delete from "SYS"."WRH$_SERVICE_STAT" where ROWID = 'AAA8TuAADAAAEB9AAS';

TCS Internal

Page 16: Flashback All

0002000200000D15 889587433 8/19/2009 2:30: 8895874331 8/19/2009 2:30:0 SYS 36 INSERT WRH$_SERVICE_STAT SYS AAA8TuAADAAAEB9AAT delete from "SYS"."WRH$_SERVICE_STAT" where ROWID = 'AAA8TuAADAAAEB9AAT';

(4) Flashback database

When Flashback Database is enabled, a new RVWR background process is started. This process is similar to the LGWR (log writer) process. The new process writes Flashback Database data to the Flashback Database logs.

oracleqc 8379 1 0 18:15:48 ? 0:00 ora_lgwr_iedboracleqc 8415 1 0 18:17:12 ? 0:00 ora_q000_iedboracleqc 8403 1 0 18:16:49 ? 0:00 ora_rvwr_iedboracleqc 8420 1 0 18:17:53 ? 0:00 ora_q001_iedboracleqc 8371 1 0 18:15:48 ? 0:00 ora_pmon_iedboracleqc 8389 1 0 18:15:49 ? 0:00 ora_mmon_iedboracleqc 8385 1 0 18:15:49 ? 0:00 ora_reco_iedb

Example 1: Flashback a Database using RMAN

RMAN> FLASHBACK DATABASE 2> TO TIME = TO_DATE 3> ('06/25/03 12:00:00','MM/DD/YY HH:MI:SS');

Example 2: Flashback a database using SQL command

The database must be in mount state to issue these commands:

SQL> FLASHBACK DATABASE TO TIMESTAMP (SYSDATE - 5/24);SQL> FLASHBACK DATABASE TO SCN 76239;

You must issue the following command afterwards:

SQL> ALTER DATABASE RESETLOGS;

(5) Flashback standby database

TCS Internal

Page 17: Flashback All

If you have multiple standby sites, you may utilize the DELAY option in Data Guard to prevent physical/logical corruption or user errors in your primary database.

For example, the first scenario in the diagram below has only one standby database. Here, a logical or physical corruption in the primary database will cause an immediate corruption in the standby database.

To avoid such a pitfall, you can implement a second standby database with the 'Delay' option (introducing a delay of minutes or hours on the second standby database for applying archive log changes). This will prevent the corruptions on the second standby database and allow recovery from a possible physical/logical corruption or user errors in the primary database.

You can issue the following command to accomplish this:

SQL> alter database recover managed standby database delay 60 disconnect;

However, in Oracle 10g, you can configure the standby database with Flashback Database to achieve the same benefit as the DELAY option. Therefore, there is no need to implement a second standby database with the DELAY option.

(6) Flashback reinstantiation

In an Oracle9i Data Guard environment, a failover operation leads to a resetlogs. This operation invalidates the old primary database. Therefore, you need to perform a hot backup on the new primary database immediately, and then re-create a new standby database. This operation can take a long time, and your new primary database is vulnerable during this period.

The new Flashback Re-instantiation feature reduces the need to reinstantiate the old primary database following a failover. This feature allows you to quickly restore full resiliency after a failure. This is accomplished by using the SQL statement FLASHBACK DATABASE to roll back the old primary database in time to synchronize with the old standby database.

Here are the steps to perform Flashback Re-instantiation:

On your new primary database (Instance B): SQL> select standby_became_primary_scn from v$database;

STANDBY_BECAME_P----------------2960985

Mount the old primary database (Instance A). SQL> STARTUP MOUNT

Flashback the old primary database (Instance A) to the SCN. SQL> flashback database to scn 2960985;

Disable Flashback on the old primary database (Instance A). SQL> ALTER DATABASE FLASHBACK OFF;

TCS Internal

Page 18: Flashback All

On the old primary database (Instance A), create a standby control file. SQL> alter database create standby controlfile as'/dba/standby/stbycf.f' reuse;

Shutdown the old primary database (Instance A), and replace the control files with the new standby control files. SQL> shutdown immediate; $ cp /dba/standby/stbyct.f /u02/oradata/sid/control01.ctl $ cp /dba/standby/stbyct.f /u02/oradata/sid/control02.ctl

Bring up the old primary database as a new physical standby database (Instance A). SQL> startup mount;

Turn flashback back on the new primary database (Instance A). SQL> alter database flashback on;

Enable transport from the new primary database (Instance B) SQL> ALTER SYSTEM SET LOG_ARCHIVE_DEST_STATE_1=ENABLE;

On the new standby database (Instance A), start real time apply. SQL> RECOVER MANAGED STANDBY DATABASE using current logfile DISCONNECT;

The Managed Recovery process (MRP) will hit the End-Of-Redo and then need to be restarted. SQL> RECOVER MANAGED STANDBY DATABASE using current logfile DISCONNECT;

(7) Flashback Drop:

Prior to Oracle 10g, a DROP command permanently removed objects from the database. In Oracle 10g, a DROP command places the object in the recycle bin. The extents allocated to the segment are not reallocated until you purge the object. You can restore the object from the recycle bin at any time.

This feature eliminates the need to perform a point-in-time recovery operation. Therefore, it has minimum impact to other database users.

Recycle Bin

A recycle bin contains all the dropped database objects until,

- You permanently drop them with the PURGE command.- Recover the dropped objects with the UNDROP command.- There is no room in the tablespace for new rows or updates to existing rows.- The tablespace needs to be extended.

You can view the dropped objects in the recycle bin from two dictionary views:

- user_recyclebin - lists all dropped user objects - dba_recyclebin - lists all dropped system-wide objects

Example 1: Dropping an Object

In the example below, the name of the object is changed when it is dropped and moved to the recycle bin. The recycle bin also keeps the original name of the object. This feature allows you to create a new object of the same name and then drop it again.

SQL> create table test (col_a varchar(4));

Table created.

TCS Internal

Page 19: Flashback All

SQL> select object_name, original_name, type from user_recyclebin;

no rows selected

SQL> drop table test;

Table dropped.

SQL> select object_name, original_name, type from user_recyclebin;

OBJECT_NAME ORIGINAL_NAME TYPE------------------------ ---------------- -----RB$$42513$TABLE$0 TEST TABLE

SQL> create table test (col_b varchar(4));Table created.

SQL> select object_name, original_name, type from user_recyclebin;

OBJECT_NAME ORIGINAL_NAME TYPE------------------------ ---------------- -----RB$$42513$TABLE$0 TEST TABLE

SQL> drop table test;Table dropped.

SQL> select object_name, original_name, type from user_recyclebin;

OBJECT_NAME ORIGINAL_NAME TYPE------------------------ ---------------- -----RB$$42513$TABLE$0 TEST TABLERB$$42514$TABLE$0 TEST TABLE

Example 2: Restoring a Dropped Object

This example will restore a dropped table test.

SQL> flashback table RB$$42514$TABLE$0 to before drop;

Flashback complete.

Example 3: Dropping a Table Permanently

This statement puts the table in the recycle bin:

SQL> drop table test purge;

this statement removes the table permanently:

SQL> purge table RB$$42514$TABLE$0;Table purged.

Example 4: Dropping a Tablespace

TCS Internal

Page 20: Flashback All

You can only issue this command when the tablespace ‘users’ is empty. Objects in the recycle bin of tablespace users will be purged:

SQL> drop tablespace users;

When you issue this command, objects in the tablespace users are dropped. They are not placed in the recycle bin. Any objects in the recycle bin belonging to the tablespace users are purged.

SQL> drop tablespace users including contents;

Example 5: Purging the Recycle Bin

This statement purges the user recycle bin:

SQL> purge recyclebin;

Recyclebin purged.

This statement removes all objects from the recycle bin:

SQL> purge dba_recyclebin;

Recyclebin purged.

This statement purges all objects from tablespace users in the recycle bin:

SQL> purge tablespace users;

Tablespace purged.

Exploring Flashback With More Examples:

Example 1:

Step 1---------

SQL> select dbms_flashback.get_system_change_number SCN from dual;

SCN-------1700715

SQL> conn scott/tigerConnected.

SQL> create table T(name varchar2(20));

TCS Internal

Page 21: Flashback All

Table created.

SQL> insert into T values('jatin');

1 row created.

SQL> insert into T values('lalit');

1 row created.

SQL> insert into T values('varun');

1 row created.

SQL> insert into T values('anil');

1 row created.

SQL> insert into T values('sushant');

1 row created.

SQL> commit;

Commit complete.

SQL> conn sys as sysdbaEnter password:Connected.

SQL> select dbms_flashback.get_system_change_number SCN from dual;

SCN---------- 1700755 => until this SCN we have all changes.

step 2------

SQL> delete from T 2 ;

5 rows deleted.

SQL> commit;

Commit complete.

Step 3--------

SQL> desc T

TCS Internal

Page 22: Flashback All

Name Null? Type ----------------------------------------- -------- ---------------------------- NAME VARCHAR2(20)

SQL> create table t_temp as select * from t;

Table created.

Step 4-------SQL> conn sys as sysdbaEnter password:

Connected.SQL> grant execute on DBMS_FLASHBACK to scott;

Grant succeeded.

SQL> conn scott/tiger;Connected.

SQL> DECLARE 2 CURSOR emp_cur IS 3 SELECT * FROM T; 4 v_rec emp_cur%rowtype; 5 BEGIN 6 DBMS_FLASHBACK.ENABLE_AT_SYSTEM_CHANGE_NUMBER (1700755); 7 open emp_cur; 8 DBMS_FLASHBACK.DISABLE; 9 LOOP 10 fetch emp_cur into v_rec; 11 EXIT WHEN emp_cur%NOTFOUND; 12 INSERT INTO T_TEMP VALUES 13 (v_rec.name); 14 END LOOP; 15 close emp_cur; 16 COMMIT; 17 END; 18 /

PL/SQL procedure successfully completed.

SQL> select * from t_temp;

NAME--------------------jatinlalitvarunanilsushant

Example 2:

In case you end up dropping a table use:

SQL> flashback table t_temp to before drop;

TCS Internal

Page 23: Flashback All

Caution: There is no disable flashback in this case & the table is just restored from the recycle bin.

Example 3:

SQL> desc rates

Name Null? Type ----------------- -------- ------------ CURRENCY VARCHAR2(4) RATE NUMBER(15,10)

For example, say that the DBA, in the course of normal business, updates the rate several times—or even deletes a row and reinserts it:

insert into rates values ('EURO',1.1012);commit;update rates set rate = 1.1014;commit;update rates set rate = 1.1013;commit;delete rates;commit;insert into rates values ('EURO',1.1016);commit;update rates set rate = 1.1011;commit;

After this set of activities, the DBA would get the current committed value of RATE column by

SQL> select * from rates;

CURR RATE---- ----------EURO 1.1011

This output shows the current value of the RATE, not all the changes that have occurred since the first time the row was created. Thus using Flashback Query, you can find out the value at a given point in time; but we are more interested in building an audit trail of the changes—somewhat like recording changes through a camcorder, not just as a series of snapshots taken at a certain point.

The following query shows the changes made to the table:

select versions_starttime, versions_endtime, versions_xid, versions_operation, rate from rates versions between timestamp minvalue and maxvalueorder by VERSIONS_STARTTIME/

VERSIONS_STARTTIME VERSIONS_ENDTIME VERSIONS_XID V RATE---------------------- ---------------------- ---------------- - ----------01-DEC-03 03.57.12 PM 01-DEC-03 03.57.30 PM 0002002800000C61 I 1.1012

TCS Internal

Page 24: Flashback All

01-DEC-03 03.57.30 PM 01-DEC-03 03.57.39 PM 000A000A00000029 U 1.101401-DEC-03 03.57.39 PM 01-DEC-03 03.57.55 PM 000A000B00000029 U 1.101301-DEC-03 03.57.55 PM 000A000C00000029 D 1.101301-DEC-03 03.58.07 PM 01-DEC-03 03.58.17 PM 000A000D00000029 I 1.101601-DEC-03 03.58.17 PM 000A000E00000029 U 1.1011

Note that all the changes to the row are shown here, even when the row was deleted and reinserted. The VERSION_OPERATION column shows what operation (Insert/Update/Delete) was performed on the row. This was done without any need of a history table or additional columns.

In the above query, the columns versions_starttime, versions_endtime, versions_xid, versions_operation are pseudo-columns, similar to other familiar ones such as ROWNUM, LEVEL. Other pseudo-columns—such as VERSIONS_STARTSCN and VERSIONS_ENDSCN—show the System Change Numbers at that time. The column versions_xid shows the identifier of the transaction that changed the row. More details about the transaction can be found from the view FLASHBACK_TRANSACTION_QUERY, where the column XID shows the transaction id. For instance, using the VERSIONS_XID value 000A000D00000029 from above, the UNDO_SQL value shows the actual statement.

SELECT UNDO_SQLFROM FLASHBACK_TRANSACTION_QUERYWHERE XID = '000A000C00000029';

UNDO_SQL----------------------------------------------------------------------------insert into "ANANDA"."RATES"("CURRENCY","RATE") values ('EURO','1.1013');

In addition to the actual statement, this view also shows the timestamp and SCN of commit and the SCN and timestamp at the start of the query, among other information.

Example 4:

Just another way of exploring the data in example 3:

Now, let's see how we can use the information effectively. Suppose we want to find out the value of the RATE column at 3:57:54 PM. We can issue:

select rate, versions_starttime, versions_endtimefrom rates versionsbetween timestamp to_date('12/1/2003 15:57:54','mm/dd/yyyy hh24:mi:ss')and to_date('12/1/2003 16:57:55','mm/dd/yyyy hh24:mi:ss')/

RATE VERSIONS_STARTTIME VERSIONS_ENDTIME---------- ---------------------- ---------------------- 1.1011

This query is similar to the flashback queries. In the above example, the start and end times are null, indicating that the rate did not change during the time period; rather, it includes a time period. You could also use the SCN to find the value of a version in the past. The SCN numbers can be obtained from the pseudo-columns VERSIONS_STARTSCN and VERSIONS_ENDSCN. Here is an example:

select rate, versions_starttime, versions_endtimefrom rates versionsbetween scn 1000 and 1001/

TCS Internal

Page 25: Flashback All

Using the keywords MINVALUE and MAXVALUE, all the changes that are available from the undo segments is displayed. You can even give a specific date or SCN value as one of the end points of the ranges and the other as the literal MAXVALUE or MINVALUE. For instance, here is a query that tells us the changes from 3:57:52 PM only; not the complete range:

select versions_starttime, versions_endtime, versions_xid, versions_operation, rate from rates versions between timestamp to_date('12/11/2003 15:57:52', 'mm/dd/yyyy hh24:mi:ss')and maxvalueorder by VERSIONS_STARTTIME/

VERSIONS_STARTTIME VERSIONS_ENDTIME VERSIONS_XID V RATE---------------------- ---------------------- ---------------- - ----------01-DEC-03 03.57.55 PM 000A000C00000029 D 1.101301-DEC-03 03.58.07 PM 01-DEC-03 03.58.17 PM 000A000D00000029 I 1.101601-DEC-03 03.58.17 PM 000A000E00000029 U 1.1011

Note: The maximum available versions are dependent (of course) on the UNDO_RETENTION parameter.

Example 5

/data/iedbdev/archive/IEDB/flashback #ls -ltrtotal 436128-rw-r----- 1 oracleqc dba 15949824 Sep 14 23:15 o1_mf_58yh0mhj_.flb-rw-r----- 1 oracleqc dba 15949824 Sep 14 23:15 o1_mf_58yh0swo_.flb-rw-r----- 1 oracleqc dba 15949824 Sep 15 01:30 o1_mf_58yh1014_.flb-rw-r----- 1 oracleqc dba 15949824 Sep 15 07:30 o1_mf_58yh15tw_.flb-rw-r----- 1 oracleqc dba 15949824 Sep 15 12:30 o1_mf_58yh1pfk_.flb-rw-r----- 1 oracleqc dba 15949824 Sep 15 18:10 o1_mf_58rb56w2_.flb-rw-r----- 1 oracleqc dba 15949824 Sep 15 22:00 o1_mf_58rglr7g_.flb-rw-r----- 1 oracleqc dba 15949824 Sep 15 22:00 o1_mf_58rxjt16_.flb-rw-r----- 1 oracleqc dba 15949824 Sep 15 23:15 o1_mf_58sp35jr_.flb-rw-r----- 1 oracleqc dba 15949824 Sep 15 23:30 o1_mf_58t7p2ob_.flb-rw-r----- 1 oracleqc dba 15949824 Sep 16 05:30 o1_mf_58twsc2o_.flb-rw-r----- 1 oracleqc dba 15949824 Sep 16 11:30 o1_mf_58qx1q8s_.flb-rw-r----- 1 oracleqc dba 15949824 Sep 16 17:30 o1_mf_58rb4mmk_.flb-rw-r----- 1 oracleqc dba 15949824 Sep 16 18:38 o1_mf_58yh0fx5_.flb

SQL> select * from v$flash_recovery_area_usage;

FILE_TYPE PERCENT_SPACE_USED PERCENT_SPACE_RECLAIMABLE NUMBER_OF_FILES------------ ------------------ ------------------------- ---------------CONTROLFILE 0 0 0ONLINELOG 0 0 0ARCHIVELOG 1.63 0 4BACKUPPIECE 33.28 33.28 1IMAGECOPY 0 0 0FLASHBACKLOG 42.57 18.24 14

6 rows selected

SQL> select * from v$flashback_database_log;

TCS Internal

Page 26: Flashback All

OLDEST_FLASHBACK_SCN OLDEST_FLASHBACK_TIME RETENTION_TARGET FLASHBACK_SIZE ESTIMATED_FLASHBACK_SIZE-------------------- --------------------- ---------------- -------------- ------------------------ 8895876947228 9/14/2009 9:59:00 PM 1440 223182848 104595456

SQL> startup mount

ORACLE instance started.

Total System Global Area 2147483648 bytesFixed Size 2070624 bytesVariable Size 520095648 bytesDatabase Buffers 1610612736 bytesRedo Buffers 14704640 bytesDatabase mounted.

SQL> FLASHBACK DATABASE TO TIMESTAMP (SYSDATE -1/24);

Flashback complete

SQL> alter database open resetlogs;

Database altered.

TCS Internal