CHAPTER 19

image

RMAN Restore and Recovery

A couple of years ago, I was out on a long Saturday morning bike ride. About halfway through the ride, my cell phone rang. It was one of the data center operational support technicians. He told me that a mission critical database server was acting strange and that I should log in as soon as possible and make sure things were okay. I told him that I was about 15 minutes from being able to log in. So, I scurried home as fast as I could to check out the production box. When I got home and logged in to the database server, I tried to start SQL*Plus and immediately got an error indicating that the SQL*Plus binary file had corruption. Great. I couldn’t even log in to SQL*Plus. This was not good.

image Mental Note  Ensure that all bicycle rides are taken out of range of cell phone coverage. – Ed.

I had the SA restore the Oracle binaries from an OS backup. I started SQL*Plus. The database had crashed, so I attempted to start it . The output indicated that there was a media failure with all the data files. After some analysis it was discovered that there had been some filesystem issues and that all these files on disk were corrupt:

  • Data files
  • Control files
  • Archive redo logs
  • Online redo log files
  • RMAN backup pieces

This was almost a total disaster. My director asked about our options. I responded, “All we have to do is restore the database from our last tape backup, and we’ll lose whatever data are in archive redo logs that haven’t been backed up to tape yet. ”

The storage administrators were called in and instructed to restore the last set of RMAN backups that had been written to tape. About 15 minutes later, we could hear the tape guys talking to each other in hushed voices. One of them said, “We are sooooo hosed. We don’t have any tape backups of RMAN for any databases on this box.”

That was a dark moment. The worst case scenario was to rebuild the database from DDL scripts and lose 3 years of production data. Not a very palatable option.

After looking around the production box, I discovered that the prior production support DBA (who, ironically, had just been let go a few days before, owing to budget cuts) had implemented a job to copy the RMAN backups to another server in the production environment. The RMAN backups on this other server were intact. I was able to restore and recover the production database from these backups. We lost about a day’s worth of data (between corrupt archive logs and downtime, in which no incoming transactions were allowed), but we were able to get the database restored and recovered approximately 20 hours after the initial phone call. That was a long day.

Most situations in which you need to restore and recover will not be as bad as the one just described. However, the previous scenario does highlight the need for

  • a backup strategy
  • a DBA with B&R skills
  • a restore-and-recovery strategy, including a requirement to test the restore and recovery periodically

This chapter walks you through restore and recovery, using RMAN. The chapter covers many of the common tasks you will have to perform when dealing with media failures.

Determining if Media Recovery Is Required

The term media recovery means the restoration of files that have been lost or damaged, owing to the failure of the underlying storage media (usually a disk of some sort) or accidental removal of files. Usually, you know that media recovery is required through an error such as the following:

ORA-01157: cannot identify/lock data file 1 - see DBWR trace file
ORA-01110: data file 1: '/u01/dbfile/o12c/system01.dbf'

The error may be displayed on your screen when performing DBA tasks, such as stopping and starting the database. Or, you might see such an error in a trace file or the alert.log file. If you don’t notice the issue right away, with a severe media failure, the database will stop processing transactions, and users will start calling you.

To understand how Oracle determines that media recovery is required, you must first understand how Oracle determines that everything is okay. When Oracle shuts down normally (IMMEDIATE, TRANSACTIONAL, NORMAL), part of the shutdown process is to flush all modified blocks (in memory) to disk, mark the header of each data file with the current SCN, and update the control file with the current SCN information.

Upon startup, Oracle checks to see if the SCN in the control file matches the SCN in the header of the data files. If there is a match, then Oracle attempts to open the data files and online redo log files. If all files are available and can be opened, Oracle starts normally. The following query compares the SCN in the control file (for each data file) with the SCN in the data file header:

SET LINES 132
COL name             FORM a40
COL status           FORM A8
COL file#            FORM 9999
COL control_file_SCN FORM 999999999999999
COL datafile_SCN     FORM 999999999999999
--
SELECT
 a.name
,a.status
,a.file#
,a.checkpoint_change# control_file_SCN
,b.checkpoint_change# datafile_SCN
,CASE
   WHEN ((a.checkpoint_change# - b.checkpoint_change#) = 0) THEN 'Startup Normal'
   WHEN ((b.checkpoint_change#) = 0)                        THEN 'File Missing?'
   WHEN ((a.checkpoint_change# - b.checkpoint_change#) > 0) THEN 'Media Rec. Req.'
   WHEN ((a.checkpoint_change# - b.checkpoint_change#) < 0) THEN 'Old Control File'
   ELSE 'what the ?'
 END datafile_status
FROM v$datafile        a -- control file SCN for datafile
    ,v$datafile_header b -- datafile header SCN
WHERE a.file# = b.file#
ORDER BY a.file#;

If the control file SCN values are greater than the data file SCN values, then media recovery is most likely required. This would be the case if you restored a data file from a backup, and the SCN in the restored data file had an SCN less than the data file in the current control file.

image Tip   The V$DATAFILE_HEADER view uses the physical data file on disk as its source. The V$DATAFILE view uses the control file as its source.

You can also directly query the V$DATAFILE_HEADER for more information. The ERROR and RECOVER columns report any potential problems. For example, a YES or null value in the RECOVER column indicates that there is a problem:

SQL> select file#, status, error, recover from v$datafile_header;

Here is some sample output:

     FILE# STATUS  ERROR                REC
---------- ------- -------------------- ---
         1 ONLINE  FILE NOT FOUND
         2 ONLINE                       NO
         3 ONLINE                       NO

Determining What to Restore

Media recovery requires that you perform manual tasks to get your database back in one piece. These tasks usually involve a combination of RESTORE and RECOVER commands. You will have to issue an RMAN RESTORE command if, for some reason (accidental deleting of files, disk failure, and so on), your data files have experienced media failure.

How the Process Works

When you issue the RESTORE command, RMAN automatically decides how to extract the data files from any of the following available backups:

  • Full database backup
  • Incremental level-0 backup
  • Image copy backup generated by BACKUP AS COPY command

After the files are restored from a backup, you are required to apply redo to them via the RECOVER command. When you issue the RECOVER command, Oracle examines the SCNs in the affected data files and determines whether any of them need to be recovered. If the SCN in the data file is less than the corresponding SCN in the control file, then media recovery will be required.

Oracle retrieves the data file SCN and then looks for the corresponding SCN in the redo stream to establish where to start the recovery process. If the starting recovery SCN is in the online redo log files, the archived redo log files are not required for recovery.

During a recovery, RMAN automatically determines how to apply redo. First, RMAN applies any incremental backups available that are greater than level 0, such as the incremental level 1. Next, any archived redo log files on disk are applied. If the archived redo log files do not exist on disk, RMAN attempts to retrieve them from a backup set.

To be able to perform a complete recovery, all the following conditions need to be true:

  • Your database is in archivelog mode.
  • You have a good baseline backup of your database.
  • You have any required redo that has been generated since the backup (archived redo log files, online redo log files, or incremental backups that RMAN can use for recovery instead of applying redo).

There are a wide variety of restore-and-recovery scenarios. How you restore and recover depends directly on your backup strategy and which files have been damaged. Listed next are the general steps to follow when facing a media failure:

  1. Determine which files need to be restored.
  2. Depending on the damage, set your database mode to nomount, mount, or open.
  3. Use the RESTORE command to retrieve files from RMAN backups.
  4. Use the RECOVER command for data files requiring recovery.
  5. Open your database.

Your particular restore-and-recovery scenario may not require that all the previous steps be performed. For instance, you may just want to restore your spfile, which doesn’t require a recovery step.

The first step in the restore-and-recovery process is to determine which files have experienced media failure. You can usually determine which files need to be restored from the following sources:

  • Error messages displayed on your screen, either from RMAN or SQL*Plus
  • Alert.log file and corresponding trace files
  • Data dictionary views

If you’re using Oracle Database 11g or higher, then in addition to the previously listed methods, you should consider the Data Recovery Advisor for obtaining information about the extent of a failure and corresponding corrective action.

Using Data Recovery Advisor

The Data Recovery Advisor tool was introduced in Oracle Database 11g. In the event of a media failure, this tool will display the details of the failure, recommend corrective actions, and perform the recommended actions if you specify that it do so. It’s like having another set of eyes to provide feedback when in a restore-and-recovery situation. There are four modes to Data Recovery Advisor:

  • Listing failures
  • Suggesting corrective action
  • Running commands to repair failures
  • Changing the status of a failure

The Data Recovery Advisor is invoked from RMAN. You can think of the Data Recovery Advisor as a set of RMAN commands that can assist you when dealing with media failure.

Listing Failures

When using the Data Recovery Advisor, the LIST FAILURE command is used to display any issues with the data files, control files, or online redo logs:

RMAN> list failure;

If there are no detected failures, you’ll see a message indicating that there are no failures. Here is some sample output indicating that there may be an issue with a data file:

List of Database Failures
=========================
 
Failure ID Priority Status    Time Detected Summary
---------- -------- --------- ------------- -------
6222       CRITICAL OPEN      12-JAN-13     System datafile 1:
 '/u01/dbfile/o12c/system01.dbf' is missing

To display more information about the failure, use the DETAIL clause:

RMAN> list failure 6222 detail;

Here is the additional output for this example:

Impact: Database cannot be opened

With this type of failure, the prior output indicates that the database can’t be opened.

image Tip   If you suspect there’s a media failure, yet the Data Recovery Advisor is not reporting any issues, run the VALIDATE DATABASE command to verify that the database is intact.

Suggesting Corrective Action

The ADVISE FAILURE command gives advice about how to recover from potential problems detected by the Data Recovery Advisor. If you have multiple failures with your database, you can directly specify the failure ID to get advice on a given failure, like so:

RMAN> advise failure 6222;

Here is a snippet of the output for this particular issue:

Optional Manual Actions
=======================
1. If file /u01/dbfile/o12c/system01.dbf was unintentionally renamed or moved,
restore it
 
Automated Repair Options
========================
Option Repair Description
------ ------------------
1      Restore and recover datafile 1
  Strategy: The repair includes complete media recovery with no data loss
  Repair script: /ora01/app/oracle/diag/rdbms/o12c/o12c/hm/reco_4116328280.hm

In this case, the Data Recovery Advisor created a script that can be used to potentially fix the problem. The contents of the repair script can be viewed with an OS utility; for example,

$ cat /ora01/app/oracle/diag/rdbms/o12c/o12c/hm/reco_4116328280.hm

Here are the contents of the script for this example:

# restore and recover datafile
restore ( datafile 1 );
recover datafile 1;
sql 'alter database datafile 1 online';

After reviewing the script, you can decide to run the suggested commands manually, or you can have the Data Recovery Advisor run the script via the REPAIR command (see the next section for details).

Repairing Failures

If you have identified a failure and viewed the recommended advice, you can proceed to the repair work. If you want to inspect what the REPAIR FAILURE command will do without actually running the commands, use the PREVIEW clause:

RMAN> repair failure preview;

Before you run the REPAIR FAILURE command, ensure that you first run the LIST FAILURE and ADVISE FAILURE commands from the same connected session. In other words, the RMAN session that you’re in must run the LIST and ADVISE commands within the same session before running the REPAIR command.

If you’re satisfied with the repair suggestions, then run the REPAIR FAILURE command:

RMAN> repair failure;

You’ll be prompted at this point for confirmation:

Do you really want to execute the above repair (enter YES or NO)?

Type YES to proceed:

YES

If all goes well, you should see a final message such as this in the output:

repair failure complete

image Note   You can run the Data Recovery Advisor commands from the RMAN command prompt or from Enterprise Manager.

In this way, you can use the RMAN commands L IST FAILURE, A DVISE FAILURE, and REPAIR FAILURE to resolve media failures.

Changing the Status of a Failure

One last note on the Data Recovery Advisor: if you know that you’ve had a failure and that it isn’t critical (e.g., a data file missing from a tablespace that is no longer used), then use the CHANGE FAILURE command to alter the priority of a failure. In this example, there’s a missing data file that belongs to a noncritical tablespace. First, obtain the failure priority via the LIST FAILURE command:

RMAN> list failure;

Here is some sample output:

Failure ID Priority Status    Time Detected Summary
---------- -------- --------- ------------- -------
5          HIGH     OPEN      12-JAN-13     One or more non-system datafiles
                                            are missing

Next, change the priority from HIGH to LOW with the CHANGE FAILURE command:

RMAN> change failure 5 priority low;

You will be prompted to confirm that you really do want to change the priority:

Do you really want to change the above failures (enter YES or NO)?

If you do want to change the priority, then type YES, and press the Enter key. If you run the LIST FAILURE command again, you’ll see that the priority has now been changed to LOW:

RMAN> list failure low;

Using RMAN to Stop/Start Oracle

You can use RMAN to stop and start your database with methods that are almost identical to those available through SQL*Plus. When performing restore and recovery operations, it’s often more convenient to stop and start your database from within RMAN. The following RMAN commands can be used to stop and start your database:

  • SHUTDOWN
  • STARTUP
  • ALTER DATABASE

Shutting Down

The S HUTDOWN command works the same from RMAN as it does from SQL*Plus. There are four types of shutdown: ABORT, IMMEDIATE, NORMAL, and TRANSACTIONAL. I usually first attempt to stop a database using S HUTDOWN IMMEDIATE; if that doesn’t work, don’t hesitate to use S HUTDOWN ABORT. Here are some examples:

RMAN> shutdown immediate;
RMAN> shutdown abort;

If you don’t specify a shutdown option, NORMAL is the default. Shutting down a database with NORMAL is rarely viable, as this mode waits for currently connected users to disconnect at their leisure. I never use NORMAL when shutting down a database.

Starting Up

As with SQL*Plus, you can use a combination of S TARTUP and A LTER DATABASE commands with RMAN to step the database through startup phases, like this:

RMAN> startup nomount;
RMAN> alter database mount;
RMAN> alter database open;

Here is another example:

RMAN> startup mount;
RMAN> alter database open;

If you want to start the database with restricted access, use the DBA option:

RMAN> startup dba;

image Tip   Starting with Oracle Database 12c, you can run all SQL statements directly from within RMAN without having to specify the RMAN sql command.

Complete Recovery

As discussed in Chapter 16, the term complete recovery means that you can restore all transactions that were committed before a failure occurred. Complete recovery doesn’t mean that you are restoring and recovering all data files in your database. For instance, you are performing a complete recovery if you have a media failure with one data file, and you restore and recover the one data file. For complete recovery, the following conditions must be true:

  • Your database is in archivelog mode.
  • You have a good baseline backup of the data files that have experienced media failure.
  • You have any required redo that has been generated since the last backup.
  • All archive redo logs start from the point at which the last backup began.
  • Any incremental backups that RMAN can use for recovery are available (if using).
  • Online redo logs that contain transactions that have not yet been archived are available.

If you’ve experienced a media failure, and you have the required files to perform a complete recovery, then you can restore and recover your database.

Testing Restore and Recovery

You can determine which files RMAN will use for restore and recovery before you actually perform the restore and recovery. You can also instruct RMAN to verify the integrity of the backup files that will be used for the restore and recovery.

Previewing Backups Used for Recovery

Use the RESTORE...PREVIEW command to list the backups and archive redo log files that RMAN will use to restore and recover database data files. The RESTORE...PREVIEW command does not actually restore any files. Rather, it lists the backup files that will be used for a restore operation. This example previews in detail the backups required for restore and recovery for the entire database:

RMAN> restore database preview;

You can also preview require backup files at a summarized level of detail:

RMAN> restore database preview summary;

Here is a snippet of the output:

List of Backup Sets
===================
BS Key  Type LV Size       Device Type Elapsed Time Completion Time
------- ---- -- ---------- ----------- ------------ ---------------
224     Full    775.37M    DISK        00:02:22     12-JAN-13
        BP Key: 229   Status: AVAILABLE  Compressed: NO  Tag: TAG20130112T120713
        Piece Name: /u02/O12C/rman/r29gnv7q7i_1_1.bk
  List of Datafiles in backup set 224
  File LV Type Ckp SCN    Ckp Time  Name
  ---- -- ---- ---------- --------- ----
  1       Full 4586940    12-JAN-13 /u01/dbfile/o12c/system01.dbf
  3       Full 4586940    12-JAN-13 /u01/dbfile/o12c/undotbs01.dbf
  4       Full 4586940    12-JAN-13 /u01/dbfile/o12c/users01.dbf

Here are some more examples of how to preview backups required for restore and recovery:

RMAN> restore tablespace system preview;
RMAN> restore archivelog from time 'sysdate -1' preview;
RMAN> restore datafile 1, 2, 3 preview;

Validating Backup Files Before Restoring

There are several levels of verification that you can perform on backup files without actually restoring anything. If you just want RMAN to verify that the files exist and check the file headers, then use the RESTORE...VALIDATE HEADER command, as shown:

RMAN> restore database validate header;

This command only validates the existence of backup files and checks the file headers. You can further instruct RMAN to verify the integrity of blocks within backup files required to restore the database data files via the RESTORE...VALIDATE command (sans the HEADER clause). Again, RMAN will not restore any data files in this mode:

RMAN> restore database validate;

This command only checks for physical corruption within the backup files. You can also check for logical corruption (along with physical corruption), as follows:

RMAN> restore database validate check logical;

Here are some other examples of using RESTORE...VALIDATE:

RMAN> restore datafile 1,2,3 validate;
RMAN> restore archivelog all validate;
RMAN> restore controlfile validate;
RMAN> restore tablespace system validate;

Testing Media Recovery

The prior sections covered reporting and verifying the restore operations. You can also instruct RMAN to verify the recovery process via the RECOVER...TEST command. Before performing a test recovery, you need to ensure that the data files being recovered are offline. Oracle will throw an error for any online data files being recovered in test mode.

In this example the tablespace U SERS is restored first, and then a trial recovery is performed:

RMAN> connect target /
RMAN> startup mount;
RMAN> restore tablespace users;
RMAN> recover tablespace users test;

If there are any missing archive redo logs that are required for recovery, the following error is thrown:

RMAN-06053: unable to perform media recovery because of missing log
RMAN-06025: no backup of archived log for thread 1 with sequence 6 ...

If the testing of the recovery succeeded, you’ll see messages such as the following, indicating that the application of redo was tested but not applied:

ORA-10574: Test recovery did not corrupt any data block
ORA-10573: Test recovery tested redo from change 4586939 to 4588462
ORA-10572: Test recovery canceled due to errors
ORA-10585: Test recovery can not apply redo that may modify control file

Here are some other examples of testing the recovery process:

RMAN> recover database test;
RMAN> recover tablespace users, tools test;
RMAN> recover datafile 1,2,3 test;

Restoring and Recovering the Entire Database

The RESTORE DATABASE command will restore every data file in your database. The exception to this is when RMAN detects that data files have already been restored; in that case, it will not restore them again. If you want to override that behavior, use the FORCE command.

When you issue the R ECOVER DATABASE command, RMAN will automatically apply redo to any data files that need recovery. The recovery process includes applying changes found in the following files:

  • Incremental backup pieces (applicable only if using incremental backups)
  • Archived redo log files (generated since the last backup or incremental backup applied)
  • Online redo log files (current and unarchived)

You can open your database after the restore-and-recovery process is complete. Complete database recovery works only if you have good backups of your database and access to all redo generated after the backup was taken. You need all the redo required to recover the database data files. If you don’t have all the required redo, then you’ll most likely have to perform an incomplete recovery (see the section “Incomplete Recovery, ” later in this chapter).

image Note   Your database has to be at least mounted to restore data files, using RMAN. This is because RMAN reads information from the control file during the restore-and-recovery process.

You can perform a complete database-level recovery with either the current control file or a backup control file.

Using the Current Control File

You must first put your database in mount mode to perform a database-wide restore and recovery. This is because Oracle won’t allow you to operate your database in open mode while data files associated with the SYSTEM tablespace are being restored and recovered. In this situation, start up the database in mount mode, issue the R ESTORE and R ECOVER commands, and then open the database, like so:

$ rman target /
RMAN> startup mount;
RMAN> restore database;
RMAN> recover database;
RMAN> alter database open;

If everything goes as expected, the last message you should see is this:

Statement processed

Using the Backup Control File

This technique uses an autobackup of the control file retrieved from the FRA. (see the section “Restoring a Control File,” later in this chapter, for more examples of how to restore your control file). In this scenario the control file is first retrieved from a backup before restoring and recovering the database:

$ rman target /
RMAN> startup nomount;
RMAN> restore controlfile from autobackup;
RMAN> alter database mount;
RMAN> restore database;
RMAN> recover database;
RMAN> alter database open resetlogs;

If successful, the last message you should see is this:

Statement processed

Restoring and Recovering Tablespaces

Sometimes you’ll have a media failure that’s localized to a particular tablespace or set of tablespaces. In this situation, it’s appropriate to restore and recover at the tablespace level of granularity. The RMAN RESTORE TABLESPACE and RECOVER TABLESPACE commands will restore and recover all data files associated with the specified tablespace(s).

Restoring Tablespaces While the Database Is Open

If your database is open, then you must take offline the tablespace you want to restore and recover. You can do this for any tablespace except SYSTEM and UNDO. This example restores and recovers the USERS tablespace while the database is open:

$ rman target /
RMAN> sql 'alter tablespace users offline immediate';
RMAN> restore tablespace users;
RMAN> recover tablespace users;
RMAN> sql 'alter tablespace users online';

After the tablespace is brought online, you should see a message such as this:

sql statement: alter tablespace users online

Starting with Oracle Database 12c, you can run SQL statements directly, without the RMAN sql command and associated quotation marks; for example,

$ rman target /
RMAN> alter tablespace users offline immediate;
RMAN> restore tablespace users;
RMAN> recover tablespace users;
RMAN> alter tablespace users online;

Restoring Tablespaces While the Database Is in Mount Mode

Usually when performing a restore and recovery, DBAs will shut down the database and restart it in mount mode in preparation for performing the recovery. Placing a database in mount mode ensures that no users are connecting to the database and that no transactions are transpiring.

Also, if you’re restoring and recovering the SYSTEM tablespace, then you must start the database in mount mode. Oracle doesn’t allow for restoring and recovering the SYSTEM tablespace data files while the database is open. This next example restores the SYSTEM tablespace while the database is in mount mode:

$ rman target /
RMAN> shutdown immediate;
RMAN> startup mount;
RMAN> restore tablespace system;
RMAN> recover tablespace system;
RMAN> alter database open;

If successful, the last message you should see is this:

Statement processed

Restoring Read-Only Tablespaces

RMAN will restore read-only tablespaces along with the rest of the database when you issue a RESTORE DATABASE command. For example, the following command will restore all data files (including those in read-only mode):

RMAN> restore database;

Prior to Oracle Database 11g, you were required to issue RESTORE DATABASE CHECK READONLY to instruct RMAN to restore read-only tablespaces along with tablespaces in read-write mode. This is no longer a requirement in Oracle Database 11g and higher.

image Note   If you are using a backup that was created after the read-only tablespace was placed in read-only mode, then no recovery is necessary for the read-only data files. In this situation no redo has been generated for the read-only tablespace since it was backed up.

Restoring Temporary Tablespaces

Starting with Oracle Database 10g, you don’t have to restore or re-create missing locally managed temporary tablespace temp files. When you open your database for use, Oracle automatically detects and re-creates locally managed temporary tablespace temp files.

When Oracle automatically re-creates a temporary tablespace, it will log a message to your target database alert.log  such as this:

Re-creating tempfile <your temporary tablespace filename>

If, for any reason, your temporary tablespace becomes unavailable, you can also re-create it yourself. Because there are never any permanent objects in temporary tablespaces, you can simply re-create them as needed. Here is an example of how to create a locally managed temporary tablespace:

CREATE TEMPORARY TABLESPACE temp TEMPFILE
'/u01/dbfile/o12c/temp01.dbf' SIZE 1000M
EXTENT MANAGEMENT
LOCAL UNIFORM SIZE 512K;

If your temporary tablespace exists, but the temporary data files are missing, you can just add them, as shown:

alter tablespace temp
add tempfile '/u01/dbfile/o12c/temp02.dbf' SIZE 5000M REUSE;

Restoring and Recovering Data Files

A data file–level restore and recovery works well when a media failure is confined to a small set of data files. With data file–level recoveries, you can instruct RMAN to restore and recover either with data file name or data file number. For data files not associated with the SYSTEM or UNDO tablespaces, you have the option of restoring and recovering while the database remains open. While the database is open, however, you must first take offline any data files being restored and recovered.

Restoring and Recovering Data Files While the Database Is Open

Use the RESTORE DATAFILE and RECOVER DATAFILE commands to restore and recover at the data file level. When your database is open, you’re required to take offline any data files that you’re attempting to restore and recover. This example restores and recovers data files while the database is open:

RMAN> sql 'alter database datafile 4, 5 offline';
RMAN> restore datafile 4, 5;
RMAN> recover datafile 4, 5;
RMAN> sql 'alter database datafile 4, 5 online';

image Tip   Use the RMAN REPORT SCHEMA command to list data file names and file numbers. You can also query the NAME and FILE# columns of V$DATAFILE to take names and numbers.

You can also specify the name of the data file that you want to restore and recover; for example,

RMAN> sql "alter database datafile ''/u01/dbfile/o12c/users01.dbf'' offline";
RMAN> restore datafile '/u01/dbfile/o12c/users01.dbf';
RMAN> recover datafile '/u01/dbfile/o12c/users01.dbf';
RMAN> sql "alter database datafile ''/u01/dbfile/o12c/users01.dbf'' online";

image Note   When using the RMAN sql command, if there are single quotation marks within the SQL statement, then you are required to use double quotation marks to enclose the entire SQL statement and two single quotation marks where you would ordinarily use just one quotation double mark.

As mentioned earlier, starting with Oracle Database 12c, you can run SQL commands directly, without the RMAN sql command and associated quotation marks; for example,

RMAN> alter database datafile 4 offline;
RMAN> restore datafile 4;
RMAN> recover datafile 4;
RMAN> alter database datafile 4 online;

Here are the corresponding 12c examples, with the data file names:

RMAN> alter database datafile '/u01/dbfile/o12c/users01.dbf' offline;
RMAN> restore datafile '/u01/dbfile/o12c/users01.dbf';
RMAN> recover datafile '/u01/dbfile/o12c/users01.dbf';
RMAN> alter database datafile '/u01/dbfile/o12c/users01.dbf' online;

Restoring and Recovering Data Files While the Database Is Not Open

In this scenario the database is first shut down and then started in mount mode. You can restore and recover any data file in your database while the database is not open. This example shows the restoring of data file 1, which is associated with the SYSTEM tablespace:

$ rman target /
RMAN> shutdown abort;
RMAN> startup mount;
RMAN> restore datafile 1;
RMAN> recover datafile 1;
RMAN> alter database open;

You can also specify the file name when performing a data file recovery:

$ rman target /
RMAN> shutdown abort;
RMAN> startup mount;
RMAN> restore datafile '/u01/dbfile/o12c/system01.dbf';
RMAN> recover datafile '/u01/dbfile/o12c/system01.dbf';
RMAN> alter database open;

Restoring Data Files to Nondefault Locations

Sometimes a failure will occur that renders the disks associated with a mount point inoperable. In these situations, you will need to restore and recover the data files to a location different from the one where they originally resided. Another typical need for restoring data files to nondefault locations is that you’re restoring to a different database server, on which the mount points are completely different from those of the server on which the backup originated.

Use the SET NEWNAME and SWITCH commands to restore data files to nondefault locations. Both of these commands must be run from within an RMAN run{} block. You can think of using SET NEWNAME and SWITCH as a way to rename data files (similar to the SQL*Plus ALTER DATABASE RENAME FILE statement).

This example changes the location of data files when doing a restore and recover. First, place the database in mount mode:

$ rman target /
RMAN> startup mount;

Then, run the following block of RMAN code:

run{
set newname for datafile 4 to '/u02/dbfile/o12c/users01.dbf';
set newname for datafile 5 to '/u02/dbfile/o12c/users02.dbf';
restore datafile 4, 5;
switch datafile all; # Updates repository with new datafile location.
recover datafile 4, 5;
alter database open;
}

This is a partial listing of the output:

datafile 4 switched to datafile copy
input datafile copy RECID=79 STAMP=804533148 file name=/u02/dbfile/o12c/users01.dbf
datafile 5 switched to datafile copy
input datafile copy RECID=80 STAMP=804533148 file name=/u02/dbfile/o12c/users02.dbf

If the database is open, you can place the data files offline and then set their new names for restore and recovery, as follows:

run{
sql 'alter database datafile 4, 5 offline';
set newname for datafile 4 to '/u02/dbfile/o12c/users01.dbf';
set newname for datafile 5 to '/u02/dbfile/o12c/users02.dbf';
restore datafile 4, 5;
switch datafile all; # Updates repository with new datafile location.
recover datafile 4, 5;
sql 'alter database datafile 4, 5 online';
}

Starting with Oracle Database 12c, you no longer need to specify the RMAN sql command when running SQL statements, such as ALTER DATABASE; for example,

run{
alter database datafile 4, 5 offline;
set newname for datafile 4 to '/u02/dbfile/o12c/users01.dbf';
set newname for datafile 5 to '/u02/dbfile/o12c/users02.dbf';
restore datafile 4, 5;
switch datafile all; # Updates repository with new datafile location.
recover datafile 4, 5;
alter database datafile 4, 5 online;
}

Performing Block-Level Recovery

Block-level corruption is rare and is usually caused by some sort of I/O error. However, if you do have an isolated corrupt block within a large data file, it’s nice to have the option of performing a block-level recovery. Block-level recovery is useful when a small number of blocks are corrupt within a data file. Block recovery is not appropriate if the entire data file needs media recovery.

RMAN will automatically detect corrupt blocks whenever a B ACKUP, V ALIDATE, or B ACKUP VALIDATE command is run. Details on corrupt blocks can be viewed in the V$DATABASE_BLOCK_CORRUPTION view. In the following example the regular backup job has reported a corrupt block in the output:

ORA-19566: exceeded limit of 0 corrupt blocks for file...

Querying the V$DATABASE_BLOCK_CORRUPTION view indicates which file contains corruption:

SQL> select * from v$database_block_corruption;
 
     FILE#     BLOCK#     BLOCKS CORRUPTION_CHANGE# CORRUPTIO     CON_ID
---------- ---------- ---------- ------------------ --------- ----------
         4         20          1                  0 ALL ZERO           0

Your database can be either mounted or open when performing block-level recovery. You do not have to take offline the data file being recovered. You can instruct RMAN to recover all blocks reported in V $DATABASE_BLOCK_CORRUPTION, as shown:

RMAN> recover corruption list;

If successful, the following message is displayed:

media recovery complete...

Another way to recover the block is to specify the data file and block number, like so:

RMAN> recover datafile 4 block 20;

It’s preferable to use the RECOVER CORRUPTION LIST syntax because it will clear out any blocks recovered from the V $DATABASE_BLOCK_CORRUPTION view.

image Note   RMAN can’t perform block-level recovery on block 1 (data file header) of the data file.

Block-level media recovery allows you to keep your database available and also reduces the mean time to recovery, as only the corrupt blocks are offline during the recovery. Your database must be in archivelog mode for performing block-level recoveries. Starting with Oracle Database 11g, RMAN can restore the block from the flashback logs (if available). If the flashback logs are not available, then RMAN will attempt to restore the block from a full backup, a level-0 backup, or an image copy backup generated by the B ACKUP AS COPY command. After the block has been restored, any required archived redo logs must be available to recover the block. RMAN can’t perform block media recovery using incremental level-1 (or higher) backups.

image Note   If you’re using Oracle Database 10g or Oracle9i Database, use the B LOCKRECOVER command to perform block media recovery. Block-level recovery is not available in Oracle version 8.

Restoring a Container Database and Its Associated Pluggable Databases

Starting with Oracle Database 12c, you can create pluggable databases within one container database (see Chapter 23 for details). When dealing with container and associated pluggable databases, there are three basic scenarios:

  • All data files have experienced media failure (container root data files as well as all associated pluggable database data files).
  • Just the data files associated with the container root database have experienced media failure.
  • Only data files associated with a pluggable database have experienced media failure.

The prior scenarios are covered in the following sections.

Restoring and Recovering All Data Files

To restore and recover all data files associated with a container database (this includes the root container, the seed container, and all associated pluggable databases), use RMAN to connect to the container database as a user with sysdba or sysbackup privileges. Because the data files associated with the root system tablespace are being restored, the database must be started in mount mode (and not open):

$ rman target /
RMAN> startup mount;
RMAN> restore database;
RMAN> recover database;
RMAN> alter database open;

Keep in mind that when you open a container database, this does not, by default, open the associated pluggable databases. You can do that from the root container, as follows:

RMAN> alter pluggable database all open;

Restoring and Recovering Root Container Data Files

If just data files associated with the root container have been damaged, then you can restore and recover at the root level. In this example the root container’s system data file is being restored, so the database must not be open. The following commands instruct RMAN to restore only the data files associated with the root container database, via the keyword root:

$ rman target /
RMAN> startup mount;
RMAN> restore database root;
RMAN> recover database root;
RMAN> alter database open;

In the prior code the restore database root command instructs RMAN to restore only data files associated with the root container database. After the container database is opened, you must open any associated pluggable databases. You can do so from the root container, as shown:

RMAN> alter pluggable database all open;

You can check the status of your pluggable databases via this query:

SQL> select name, open_mode from v$pdbs;

Restoring and Recovering a Pluggable Database

You have two options for restoring and recovering a pluggable database:

  • Connect as the container root user, and specify the pluggable database to be restored and recovered.
  • Connect directly to the pluggable database as a privileged pluggable-level user, and issue RESTORE and RECOVER commands.

This first example connects to the root container and restores and recovers the data files associated with the salespdb pluggable database. For this to work, the pluggable database must not be open (because the pluggable database’s system data files are also being restored and recovered):

$ rman target /
RMAN> alter pluggable database salespdb close;
RMAN> restore pluggable database salespdb;
RMAN> recover pluggable database salespdb;
RMAN> alter pluggable database salespdb open;

You can also connect directly to a pluggable database and perform restore and recovery operations. When connected directly to the pluggable database, the user only has access to the data files associated with the pluggable database:

$ rman target sys/foo@salespdb
RMAN> shutdown immediate;
RMAN> restore database;
RMAN> recover database;
RMAN> alter database open;

image Note   When you’re connected directly to a pluggable database, you can’t specify the name of the pluggable database as part of the RESTORE and RECOVER commands. In this situation, you’ll get an error indicating the operation isn’t allowed while connected to a pluggable database.

The prior code only affects data files associated with the pluggable database to which you are connected. The pluggable database needs to be closed for this to work. However, the root container database can be open or mounted. Also, you must use a backup that was taken while connected to the pluggable database as a privileged user. The privileged pluggable database user can’t access backups of data files initiated by the root container database privileged user.

Restoring Archive Redo Log Files

RMAN will automatically restore any archived redo log files that it needs during a recovery process. You normally don’t need to restore archived redo log files manually. However, you may want to do so if any of the following situations apply:

  • You need to restore archived redo log files in anticipation of later performing a recovery; the idea is that if the archived redo log files are already restored, it will speed the recovery operation.
  • You’re required to restore the archived redo log files to a nondefault location, either because of media failure or because of storage space issues.
  • You need to restore specific archived redo log files in order to inspect them via LogMiner.

If you’ve enabled an FRA, then RMAN will, by default, restore archived redo log files to the destination defined by the initialization parameter DB_RECOVERY_FILE_DEST. Otherwise, RMAN uses the LOG_ARCHIVE_DEST_N initialization parameter (where N is usually 1) to determine where to restore the archived redo log files.

If you restore archived redo log files to a nondefault location, RMAN knows the location they were restored to and automatically finds these files when you issue any subsequent RECOVER commands. RMAN will not restore archived redo log files that it determines are already on disk. Even if you specify a nondefault location, RMAN will not restore an archived redo log file to disk if the file already exists. In this situation, RMAN simply returns a message stating that the archived redo log file has already been restored. Use the FORCE option to override this behavior.

If you are uncertain of the sequence numbers to use during a restore of log files, you can query the V$LOG_HISTORY view.

image Tip   Keep in mind that you can’t restore an archive redo log that you never backed up. Also, you can’t restore an archive redo log if the backup file containing the archive redo log is no longer available. Run the LIST ARCHIVELOG ALL command to view archive redo logs currently on disk, and LIST BACKUP OF ARCHIVELOG ALL to verify which archive redo log files are in available RMAN backups.

Restoring to the Default Location

The following command will restore all archived redo log files that RMAN has backed up:

RMAN> restore archivelog all;

If you want to restore from a specified sequence, use the FROM SEQUENCE clause. You may want to run this query first to establish the most recent log files and sequence numbers that have been generated:

SQL> select sequence#, first_time from v$log_history order by 2;

This example restores all archived redo log files from sequence 68:

RMAN> restore archivelog from sequence 68;

If you want to restore a range of archived redo log files, use the FROM SEQUENCE and UNTIL SEQUENCE clauses or the SEQUENCE BETWEEN clause, as shown. The following commands restore archived redo log files from sequence 68 through sequence 78, using thread 1:

RMAN> restore archivelog from sequence 68 until sequence 78 thread 1;
RMAN> restore archivelog sequence between 68 and 78 thread 1;

By default, RMAN won’t restore an archived redo log file if it is already on disk. You can override this behavior if you use the FORCE, like so:

RMAN> restore archivelog from sequence 1 force;

Restoring to a Nondefault Location

Use the SET ARCHIVELOG DESTINATION clause if you want to restore archived redo log files to a location different from the default. The following example restores to the nondefault location u01/archtemp. The option of the SET command must be executed from within an RMAN run{} block.

run{
set archivelog destination to '/u01/archtemp';
restore archivelog from sequence 8 force;
}

Restoring a Control File

If you are missing one control file, and you have multiple copies, then you can shut down your database and simply restore the missing or damaged control file by copying a good control file to the correct location and name of the missing control file (see Chapter 5 for details).

Listed next are three typical scenarios when restoring a control file:

  • Using a recovery catalog
  • Using an autobackup
  • Specifying a backup file name

Using a Recovery Catalog

When you’re connected to the recovery catalog, you can view backup information about your control files even while your target database is in nomount mode. To list backups of your control files, use the LIST command, as shown:

$ rman target / catalog rcat/foo@rcat
RMAN> startup nomount;
RMAN> list backup of controlfile;

If you’re missing all your control files, and you’re using a recovery catalog, then issue the STARTUP NOMOUNT and the RESTORE CONTROLFILE commands:

RMAN> startup nomount;
RMAN> restore controlfile;

RMAN restores the control files to the location defined by your CONTROL_FILES initialization parameter. You should see a message indicating that your control files have been successfully copied back from an RMAN backup piece. You can now alter your database into mount mode and perform any additional restore and recovery commands required for your database.

image Note   When you restore a control file from a backup, you’re required to perform media recovery on your entire database and open your database with the OPEN RESETLOGS command, even if you didn’t restore any data files. You can determine whether your control file is a backup by querying the CONTROLFILE_TYPE column of the V$DATABASE view.

Using an Autobackup

When you enable the autobackup of your control file and are using an FRA, restoring your control file is fairly simple. First, connect to your target database, then issue a STARTUP NOMOUNT command, followed by the RESTORE CONTROLFILE FROM AUTOBACKUP command, like this:

$ rman target /
RMAN> startup nomount;
RMAN> restore controlfile from autobackup;

RMAN restores the control files to the location defined by your CONTROL_FILES initialization parameter. You should see a message indicating that your control files have been successfully copied back from an RMAN backup piece. Here is a snippet of the output:

channel ORA_DISK_1: control file restore from AUTOBACKUP complete

You can now alter your database into mount mode and perform any additional restore and recovery commands required for your database.

Specifying a Backup File Name

When restoring a database to a different server, these are generally the first few steps in the process take a backup of the target database, copy to the remote server, and then restore the control file from the RMAN backup. In these scenarios, I usually know the name of the backup piece that contains the control file. Here is an example in which you instruct RMAN to restore a control file from a specific backup piece file:

RMAN> startup nomount;
RMAN> restore controlfile from
'/u01/O12C/rman/rman_ctl_c-3423216220-20130113-01.bk';

The control file will be restored to the location defined by the CONTROL_FILES initialization parameter.

Restoring the spfile

You might want to restore a spfile for several different reasons:

  • You accidentally set a value in the spfile that keeps your instance from starting.
  • You accidentally deleted the spfile.
  • You are required to see what the spfile looked like at some point in time in the past.

One scenario (this has happened to me more than once) is that you’re using a spfile, and one of the DBAs on your team does something inexplicable, such as this:

SQL> alter system set processes=1000000 scope=spfile;

The parameter is changed in the spfile on disk, but not in memory. Sometime later, the database is stopped for some maintenance. When attempting to start the database, you can’t even get the instance to start in a nomount state. This is because a parameter has been set to a ridiculous value that will consume all the memory on the box. In this scenario the instance may hang, or you may see one or more of the following messages:

ORA-01078: failure in processing system parameters
ORA-00838: Specified value of ... is too small

If you have an RMAN backup available that has a copy of the spfile as it was before it was modified, you can simply restore the spfile. If you are using a recovery catalog, here is the procedure for restoring the spfile:

$ rman target / catalog rcat/foo@rcat
RMAN> startup nomount;
RMAN> restore spfile;
  • If you’re not using a recovery catalog, there are a number of ways to restore your spfile. The approach you take depends on several variables, such as whether you’re using an FRA
  • you’ve configured a channel backup location for the autobackup
  • you’re using the default location for autobackups

I’m not going to show every detail of these scenarios. Usually, I determine the location of the backup piece that contains the backup of the spfile and do the restore, like this:

RMAN> startup nomount force;
RMAN> restore spfile to '/tmp/spfile.ora'
      from '/u01/O12C/rman/rman_ctl_c-3423216220-20130113-00.bk';

You should see a message such as this:

channel ORA_DISK_1: SPFILE restore from AUTOBACKUP complete

In this example the spfile is restored to the /tmp directory. Once restored, you can copy the spfile to ORACLE_HOME/dbs, with the proper name. For my environment (database name: o12c) this would be as follows:

$ cp /tmp/spfile.ora $ORACLE_HOME/dbs/spfileo12c.ora

image Note   For a complete description of all possible spfile and control file restore scenarios, see RMAN Recipes for Oracle Database 12c, second edition, by Darl Kuhn (Apress, 2013).

Incomplete Recovery

The term incomplete database recovery means that you can’t recover all committed transactions. Incomplete means that you do not apply all redo to restore up to the point of the last committed transaction that occurred in your database. In other words, you are restoring and recovering to a point in time in the past. For this reason, incomplete database recovery is also called database point-in-time recovery (DBPITR). Typically, you perform incomplete database recovery for one of the following reasons:

  • You don’t have all the redo required to perform a complete recovery. You’re missing either the archived redo log files or the online redo log files that are required for complete recovery. This situation could arise because the required redo files are damaged or missing.
  • You purposely want to roll back the database to a point in time in the past. For example, you would do this if somebody accidentally truncated a table, and you intentionally wanted to roll back the database to just before the truncate table command was issued.

Incomplete database recovery consists of two : restore and recovery. The restore step re-creates data files, and the recover step applies redo up to the specified point in time. The restore process can be initiated from RMAN in a couple of different ways:

  • RESTORE DATABASE UNTIL
  • FLASHBACK DATABASE

For the majority of incomplete database recovery circumstances, you use the RESTORE DATABASE UNTIL command to instruct RMAN to retrieve data files from the RMAN backup files. This type of incomplete database recovery is the main focus of this section of the chapter. The Flashback Database feature is covered in the section “Flashing Back a Database, ” later in this chapter.

The UNTIL portion of the R ESTORE DATABASE command instructs RMAN to retrieve data files from a point in time in the past, based on one of the following methods:

  • Time
  • SCN
  • Log sequence number
  • Restore point

The RMAN RESTORE DATABASE UNTIL command will retrieve all data files from the most recent backup set or image copy. RMAN will automatically determine from the UNTIL clause which backup set contains the required data files. If you omit the UNTIL clause of the R ESTORE DATABASE command, RMAN will retrieve data files from the latest available backup set or image copy. In some situations this may be the behavior you desire. I recommend that you use the UNTIL clause to ensure that RMAN restores from the correct backup set. When you issue the RESTORE DATABASE UNTIL command, RMAN will establish how to extract the data files from any of the following types of backups:

  • Full database backup
  • Incremental level-0 backup
  • Image copy backup generated by the B ACKUP AS COPY command

You can’t perform an incomplete database recovery on a subset of your database’s online data files. When performing incomplete database recovery, all the checkpoint SCNs for all online data files must be synchronized before you can open your database with the ALTER DATABASE OPEN RESETLOGS command. You can view the data file header SCNs and the status of each data file via this SQL query:

select file#, status, fuzzy,
error, checkpoint_change#,
to_char(checkpoint_time,'dd-mon-rrrr hh24:mi:ss') as checkpoint_time
from v$datafile_header;

image Note   The FUZZY column V$DATAFILE_HEADER contains data files that have one or more blocks with an SCN value greater than or equal to the checkpoint SCN in the data file header. If a data file is restored and has a FUZZY value of YES, then media recovery is required.

The only exception to this rule of not performing an incomplete recovery on a subset of online database files is a tablespace point-in-time recovery (TSPITR), which uses the RECOVER TABLESPACE UNTIL command. TSPITR is used in rare situations; it restores and recovers only the tablespace(s) you specify. For more details on TSPITR, see RMAN Recipes for Oracle Database 12c.

The recovery portion of an incomplete database recovery is always initiated with the R ECOVER DATABASE UNTIL command. RMAN will automatically recover your database up to the point specified with the UNTIL clause. Just like the RESTORE command, you can recover up to time, change/SCN, log sequence number, or restore point. When RMAN reaches the specified point, it will automatically terminate the recovery process.

image Note   Regardless of what you specify in the UNTIL clause, RMAN will convert that into a corresponding UNTIL SCN clause and assign the appropriate SCN. This is to avoid any timing issues, particularly those caused by Daylight Saving Time.

During a recovery, RMAN will automatically determine how to apply redo. First, RMAN will apply any incremental backups available. Next, any archived redo log files on disk will be applied. If the archived redo log files do not exist on disk, then RMAN will attempt to retrieve them from a backup set. If you want to apply redo as part of an incomplete database recovery, the following conditions must be true:

  • Your database is in archivelog mode.
  • You have a good backup of all data files.
  • You have all redo required to restore up to the specified point.

image Tip   Starting with Oracle Database 10g, you can perform parallel media recovery by using the RECOVER DATABASE PARALLEL command.

When performing an incomplete database recovery with RMAN, you must have your database in mount mode. RMAN needs the database in mount mode to be able to read and write to the control file. Also, with an incomplete database recovery, any SYSTEM tablespace data files are always recovered. Oracle will not allow your database to be open while restoring the SYSTEM tablespace data file(s).

image Note   After incomplete database recovery is performed, you are required to open your database with the ALTER DATABASE OPEN RESETLOGS command.

Depending on the scenario, you can use RMAN to perform a variety of incomplete recovery methods. The next section discusses how to determine what type of incomplete recovery to perform.

Determining the Type of Incomplete Recovery

Time-based restore and recovery is commonly used when you know the approximate date and time to which you want to recover your database. For instance, you may know approximately the time you want to stop the recovery process, but not a particular SCN.

Log sequence–based and cancel-based recovery work well in situations in which you have missing or damaged log files. In such scenarios, you can recover only up to your last good archived redo log file.

SCN-based recovery works well if you can pinpoint the SCN at which you want to stop the recovery process. You can retrieve SCN information from views such as V$LOG and V$LOG_HISTORY. You can also use tools such as LogMiner to retrieve the SCN of a particular SQL statement.

Restore point recoveries work only if you have established restore points. In these situations, you restore and recover up to the SCN associated with the specified restore point.

TSPITR is used in situations in which you need to restore and recover just a few tablespaces. You can use RMAN to automate many of the tasks associated with this type of incomplete recovery.

Performing Time-Based Recovery

To restore and recover your database back to a point in time in the past, you can use either the UNTIL TIME clause of the RESTORE and RECOVER commands or the SET UNTIL TIME clause within a run{} block. RMAN will restore and recover the database up to, but not including, the specified time. In other words, RMAN will restore any transactions committed prior to the time specified. RMAN automatically stops the recovery process when it reaches the time you specified.

The default date format that RMAN expects is YYYY-MM-DD:HH24:MI:SS. However, I recommend using the TO_DATE function and specifying a format mask. This eliminates ambiguities with different national date formats and having to set the OS NLS_DATE_FORMAT variable. The following example specifies a time when issuing the restore and recover commands:

$ rman target /
RMAN> startup mount;
RMAN> restore database until time
      "to_date('15-jan-2013 12:20:00', 'dd-mon-rrrr hh24:mi:ss')";
RMAN> recover database until time
      "to_date('15-jan-2013 12:20:00', 'dd-mon-rrrr hh24:mi:ss')";
RMAN> alter database open resetlogs;

If everything goes well, you should see output such as this:

Statement processed

Performing Log Sequence-Based Recovery

Usually this type of incomplete database recovery is initiated because you have a missing or damaged archived redo log file. If that’s the case, you can recover only up to your last good archived redo log file, because you can’t skip a missing archived redo log.

How you determine which archived redo log file to restore up to (but not including) will vary. For example, if you are physically missing an archived redo log file, and RMAN can’t find it in a backup set, you’ll receive a message such as this when trying to apply the missing file:

RMAN-06053: unable to perform media recovery because of missing log
RMAN-06025: no backup of archived log for thread 1 with sequence 19...

Based on the previous error message, you would restore up to (but not including) log sequence 19.

$ rman target /
RMAN> startup mount;
RMAN> restore database until sequence 19;
RMAN> recover database until sequence 19;
RMAN> alter database open resetlogs;

If successful, you should see output such as this:

Statement processed

image Note   Log sequence–based recovery is similar to user-managed cancel-based recovery. See Chapter 16 for details on a user-managed cancel-based recovery.

Performing SCN-Based Recovery

SCN-based incomplete database recovery works in situations in which you know the SCN value at which you want to end the restore-and-recovery session. RMAN will recover up to, but not including, the specified SCN. RMAN automatically terminates the restore process when it reaches the specified SCN.

You can view your database SCN information in several ways:

  • Using LogMiner to determine an SCN associated with a DDL or DML statement
  • Looking in the alert.log file
  • Looking in your trace files
  • Querying the FIRST_CHANGE# column of V$LOG, V$LOG_HISTORY and V$ARCHIVED_LOG

After establishing the SCN to which you want to restore, use the U NTIL SCN clause to restore up to, but not including, the SCN specified. The following example restores all transactions that have an SCN that is less than 95019865425:

$ rman target /
RMAN> startup mount;
RMAN> restore database until scn 95019865425;
RMAN> recover database until scn 95019865425;
RMAN> alter database open resetlogs;

If everything goes well, you should see output such as this:

Statement processed

Restoring to a Restore Point

There are two types of restore points: normal and guaranteed. The main difference between a guaranteed restore point and a normal restore point is that a guaranteed restore point is not eventually aged out of the control file; a guaranteed restore point will persist until you drop it. Guaranteed restore points do require an FRA. However, for incomplete recovery using a guaranteed restore point, you do not have to have flashback database enabled.

You can create a normal restore point using SQL*Plus, as follows:

SQL> create restore point MY_RP;

This command creates a restore point, named MY_RP, that is associated with the SCN of the database at the time the command was issued. You can view the current SCN of your database, as shown:

SQL> select current_scn from v$database;

You can view restore point information in the V$RESTORE_POINT view, like so:

SQL> select name, scn from v$restore_point;

The restore point acts like a synonym for the particular SCN. The restore point allows you to restore and recover to an SCN without having to specify a number. RMAN will restore and recover up to, but not including, the SCN associated with the restore point.

This example restores and recovers to the MY_RP restore point:

$ rman target /
RMAN> startup mount;
RMAN> restore database until restore point MY_RP;
RMAN> recover database until restore point MY_RP;
RMAN> alter database open resetlogs;

Restoring Tables to a Previous Point

Starting with Oracle Database 12c, you can restore individual tables from RMAN backups via the RECOVER TABLE command. This gives you with the ability to restore and recover a table back to a point in time in the past.

The table-level restore feature uses a temporary auxiliary instance and the Data Pump utility. Both the auxiliary instance and Data Pump create temporary files when restoring the table. Before initiating a table-level restore, first create two directories: one to hold files used by the auxiliary instance and one to store a Data Pump dump file:

$ mkdir /tmp/oracle
$ mkdir /tmp/recover

The prior two directories are referenced within the RECOVER TABLE command via the AUXILIARY DESTINATION and DATAPUMP DESTINATION clauses. In the following bit of code, the INV table, owned by MV_MAINT, is restored as it was at a prior SCN:

recover table mv_maint.inv
until scn 4689805
auxiliary destination '/tmp/oracle'
datapump destination '/tmp/recover';

Providing that RMAN backups are available that contain the state of the table at the specified SCN, a table-level restore and recovery is performed.

image Note   You can also restore a table to an SCN, a point in time, or a log sequence number.

When RMAN performs a table-level recovery, it automatically creates a temporary auxiliary database, uses Data Pump to export the table, and then imports the table back into the target database as it was at the specified restore point. After the restore is finished, the auxiliary database is dropped, and Data Pump dump file is removed.

image Tip   Although the RECOVER TABLE command is a nice enhancement, I would recommend that, if you have an accidentally dropped table, you first explore using the Flashback Table to Before Drop feature to restore the table. Or, if the table was erroneously deleted from, then use the Flashback Table feature to restore the table back to a point in time in the past. If neither of the prior options are viable, then consider using the RMAN Recover Table feature.

Flashing Back a Table

Prior to Oracle Database 10g, if a table was accidentally dropped, you had to do the following to restore the table:

  1. Restore a backup of the database to a test database.
  2. Perform an incomplete recovery up to the point in time at which the table was dropped.
  3. Export the table.
  4. Import the table into the production database.

This process can be time-consuming and resource intensive. It requires extra server resources as well as time and effort from a DBA.

To  simplify recovery of an accidentally dropped table, Oracle introduced the Flashback Table feature. Oracle offers two different types of Flashback Table operations:

  • FLASHBACK TABLE TO BEFORE DROP quickly undrops a previously dropped table. This feature uses a logical container named the recycle bin.
  • FLASHBACK TABLE flashes back to a recent point in time to undo the effects of undesired DML statements. You can flash back to an SCN, a timestamp, or a restore point.

Oracle introduced FLASHBACK TABLE TO BEFORE DROP to allow you to quickly recover a dropped table. As of Oracle Database 10g, when you drop a table, if you don’t specify the PURGE clause, Oracle doesn’t drop the table—instead, the table is renamed. Any tables you drop (that Oracle renames) are placed in the recycle bin. The recycle bin provides you with an efficient way to view and manage dropped objects.

image Note   To use the Flashback Table feature, you don’t need to implement an FRA, nor do you need Flashback Database to be enabled.

The FLASHBACK TABLE TO BEFORE DROP operation only works if your database has the recycle bin feature enabled (which it is by default). You can check the status of the recycle bin, as follows:

SQL> show parameter recyclebin
 
NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
recyclebin                           string      on

FLASHBACK TABLE TO BEFORE DROP

When you drop a table, if you don’t specify the PURGE clause, Oracle renames the table with a system-generated name. Because the table isn’t really dropped, you can use FLASHBACK TABLE TO BEFORE DROP to instruct Oracle to rename the table with its original name. Here is an example. Suppose the INV table is accidentally dropped:

SQL> drop table inv;

Verify that the table has been renamed by viewing the contents of the recycle bin:

SQL> show recyclebin;
ORIGINAL NAME    RECYCLEBIN NAME                OBJECT TYPE  DROP TIME
---------------- ------------------------------ ------------ -------------------
INV              BIN$0zIqhEFlcprgQ4TQTwq2uA==$0 TABLE        2013-01-11:12:16:49

The SHOW RECYCLEBIN statement shows only tables that have been dropped. To get a more complete picture of renamed objects, query the RECYCLEBIN view:

select object_name, original_name, type
from recyclebin;

Here is the output:

OBJECT_NAME                         ORIGINAL_NAM TYPE
----------------------------------- ------------ -------------------------
BIN$0zIqhEFjcprgQ4TQTwq2uA==$0      INV_PK       INDEX
BIN$0zIqhEFkcprgQ4TQTwq2uA==$0      INV_TRIG     TRIGGER
BIN$0zIqhEFlcprgQ4TQTwq2uA==$0      INV          TABLE

In this output the table also has a primary key that was renamed when the object was dropped. To undrop the table, do this:

SQL> flashback table inv to before drop;

The prior command restores the table to its original name. This statement, however, doesn’t restore the index to its original name:

SQL> select index_name from user_indexes where table_name='INV';
 
INDEX_NAME
-------------------------------------------------
BIN$0zIqhEFjcprgQ4TQTwq2uA==$0

In this scenario, you have to rename the index:

SQL> alter index "BIN$0zIqhEFjcprgQ4TQTwq2uA==$0" rename to inv_pk;

You also have to rename any trigger objects in the same manner. If referential constraints were in place before the table was dropped, you must manually re-create them.

If, for some reason, you need to flash back a table to a name different from the original name, you can do so as follows:

SQL> flashback table inv to before drop rename to inv_bef;

Flashing Back a Table to a Previous Point in Time

If a table was erroneously deleted from, you have the option of flashing back the table to a previous point in time. The Flashback Table feature uses information in the undo tablespace to restore the table. The point in time in the past depends on your undo tablespace retention period, which specifies the minimum time that undo information is kept.

If the required flashback information isn’t in the undo tablespace, you receive an error such as this:

ORA-01555: snapshot too old

In other words, to be able to flash back to a point in time in the past, the required information in the undo tablespace must not have been overwritten.

FLASHBACK TABLE TO SCN

Suppose you’re testing an application feature, and you want to quickly restore a table back to a specific SCN. As part of the application testing, you record the SCN before testing begins:

SQL> select current_scn from v$database;
 
CURRENT_SCN
-----------
   4760099

You perform some testing and then want to flash back the table to the SCN previously recorded. First, ensure that row movement is enabled for the table:

SQL> alter table inv enable row movement;
SQL> flashback table inv to scn 4760089;

The table should now reflect transactions that were committed as of the historical SCN value specified in the FLASHBACK statement.

FLASHBACK TABLE TO TIMESTAMP

You can also flash back a table to a prior point in time. For example, to flash back a table to 15 minutes in the past, first enable row movement, and then use FLASHBACK TABLE :

SQL> alter table inv enable row movement;
SQL> flashback table inv to timestamp(sysdate-1/96) ;

The timestamp you provide must evaluate to a valid format for an Oracle timestamp. You can also explicitly specify a time, as follows:

SQL> flashback table inv to timestamp
     to_timestamp('14-jan-13 12:07:33','dd-mon-yy hh24:mi:ss'),

FLASHBACK TABLE TO RESTORE POINT

A restore point is a name associated with a timestamp or an SCN in the database. You can create a restore point that contains the current SCN of the database, as shown:

SQL> create restore point point_a;

Later, if you decide to flash back a table to that restore point, first enable row movement:

SQL> alter table inv enable row movement;
SQL> flashback table inv to restore point point_a;

The table should now contain transactions as they were at the SCN associated with the specified restore point.

Flashing Back a Database

The Flashback Database feature allows you to perform an incomplete recovery back to a point in time in the past. Flashback Database uses information stored in flashback logs; it doesn’t rely on restoring database files (as do cold backup, hot backup, and RMAN).

image Tip   Flashback Database isn’t a substitute for a backup of your database. If you experience a media failure with a data file, you can’t use Flashback Database to flash back to before the failure. If a data file is damaged, you have to restore and recover, using a physical backup (hot, cold, or RMAN).

The Flashback Database feature may be desirable in situations in which you want to consistently reset your database back to a point in time in the past. For instance, you may periodically want to set a test or training database back to a known baseline. Or, you may be upgrading an application and, before making large-scale changes to the application database objects, mark the starting point. After the upgrade, if things don’t go well, you want the ability to quickly reset the database back to the point in time before the upgrade took place.

There are several prerequisites for Flashback Database:

  • The database must be in archivelog mode.
  • You must be using an FRA.
  • The Flashback Database feature must be enabled.

See Chapter 5 for details on enabling archivelog mode and/or enabling an FRA. You can verify the status of these features using the following SQL*Plus statements:

SQL> archive log list;
SQL> show parameter db_recovery_file_dest;

To enable the Flashback Database feature, alter your database into flashback mode, as shown:

SQL> alter database flashback on;

image Note   In Oracle Database 10g the database must be in mount mode to enable Flashback Database.

You can verify the flashback status, as follows:

SQL> select flashback_on from v$database;

After you enable Flashback Database, you can view the flashback logs in your FRA with this query:

select name, log#, thread#, sequence#, bytes
from v$flashback_database_logfile;

The range of time in which you can flash back is determined by the D B_FLASHBACK_RETENTION_TARGET parameter. This specifies the upper limit, in minutes, of how far your database can be flashed back.

You can view the oldest SCN and time you can flash back your database to by running the following SQL:

select
 oldest_flashback_scn
,to_char(oldest_flashback_time,'dd-mon-yy hh24:mi:ss')
from v$flashback_database_log;

If, for any reason, you need to disable Flashback Database, you can turn it off, as follows:

SQL> alter database flashback off;

You can use either RMAN or SQL*Plus to flash back a database. You can specify a point in time in the past, using one of the following:

  • SCN
  • Timestamp
  • Restore point
  • Last RESETLOGS operation (works from RMAN only)

This example creates a restore point:

SQL> create restore point flash_1;

Next, the application performs some testing, after which the database is flashed back to the restore point so that a new round of testing can begin:

SQL> shutdown immediate;
SQL> startup mount;
SQL> flashback database to restore point flash_1;
SQL> alter database open resetlogs;

At this point, your database should be transactionally consistent with how it was at the SCN associated with the restore point.

Restoring and Recovering to Different Server

When you think about architecting your backup strategy, as part of the process, you must also consider how you’re going to restore and recover. Your backups are only as good as the last time you tested a restore and recovery. A backup strategy can be rendered worthless without a good restore-and-recovery strategy. The last thing you want to happen is to have a media failure, go to restore your database, and then find out you’re missing critical pieces, you don’t have enough space to restore, something is corrupt, and so on.

One of the best ways to test an RMAN backup is to restore and recover it to a different database server. This will exercise all your backup, restore, and recovery DBA skills. If you can restore and recover an RMAN backup on a different server, it will give you confidence when a real disaster hits. You can think of all the prior material in this book as the building blocks for performing technically challenging tasks. Moving a database from one server to another using an RMAN backup requires an expert level understanding of the Oracle architecture and how B&R works.

image Note   RMAN does have a D UPLICATE DATABASE command, which works well for copying a database from one server to another. If you’re going to be performing this type of task often, I would recommend that you use RMAN’s duplicate database functionality. However, you may still have to copy a backup of a database manually from one server to another, especially when the security is such that you can’t directly connect a production server to a development environment. I work with many production databases in which there is no direct access to a production server, so the only way to duplicate a database is by manually copying the RMAN backups from production to a test environment. Starting with Oracle Database 11g Release 2, you can use RMAN to duplicate a database based on backups you copy from the target to the auxiliary server. See MOS note 874352.1 for details on targetless duplication.

In this example the originating server and destination server have different mount points. Listed next are the high-level steps required to take an RMAN backup and use it to recreate a database on a separate server:

  1. Create an RMAN backup on the originating database.
  2. Copy the RMAN backup to the destination server. All steps that follow are performed on the destination database server.
  3. Ensure that Oracle is installed.
  4. Source the required OS variables.
  5. Create an init.ora file for the database to be restored.
  6. Create any required directories for data files, control files, and dump/trace files.
  7. Start up the database in nomount mode.
  8. Restore the control file from the RMAN backup.
  9. Start up the database in mount mode.
  10. Make the control file aware of the location of the RMAN backups.
  11. Rename and restore the data files to reflect new directory locations.
  12. Recover the database.
  13. Set the new location for the online redo logs.
  14. Open the database.
  15. Add the temp file.
  16. Rename the database (optional).

Each of the prior steps is covered in detail in the next several sections. Steps 1 and 2 occur on the source database server. All remaining steps are performed on the destination server. For this example the source database is named o12c, and the destination database will be named DEVDB.

Furthermore, the originating server and destination server have different mount point names. On the source database the data files and control files are here:

/u01/dbfile/o12c

On the destination database the data files and control files will be renamed and restored to this directory:

/ora01/dbfile/DEVDB

The destination database online redo logs will be placed in this directory:

/ora01/oraredo/DEVDB

The destination database archive redo log file location will be set as follows:

/ora01/arc/DEVDB

Keep in mind that these are the directories used on servers in my test environment. You’ll have to adjust these directory names to reflect the directory structures on your database servers.

Step 1. Create an RMAN Backup on the Originating Database

When backing up a database, make sure you have the autobackup control file feature turned on. Also, include the archive redo logs as part of the backup, like so:

RMAN> backup database plus archivelog;

You can verify the names and locations of the backup pieces via the LIST BACKUP command. For example, this is what the backup pieces look like for the source database:

rman1_bonvb2js_1_1.bk
rman1_bqnvb2k5_1_1.bk
rman1_bsnvb2p3_1_1.bk
rman_ctl_c-3423216220-20130113-06.bk

In the prior output the file with the c-3423216220 string in the name is the backup piece that contains the control file. You’ll have to inspect the output of your LIST BACKUP command to determine which backup piece contains the control file. You’ll need to reference that backup piece in step 8.

Step 2. Copy the RMAN Backup to the Destination Server

For this step, use a utility such as rsync or scp to copy the backup pieces from one server to another. This example uses the scp command to copy the backup pieces:

$ scp rman*  oracle@DEVBOX:/ora01/rman/DEVDB

In this example the /ora01/rman/DEVDB directory must be created on the destination server before copying the backup files. Depending on your environment, this step might require copying the RMAN backups twice: once from the production server to a secure server and once from the secure server to a test server.

image Note   If the RMAN backups are on tape instead of on disk, then the same media manager software must be installed/configured on the destination server. Also, that server must have direct access to the RMAN backups on tape.

Step 3. Ensure That Oracle Is Installed

Make sure you have the same version of the Oracle binaries installed on the destination server as you do on the originating database.

Step 4. Source the Required OS Variables

You need to establish the OS variables, such as ORACLE_SID, ORACLE_HOME, and PATH. Typically, the ORACLE_SID variable is initially set to match what it was on the original database. The database name will be changed as part of the last step in this recipe (optional). Here are the settings for ORACLE_SID and ORACLE_HOME on the destination server:

$ echo $ORACLE_SID
o12c
 
$ echo $ORACLE_HOME
/ora01/app/oracle/product/12.1.0.1/db_1

At this point also consider adding the Oracle SID to the oratab file. If you plan on using this database after you’ve replicated it, then you should have an automated method for setting the required OS variables. See Chapter 2 for details on sourcing OS variables in conjunction with the oratab file.

Step 5. Create an init.ora File for the Database to Be Restored

Copy the init.ora file from the original server to the destination server, and modify it so that it matches the destination box in terms of any directory paths. Ensure that you change the parameters, such as the CONTROL_FILES, to reflect the new path directories on the destination server (/ora01/dbfile/DEVDB, in this example).

Initially, the name of the init.ora file is ORACLE_HOME/dbs/inito12c.ora, and the name of the database is o12c. Both will be renamed in a later step. Here are the contents of the init.ora file:

control_files='/ora01/dbfile/DEVDB/control01.ctl',
              '/ora01/dbfile/DEVDB/control02.ctl'
db_block_size=8192
db_name='o12c'
log_archive_dest_1='location=/ora01/arc/DEVDB'
job_queue_processes=10
memory_max_target=300000000
memory_target=300000000
open_cursors=100
os_authent_prefix=''
processes=100
remote_login_passwordfile='EXCLUSIVE'
resource_limit=true
shared_pool_size=80M
sql92_security=TRUE
undo_management='AUTO'
undo_tablespace='UNDOTBS1'
workarea_size_policy='AUTO'

image Note   If this were an Oracle Database 10g example, you would need to set the parameters background_dump_dest, user_dump_dest, core_dump_dest.

Step 6. Create Any Required Directories for Data Files, Control Files, and Dump/Trace Files

For this example the directories /ora01/dbfile/DEVDB and /ora01/oraredo/DEVDB are created:

$ mkdir -p /ora01/dbfile/DEVDB
$ mkdir -p /ora01/oraredo/DEVDB
$ mkdir -p /ora01/arc/DEVDB

Step 7. Start Up the Database in Nomount Mode

You should now be able to start up the database in nomount mode:

$ rman target /
RMAN> startup nomount;

Step 8. Restore the Control File from the RMAN Backup

Next, restore the control file from the backup that was previously copied; for example,

RMAN> restore controlfile from
'/ora01/rman/DEVDB/rman_ctl_c-3423216220-20130113-06.bk';

The control file will be restored to all locations specified by the CONTROL_FILES initialization parameter. Here is some sample output:

channel ORA_DISK_1: restore complete, elapsed time: 00:00:03
output file name=/ora01/dbfile/DEVDB/control01.ctl
output file name=/ora01/dbfile/DEVDB/control02.ctl

Step 9. Start Up the Database in Mount Mode

You should now be able to start up your database in mount mode:

RMAN> alter database mount;

At this point, your control files exist and have been opened, but none of the data files or online redo logs exist yet.

Step 10. Make the Control File Aware of the Location of the RMAN Backups

First, use the CROSSCHECK command to let the control file know that none of the backups or archive redo logs are in the same location that they were in on the original server:

RMAN> crosscheck backup; # Crosscheck backups
RMAN> crosscheck copy;   # Crosscheck image copies and archive logs

Then, use the CATALOG command to make the control file aware of the location and names of the backup pieces that were copied to the destination server.

image Note   Don’t confuse the CATALOG command with the recovery catalog schema. The CATALOG command adds RMAN metadata to the control file, whereas the recovery catalog schema is a user, generally created in a separate database, that can be used to store RMAN metadata.

In this example any RMAN files that are in the /ora01/rman/DEVDB directory will be cataloged in the control file:

RMAN> catalog start with '/ora01/rman/DEVDB';

Here is some sample output:

List of Files Unknown to the Database
=====================================
File Name: /ora01/rman/DEVDB/rman1_bqnvb2k5_1_1.bk
File Name: /ora01/rman/DEVDB/rman1_bonvb2js_1_1.bk
File Name: /ora01/rman/DEVDB/rman_ctl_c-3423216220-20130113-06.bk
File Name: /ora01/rman/DEVDB/rman1_bsnvb2p3_1_1.bk
 
Do you really want to catalog the above files (enter YES or NO)?

Now, type YES (if everything looks okay). You should then be able to use the RMAN LIST BACKUP command to view the newly cataloged backup pieces:

RMAN> list backup;

Step 11. Rename and Restore the Data Files to Reflect New Directory Locations

If your destination server has the exact same directory structure as the original server directories, you can issue the RESTORE command directly:

RMAN> restore database;

However, when restoring data files to locations that are different from the original directories, you’ll have to use the SET NEWNAME command. Create a file that uses an RMAN run{} block that contains the appropriate SET NEWNAME and RESTORE commands. I like to use an SQL script that generates SQL to give me a starting point. Here is a sample script:

set head off feed off verify off echo off pages 0 trimspool on
set lines 132 pagesize 0
spo newname.sql
--
select 'run{' from dual;
--
select
'set newname for datafile ' || file# || ' to ' || '''' || name || '''' || ';'
from v$datafile;
--
select
'restore database;' || chr(10) ||
'switch datafile all;' || chr(10) ||
'}'
from dual;
--
spo off;

After running the script, these are the contents of the newname.sql script that was generated:

run{
set newname for datafile 1 to '/u01/dbfile/o12c/system01.dbf';
set newname for datafile 2 to '/u01/dbfile/o12c/sysaux01.dbf';
set newname for datafile 3 to '/u01/dbfile/o12c/undotbs01.dbf';
set newname for datafile 4 to '/u01/dbfile/o12c/users01.dbf';
restore database;
switch datafile all;
}

Then, modify the contents of the newname.sql script to reflect the directories on the destination database server. Here is what the final newname.sql script looks like for this example:

run{
set newname for datafile 1 to '/ora01/dbfile/DEVDB/system01.dbf';
set newname for datafile 2 to '/ora01/dbfile/DEVDB/sysaux01.dbf';
set newname for datafile 3 to '/ora01/dbfile/DEVDB/undotbs01.dbf';
set newname for datafile 4 to '/ora01/dbfile/DEVDB/users01.dbf';
restore database;
switch datafile all;
}

Now, connect to RMAN, and run the prior script to restore the data files to the new locations:

$ rman target /
RMAN> @newname.sql

Here is a snippet of the output:

datafile 1 switched to datafile copy
input datafile copy RECID=5 STAMP=790357985 file name=/ora01/dbfile/DEVDB/system01.dbf

All the data files have been restored to the new database server. You can use the RMAN REPORT SCHEMA command to verify that the files have been restored and are in the correct locations:

RMAN> report schema;

Here is some sample output:

RMAN-06139: WARNING: control file is not current for REPORT SCHEMA
Report of database schema for database with db_unique_name O12C
List of Permanent Datafiles
===========================
File Size(MB) Tablespace           RB segs Datafile Name
---- -------- -------------------- ------- ------------------------
1    500      SYSTEM               ***     /ora01/dbfile/DEVDB/system01.dbf
2    500      SYSAUX               ***     /ora01/dbfile/DEVDB/sysaux01.dbf
3    800      UNDOTBS1             ***     /ora01/dbfile/DEVDB/undotbs01.dbf
4    50       USERS                ***     /ora01/dbfile/DEVDB/users01.dbf
 
List of Temporary Files
=======================
File Size(MB) Tablespace           Maxsize(MB) Tempfile Name
---- -------- -------------------- ----------- --------------------
1    500      TEMP                 500         /u01/dbfile/o12c/temp01.dbf

From the prior output you can see that the database name and temporary tablespace data file still don’t reflect the destination database (DEVDB). These will be modified in subsequent steps.

Step 12. Recover the Database

Next, you need to apply any archive redo files that were generated during the backup. These should be included in the backup because the ARCHIVELOG ALL clause was used to take the backup. Initiate the application of redo via the RECOVER DATABASE command:

RMAN> recover database;

RMAN will restore and apply as many archive redo logs as it has in the backup pieces and then may throw an error when it reaches an archive redo log that doesn’t exist; for example,

RMAN-06054: media recovery requesting unknown archived log for...

That error message is fine. The recovery process will restore and recover archive redo logs contained in the backups, which should be sufficient to open the database. The recovery process doesn’t know where to stop applying archive redo logs and therefore will continue to attempt to do so until it can’t find the next log. Having said that, now is a good time to verify that your data files are online and not in a fuzzy state:

select file#, status, fuzzy, error, checkpoint_change#,
to_char(checkpoint_time,'dd-mon-rrrr hh24:mi:ss') as checkpoint_time
from v$datafile_header;

Step 13. Set the New Location for the Online Redo Logs

If your source and destination servers have the exact same directory structures, then you don’t need to set a new location for the online redo logs (so you can skip this step).

However, if the directory structures are different, then you’ll need to update the control file to reflect the new directory for the online redo logs. I sometimes use an SQL script that generates SQL to assist with this step:

set head off feed off verify off echo off pages 0 trimspool on
set lines 132 pagesize 0
spo renlog.sql
select
'alter database rename file ' || chr(10)
|| '''' || member || '''' || ' to ' || chr(10) || '''' || member || '''' ||';'
from v$logfile;
spo off;

For this example, here is a snippet of the renlog.sql file that was generated:

alter database rename file
'/u01/oraredo/o12c/redo01a.rdo' to
'/u01/oraredo/o12c/redo01a.rdo';
...
alter database rename file
'/u02/oraredo/o12c/redo03b.rdo' to
'/u02/oraredo/o12c/redo03b.rdo';

The contents of renlog.sql need to be modified to reflect the directory structure on the destination server. Here is what renlog.sql looks like after being edited:

alter database rename file
'/u01/oraredo/o12c/redo01a.rdo' to
'/ora01/oraredo/DEVDB/redo01a.rdo';
...
alter database rename file
'/u02/oraredo/o12c/redo03b.rdo' to
'/ora01/oraredo/DEVDB/redo03b.rdo';

Update the control file by running the renlog.sql script:

SQL> @renlog.sql

You can select from V$LOGFILE to verify that the online redo log names are correct:

SQL> select member from v$logfile;

Here is the output for this example:

/ora01/oraredo/DEVDB/redo01a.rdo
/ora01/oraredo/DEVDB/redo02a.rdo
/ora01/oraredo/DEVDB/redo03a.rdo
/ora01/oraredo/DEVDB/redo01b.rdo
/ora01/oraredo/DEVDB/redo02b.rdo
/ora01/oraredo/DEVDB/redo03b.rdo

Make sure the directories exist on the new server that will contain the online redo logs. For this example, here is the mkdir command:

$ mkdir -p /ora01/oraredo/DEVDB

Step 14. Open the Database

You must open the database with the OPEN RESETLOGS command (because there are no redo logs, and they must be re-created at this point):

SQL> alter database open resetlogs;

If successful, you should see this message:

Statement processed

image Note   Keep in mind that all the passwords from the newly restored copy are as they were in the source database. You may want to change the passwords in a replicated database, especially if it was copied from production.

Step 15. Add the Temp File

When you start your database, Oracle will automatically try to add any missing temp files to the database. Oracle won’t be able to do this if the directory structure on the destination server is different from that of the source server. In this scenario, you will have to add any missing temp files manually. To do this, first take offline the temporary tablespace temp file. The file definition from the originating database is taken offline like so:

SQL> alter database tempfile '/u01/dbfile/o12c/temp01.dbf' offline;
SQL> alter database tempfile '/u01/dbfile/o12c/temp01.dbf' drop;

Next, add a temporary tablespace file to the TEMP tablespace that matches the directory structure of the destination database server:

SQL> alter tablespace temp add tempfile '/ora01/dbfile/DEVDB/temp01.dbf'
     size 100m;

You can run the REPORT SCHEMA command to verify that all files are in the correct locations.

Step 16. Rename the Database

This step is optional. If you need to rename the database to reflect the name for a development or test database, create a trace file that contains the CREATE CONTROLFILE statement, and use it to rename your database.

image Tip   If you don’t rename the database, be careful about connect and resync operations to the same recovery catalog used by the original/source database. This causes confusion in the recovery catalog as to which is the real source database and may jeopardize your ability to recover and restore the real source database.

The steps for renaming your database are as follows:

  1. Generate a trace file that contains the SQL command to recreate the control files:
    SQL> alter database backup controlfile to trace as '/tmp/cf.sql' resetlogs;
  2. Shut down the database:
    SQL> shutdown immediate;
  3. Modify the /tmp/cf.sql trace file; be sure to specify SET DATABASE "<NEW DATABASE NAME>" in the top line of the output:
    CREATE CONTROLFILE REUSE SET DATABASE "DEVDB" RESETLOGS ARCHIVELOG
        MAXLOGFILES 16
        MAXLOGMEMBERS 4
        MAXDATAFILES 1024
        MAXINSTANCES 1
        MAXLOGHISTORY 876
    LOGFILE
      GROUP 1 (
        '/ora01/oraredo/DEVDB/redo01a.rdo',
        '/ora01/oraredo/DEVDB/redo01b.rdo'
      ) SIZE 50M BLOCKSIZE 512,
      GROUP 2 (
        '/ora01/oraredo/DEVDB/redo02a.rdo',
        '/ora01/oraredo/DEVDB/redo02b.rdo'
      ) SIZE 50M BLOCKSIZE 512,
      GROUP 3 (
        '/ora01/oraredo/DEVDB/redo03a.rdo',
        '/ora01/oraredo/DEVDB/redo03b.rdo'
      ) SIZE 50M BLOCKSIZE 512
    DATAFILE
      '/ora01/dbfile/DEVDB/system01.dbf',
      '/ora01/dbfile/DEVDB/sysaux01.dbf',
      '/ora01/dbfile/DEVDB/undotbs01.dbf',
      '/ora01/dbfile/DEVDB/users01.dbf'
    CHARACTER SET AL32UTF8;

    If you don’t specify SET DATABASE in the top line of the prior script, when you run the script (as shown later in this example), you’ll receive an error such as this:

    ORA-01161: database name ... in file header does not match...
  4. Create an init.ora file that matches the new database name:
    $ cd $ORACLE_HOME/dbs
    $ cp init<old_sid>.ora init<new_sid>.ora
    $ cp inito12c.ora initDEVDB.ora
  5. Modify the DB_NAME variable within the new init.ora file (in this example, it’s set to DEVDB):
    db_name='DEVDB'
  6. Set the ORACLE_SID OS variable to reflect the new SID name (in this example, it’s set to DEVDB):
    $ echo $ORACLE_SID
    DEVDB
  7. Start up the instance in nomount mode:
    SQL> startup nomount;
  8. Run the trace file (from step 2) to re-create the control file:
    SQL> @/tmp/cf.sql

    image Note   In this example the control files already exist in the location specified by the CONTROL_FILES initialization parameter; therefore, the REUSE parameter is used in the CREATE CONTROL FILE statement.

  9. Open the database with OPEN RESETLOGS:
    SQL> alter database open resetlogs;

    If successful, you should have a database that is a copy of the original database. All the data files, control files, archive redo logs, and online redo logs are in the new locations, and the database has a new name.

  10. As a last step, ensure that your temporary tablespace exists:
    ALTER TABLESPACE TEMP ADD TEMPFILE '/ora01/dbfile/DEVDB/temp01.dbf'
         SIZE 104857600  REUSE AUTOEXTEND OFF;

image Tip   You can also use the NID utility to change the database name and database identifier (DBID). See MOS note 863800.1 for more details.

Summary

RMAN is an acronym for Recovery Manager. It’s worth noting that Oracle did not name this tool Backup Manager. The Oracle team recognized that although backups are important, the real value of a B&R tool is its ability to restore and recover the database. Being able to manage the recovery process is the critical skill. When a database is damaged and needs to be restored, everybody looks to the DBA to perform a smooth and speedy recovery of the database. Oracle DBAs should use RMAN to protect, secure, and ensure the availability of the company’s data assets.

The restore-and-recovery process is analogous to the healing process involved when you break a bone. Restoring data files from a backup and placing them in their original directories can be likened to setting a bone back to its original position. Recovering a data file is similar to the healing of a broken bone—returning the bone back to the state it was in before it was broken. When you recover data files, you apply transactions (obtained from archive redo and online redo) to transform the restored data files back to the state they were in before the media failure occurred.

RMAN can be used for any type of restore-and-recovery scenario. Depending on the situation, RMAN can be used to restore the entire database, specific data files, control files, server parameter files, archive redo logs, or just specific data blocks. You can instruct RMAN to perform a complete or an incomplete recovery.

The last section in this chapter details how to use RMAN to restore and recover a database to a remote server. I recommend that you periodically attempt this type of recovery in order to exercise your B&R strategy. You will gain much confidence and fully understand B&R internals once you can successfully restore a database to a server that is different from the original.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset