atabase Receive Updates For This Category
Data Guard
Oracle9i Data Guard is the new name for Oracle8i Standby Server, incorporating a large number of new features. In this article I shall only focus on those relevant to the 8220;Oracle9i Database: New Features For Administrators8221; OCP exam. For more detailed information read the Oracle9i Data Guard Concepts and Administration documentation.
- Architecture
- Database Synchronization Options
- Setup No-Data-Divergence
- Setup Primary Database
- Setup Standby Database
- Start Managed Standby Recovery
- Protect Primary Database
- Cancel Managed Standby Recovery
- Activating A Standby Database
- Backup Standby Database
- Database Switchover
- Database Failover
- Automatic Archive Gap Detection
- Background Managed Recovery
- Delayed Redo Application
Architecture
The Oracle9i Data Guard architecture incorporates the following items:
- Primary Database 8211; A production database that is used to create standby databases. The archive logs from the primary database are transfered and applied to standby databases. Each standby can only be associated with a single primary database, but a single primary database can be associated with multiple standby databases.
- Standby Database 8211; A replica of the primary database.
- Log Transport Services 8211; Control the automatic transfer of archive redo log files from the primary database to one or more standby destinations.
- Network Configuration 8211; The primary database is connected to one or more standby databases using Oracle Net.
- Log Apply Services 8211; Apply the archived redo logs to the standby database. The Managed Recovery Process (MRP) actually does the work of maintaining and applying the archived redo logs.
- Role Management Services 8211; Control the changing of database roles from primary to standby. The services include switchover, switchback and failover.
- Data Guard Broker 8211; Controls the creation and monitoring of Data Guard. It comes with a GUI and command line interface.
The services required on the primary database are:
- Log Writer Process (LGWR) 8211; Collects redo information and updates the online redo logs. It can also create local archived redo logs and transmit online redo to standby databases.
- Archiver Process (ARCn) 8211; One or more archiver processes make copies of online redo logs either locally or remotely for standby databases.
- Fetch Archive Log (FAL) Server 8211; Services requests for archive redo logs from FAL clients running on multiple standby databases. Multiple FAL servers can be run on a primary database, one for each FAL request. .
The services required on the standby database are:
- Fetch Archive Log (FAL) Client 8211; Pulls archived redo log files from the primary site. Initiates transfer of archived redo logs when it detects a gap sequence.
- Remote File Server (RFS) 8211; Receives archived and/or standby redo logs from the primary database.
- Archiver (ARCn) Processes 8211; Archives the standby redo logs applied by the managed recovery process (MRP).
- Managed Recovery Process (MRP) 8211; Applies archive redo log information to the standby database.
Database Synchronization Options
Data Guard can be configured to run with varying synchronization modes indicating the potential for data loss.
- No-Data-Loss mode : This simply means that the log transport services will not acknowledge modifications to the primary database until they are available to the standby database. This doesn8217;t mean that the modifications have been applied to the standby database, merely that the log information is available to the log apply services should failover occur. This mode is implemented using standby redo logs on the standby server.
- No-Data-Divergence mode : This is an extension of the no-data-loss mode whereby modifications to the primary database are prevented if conectivity between the primary and at least one standby database is unavailable.
- Minimal-Data-Loss mode : When the performance requirements of the primary database are the top priority this mode provides the optimum balance of data protection and performance.
Setup No-Data-Divergence
To setup no-data-divergence, the most extreme level of data protection, then do the following.
Setup Primary Database
- Shutdown the database using:
SHUTDOWN IMMEDIATE - Backup all database files.
- Add an entry for the standby server into the 8220;tnsnames.ora8221; file.
stby1=
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = myServerName)(PORT = 1512))
)
(CONNECT_DATA =
(SERVICE_NAME = stby1.world)
)
)
- Assuming your database in already in
ARCHIVELOGmode one of the archive destinations will be set. Add the other entries.
CONTROL_FILES=primary.ctl COMPATIBLE=9.0.1.0.0 LOG_ARCHIVE_START=true LOG_ARCHIVE_DEST_1='LOCATION=C:\Oracle\Oradata\TSH1\Archive MANDATORY REOPEN=30' LOG_ARCHIVE_DEST_2='SERVICE=stby1 LGWR SYNC AFFIRM' LOG_ARCHIVE_DEST_STATE_1=enable LOG_ARCHIVE_DEST_STATE_2=enable LOG_ARCHIVE_FORMAT=arc%t_%s.arc REMOTE_ARCHIVE_ENABLE=true
The LGWR SYNC AFFIRM keywords indicate that the Logwriter should synchronously write updates to the online redo logs to this location and wait for confirmation of the write before proceeding. The remote site will process and archive these standby redo logs to keep the databases synchronized. This whole process can impact performance greatly but provides maximum data security.
- Startup the database using:
STARTUP PFILE=C:\Oracle\Admin\TSH1\pfile\init.ora - Create standby database controlfile using:
ALTER DATABASE CREATE STANDBY CONTROLFILE AS 'c:\stbycf.f';
Setup Standby Database
- Copy the production backup files to the standby server.
- Copy the standby controlfile to the standby server.
- Alter the control_files and archive parameters of the init.ora as follows.
SERVICE_NAMES = stby1
CONTROL_FILES=standby.ctl
COMPATIBLE=9.0.1.0.0
LOG_ARCHIVE_START=true
LOCK_NAME_SPACE=stby1
FAL_SERVER=prim1
FAL_CLIENT=stby1
# Uncomment if filename conversion is needed
#DB_FILE_NAME_CONVERT=("/primary","/standby")
#LOG_FILE_NAME_CONVERT=("/primary","/standby")
STANDBY_ARCHIVE_DEST=C:\Oracle\Oradata\TSH1\Archive
LOG_ARCHIVE_DEST_1='LOCATION=C:\Oracle\Oradata\TSH1\Archive'
LOG_ARCHIVE_TRACE=127
LOG_ARCHIVE_FORMAT=arc%t_%s.arc
STANDBY_FILE_MANAGEMENT=auto
REMOTE_ARCHIVE_ENABLE=true
- Add the following entries into the 8220;listener.ora8221; file.
(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = myHost)(PORT = 1512)) ) STANDBY_LISTENER = (ADDRESS_LIST= (ADDRESS=(PROTOCOL=tcp)(PORT=1512)(HOST=myHost)) )
The file should resemble the following.
# LISTENER.ORA Network Configuration File: C:\Oracle\Ora901\network\admin\listener.ora
# Generated by Oracle configuration tools.
LISTENER =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC0))
)
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = myHost)(PORT = 1521))
)
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = myHost)(PORT = 1512))
)
)
(DESCRIPTION =
(PROTOCOL_STACK =
(PRESENTATION = GIOP)
(SESSION = RAW)
)
(ADDRESS = (PROTOCOL = TCP)(HOST = myHost)(PORT = 2481))
)
)
STANDBY_LISTENER = (ADDRESS_LIST=
(ADDRESS=(PROTOCOL=tcp)(PORT=1512)(HOST=myHost))
)
SID_LIST_LISTENER =
(SID_LIST =
(SID_DESC = (SID_NAME = PLSExtProc)(ORACLE_HOME = C:\Oracle\Ora901)(PROGRAM = extproc))
(SID_DESC = (ORACLE_HOME = C:\Oracle\Ora901) (SID_NAME = TSH1)
)
)
- Reload the listener file using
lsnrctl reloadfrom the command prompt. - Add the following entry into the tnsnames.ora file:
stby1=
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = myServerName)(PORT = 1512))
)
(CONNECT_DATA =
(SERVICE_NAME = stby1.world)
)
)
Create standby redo logs on the standby database to receive online redo information from the Logwriter on the primary database. The minimum number of groups required is an exact match, number and size, of the primary database, but performance may be increased by adding more.
ALTER DATABASE ADD STANDBY LOGFILE GROUP 10
('C:\Oracle\Oradata\TSH1\redo1a.log','C:\Oracle\Oradata\TSH1\redo1b.log') SIZE 500K;
Start Managed Standby Recovery
During managed recovery the transfer of archivelogs is controlled by the servers without user intervention.
- Copy all archive logs from the primary to the standby server. This is the only time you should need to do this.
- From sqlplus do the following.
SQL> CONNECT sys/password AS SYSDBA SQL> STARTUP NOMOUNT PFILE=C:\Oracle\Admin\TSH1\pfile\init.ora SQL> ALTER DATABASE MOUNT STANDBY DATABASE; SQL> RECOVER MANAGED STANDBY DATABASE DISCONNECT FROM SESSION;
Protect Primary Database
Now that Data Guard is configured and running the primary database can be prevented from applying updates unless the update has been sent to at least one standby location. Connect to the primary database and execute the following.
ALTER DATABASE SET STANDBY DATABASE PROTECTED;
Cancel Managed Standby Recovery
To stop managed standby recovery do the following.
SQL> -- Cancel protected mode on primary SQL> CONNECT sys/password@primary1 AS SYSDBA SQL> ALTER DATABASE SET STANDBY DATABASE UNPROTECTED; SQL> SQL> -- Cancel recovery if necessary SQL> CONNECT sys/password@standby1 AS SYSDBA SQL> RECOVER MANAGED STANDBY DATABASE CANCEL; SQL> ALTER DATABASE OPEN READ ONLY;
The database can subsequently be switched back to recovery mode as follows.
SQL> -- Startup managed recovery SQL> CONNECT sys/password@standby1 AS SYSDBA SQL> SHUTDOWN IMMEDIATE SQL> STARTUP NOMOUNT PFILE=C:\Oracle\Admin\TSH1\pfile\init.ora SQL> ALTER DATABASE MOUNT STANDBY DATABASE; SQL> RECOVER MANAGED STANDBY DATABASE DISCONNECT FROM SESSION; SQL> -- Protect primary database SQL> CONNECT sys/password@primary1 AS SYSDBA SQL> ALTER DATABASE SET STANDBY DATABASE PROTECTED;
Activating A Standby Database
If the primary database is not available the standby database can be activated as a primary database using the following statements.
SQL> -- Cancel recovery if necessary SQL> RECOVER MANAGED STANDBY DATABASE CANCEL; SQL> ALTER DATABASE ACTIVATE STANDBY DATABASE;
Since the standby database is now the primary database it should be backed up immediately. The previous primary database can then be configured as a standby.
Backup Standby Database
Backups of the standby database can only be performed if the database is shut down or in read only mode. Read only mode is best for managed recovery systems as archive logs will still be transfered during the backup process, thus preventing gap sequences. Once the server is in the desired mode simply copy the appropriate database files.
Database Switchover
A database can be in one of two mutually exclusive modes (primary or standby). These roles can be altered at runtime without loss of data or resetting of redo logs. This process is known as a Switchover and can be performed using the following statements.
-- Convert primary database to standby CONNECT sys/change_on_install@prim1 AS SYSDBA ALTER DATABASE COMMIT TO SWITCHOVER TO STANDBY; -- Shutdown primary database SHUTDOWN IMMEDIATE; -- Mount old primary database as standby database STARTUP NOMOUNT PFILE=C:\Oracle\Admin\TSH1\pfile\init.ora ALTER DATABASE MOUNT STANDBY DATABASE; ALTER DATABASE RECOVER MANAGED STANDBY DATABASE; -- Convert standby database to primary CONNECT sys/change_on_install@stby1 AS SYSDBA ALTER DATABASE COMMIT TO SWITCHOVER TO PRIMARY; -- Shutdown standby database SHUTDOWN IMMEDIATE; -- Open old standby database as primary STARTUP PFILE=C:\Oracle\Admin\TSH1\pfile\init.ora
This process has no affect on alternative standby locations. The process of converting the instances back to their original roles is known as a Switchback. The switchback is accomplished by performing another switchover.
Database Failover
Graceful Database Failover occurs when database failover causes a standby database to be converted to a primary database.
ALTER DATABASE RECOVER MANAGED STANDBY DATABASE FINISH; ALTER DATABASE ACTIVATE STANDBY DATABASE;
This process will recovery all or some of the application data using the standby redo logs, therefore avoiding reinstantiation of other standby databases. If completed successfully, only the primary database will need to be reinstatiated as a standby database.
Forced Database Failover changes one standby database to a primary database. Application data may be lost neccessitating the reinstantiation of the primary and all standby databases.
Automatic Archive Gap Detection
Gaps in the sequence of archive logs can be created when changes are applied to the primary database while the standby database is unavailable. In Oracle8i the archive redo logs associated with these gaps had to be identified using the V$ARCHIVE_GAP view and copied manually to the standby server before managed recovery could be initiated again. In Oracle9i most of these gap sequences can be resolved automatically. The following parameters must be added to the standby init.ora file where the values indicate net services names.
FAL_SERVER = 'primary_db1' FAL_CLIENT = 'standby_db1'
The FAL server is normally the primary database, but can be another standby database. Once the standby database is placed in managed recovery mode it will automatically check for gap sequences. If it finds any it will request the appropriate files from the primary database via the FAL server. If the gap sequences cannot be resolved the files have to be recovered manually.
Background Managed Recovery
In Oracle8i managed recovery caused the user session to hang until the process was stopped by the user. This type of recovery is still available along with a background recovery that spawns a new background process and frees the user session
-- User session hangs ALTER DATABASE RECOVER MANAGED STANDBY DATABASE; -- User session released ALTER DATABASE RECOVER MANAGED STANDBY DATABASE DISCONNECT FROM SESSION;
Delayed Redo Application
Application of the archived redo logs to the standby database can be delayed using the DELAY keyword. If a rogue statement significantly damages the primary database the DBA can choose to switch to the standby database, which will be in a state prior to this action
-- Delay application of archived redo logs by 30 minutes. ALTER DATABASE RECOVER MANAGED STANDBY DATABASE DELAY 30; -- Return to no delay (Default). ALTER DATABASE RECOVER MANAGED STANDBY DATABASE NODELAY;
November 22, 2011 Articles 0 0
Duplicate a Database Using RMAN in Oracle Database 11g Release 2
- Introduction
- Backup-Based Duplication
- Active Database Duplication
Introduction
RMAN has the ability to duplicate, or clone, a database from a backup or from an active database. It is possible to create a duplicate database on a remote server with the same file structure, a remote server will a different file structure or the local server with a different file structure.
The article assumes the duplicate database is being created on a separate server, using the same SID (DB11G) and the same file structure as the source database. Explanations of several other scenarios are available here.
Backup-Based Duplication
Create a backup of the source database, if a suitable one doesn8217;t already exist.
$ rman target=/ RMAN> CONFIGURE CONTROLFILE AUTOBACKUP ON; RMAN> BACKUP DATABASE PLUS ARCHIVELOG
All subsequent actions occur on the server running the duplicate database.
Create a password file for the duplicate instance.
$ orapwd file=/u01/app/oracle/product/11.2.0/db_1/dbs/orapwDB11G password=password entries=10
Add the appropriate entries into the 8220;tnsnames.ora8221; file in the 8220;$ORACLE_HOME/network/admin8221; directory to allow connections to the target database from the duplicate server.
# Added to the tnsnames.ora
DB11G-SOURCE =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = ol5-112-dup1)(PORT = 1521))
)
(CONNECT_DATA =
(ORACLE_SID = DB11G)
)
)
Create a PFILE for the duplicate database. Since we are duplicating the database onto a separate server with the same filesystem as the original, we don8217;t need to convert the file names. In this case, the PFILE is called 8220;initDB11G.ora8221; and is placed in the 8220;$ORACLE_HOME/dbs8221; directory.
# Minimum Requirement. DB_NAME=DB11G # Convert file names to allow for different directory structure if necessary. #DB_FILE_NAME_CONVERT=(/u01/app/oracle/oradata/DB11G/,/u01/app/oracle/oradata/NEWSID/) #LOG_FILE_NAME_CONVERT=(/u01/app/oracle/oradata/DB11G/,/u02/app/oracle/oradata/NEWSID/)
Create any directories necessary for start the duplicate database.
$ mkdir -p /u01/app/oracle/oradata/DB11G $ mkdir -p /u01/app/oracle/fast_recovery_area/DB11G $ mkdir -p /u01/app/oracle/admin/DB11G/adump
Make the backup files from the source database available to the destination server. That can be done by either copying them to the matching location on the destination server, or placing them on a shared drive. If you are copying the files, you may want to use the following type of commands.
$ scp -r oracle@ol5-112-dup1:/u01/app/oracle/fast_recovery_area/DB11G/archivelog /u01/app/oracle/fast_recovery_area/DB11G $ scp -r oracle@ol5-112-dup1:/u01/app/oracle/fast_recovery_area/DB11G/backupset /u01/app/oracle/fast_recovery_area/DB11G $ scp -r oracle@ol5-112-dup1:/u01/app/oracle/fast_recovery_area/DB11G/autobackup /u01/app/oracle/fast_recovery_area/DB11G
Connect to the duplicate instance.
$ ORACLE_SID=DB11G; export ORACLE_SID $ sqlplus / as sysdba
Start the database in NOMOUNT mode.
SQL> STARTUP NOMOUNT;
With the duplicate database started we can now connect to it from RMAN. For the duplication to work we must connect to the duplicate database (AUXILIARY), but depending on the type of duplication we are doing we may optionally connect to the original database (TARGET) and/or the recovery catalog (CATALOG).
$ ORACLE_SID=DB11G; export ORACLE_SID $ rman AUXILIARY / $ rman TARGET sys/password@DB11G-SOURCE AUXILIARY / $ rman CATALOG rman/password@rman-catalog AUXILIARY / $ rman TARGET sys/password@DB11G-SOURCE CATALOG rman/password@rman-catalog AUXILIARY /
We can then duplicate the database using one of the following commands.
# Backup files are in matching location to that on the source server. # Duplicate database to TARGET's current state. DUPLICATE TARGET DATABASE TO DB11G SPFILE NOFILENAMECHECK; # Duplicate database to TARGET's state 4 days ago. DUPLICATE TARGET DATABASE TO DB11G UNTIL TIME 'SYSDATE-4' SPFILE NOFILENAMECHECK; # Backup files are in a different location to that on the source server. # Duplicate database to the most recent state possible using the provided backups. # Works with just an AUXILIARY connection only. DUPLICATE DATABASE TO DB11G SPFILE BACKUP LOCATION '/source/app/oracle/fast_recovery_area/DB11G' NOFILENAMECHECK;
The time it takes to complete varies depending on the size of the database and the specification of the server. Once the process is finished RMAN produces a completion message and you have your duplicate instance.
Active Database Duplication
Oracle 11g introduced the ability to create duplicate databases directly without the need for a backup. This is known as active database duplication. The process is similar to the backup-based duplication, with a few exceptions.
First, and most obviously, you don8217;t need a backup of the source system, but it does have to be in ARCHIVELOG mode.
The passwords in the password files must match for both servers, so remember to set the correct password when creating the password file on the destination server.
Both the source and destination database servers require a 8220;tnsnames.ora8221; entry for the destination database. In this case I added the following to each server. The destination server still requires the source entry shown in the previous section.
# Added to the tnsnames.ora on source and destination server.
DB11G-DESTINATION =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = ol5-112-dup2)(PORT = 1521))
)
(CONNECT_DATA =
(ORACLE_SID = DB11G)
)
)
The destination server requires static listener configuration in a 8220;listener.ora8221; file. In this case I used the following configuration. Remember to restart or reload the listener.
SID_LIST_LISTENER =
(SID_LIST =
(SID_DESC =
(GLOBAL_DBNAME = DB11G.WORLD)
(ORACLE_HOME = /u01/app/oracle/product/11.2.0/db_1)
(SID_NAME = DB11G)
)
)
LISTENER =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = ol5-112-dup2.localdomain)(PORT = 1521))
)
(DESCRIPTION =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
)
)
ADR_BASE_LISTENER = /u01/app/oracle
When connecting to RMAN, you must use a connect string for both the target and auxiliary connections.
$ ORACLE_SID=DB11G; export ORACLE_SID $ rman TARGET sys/password@DB11G-SOURCE AUXILIARY sys/password@DB11G-DESTINATION
Include the FROM ACTIVE DATABASE clause in the DUPLICATE command.
DUPLICATE DATABASE TO DB11G FROM ACTIVE DATABASE SPFILE NOFILENAMECHECK;
For more information see:
Flashback New Features and Enhancements in Oracle Database 10g
Oracle9i introduced the DBMS_FLASHBACK package to allow queries to reference older versions of the database. Oracle 10g has taken this technology a step further making it simpler to use and much more flexible.
Note: Internally Oracle uses SCNs to track changes so any flashback operation that uses a timestamp must be translated into the nearest SCN which can result in a 3 second error.
- Flashback Query
- Flashback Version Query
- Flashback Transaction Query
- Flashback Table
- Flashback Drop (Recycle Bin)
- Flashback Database
- Flashback Query Functions
Flashback Query
Flashback Query allows the contents of a table to be queried with reference to a specific point in time, using the AS OF clause. Essentially it is the same as the DBMS_FLASHBACK functionality or Oracle 9i, but in a more convenient form. For example.
CREATE TABLE flashback_query_test (
id NUMBER(10)
);
SELECT current_scn, TO_CHAR(SYSTIMESTAMP, 'YYYY-MM-DD HH24:MI:SS') FROM v$database;
CURRENT_SCN TO_CHAR(SYSTIMESTAM
----------- -------------------
722452 2004-03-29 13:34:12
INSERT INTO flashback_query_test (id) VALUES (1);
COMMIT;
SELECT COUNT(*) FROM flashback_query_test;
COUNT(*)
----------
1
SELECT COUNT(*) FROM flashback_query_test AS OF TIMESTAMP TO_TIMESTAMP('2004-03-29 13:34:12', 'YYYY-MM-DD HH24:MI:SS');
COUNT(*)
----------
0
SELECT COUNT(*) FROM flashback_query_test AS OF SCN 722452;
COUNT(*)
----------
0
Flashback Version Query
Flashback version query allows the versions of a specific row to be tracked during a specified time period using the VERSIONS BETWEEN clause.
CREATE TABLE flashback_version_query_test (
id NUMBER(10),
description VARCHAR2(50)
);
INSERT INTO flashback_version_query_test (id, description) VALUES (1, 'ONE');
COMMIT;
SELECT current_scn, TO_CHAR(SYSTIMESTAMP, 'YYYY-MM-DD HH24:MI:SS') FROM v$database;
CURRENT_SCN TO_CHAR(SYSTIMESTAM
----------- -------------------
725202 2004-03-29 14:59:08
UPDATE flashback_version_query_test SET description = 'TWO' WHERE id = 1;
COMMIT;
UPDATE flashback_version_query_test SET description = 'THREE' WHERE id = 1;
COMMIT;
SELECT current_scn, TO_CHAR(SYSTIMESTAMP, 'YYYY-MM-DD HH24:MI:SS') FROM v$database;
CURRENT_SCN TO_CHAR(SYSTIMESTAM
----------- -------------------
725219 2004-03-29 14:59:36
COLUMN versions_startscn FORMAT 99999999999999999
COLUMN versions_starttime FORMAT A24
COLUMN versions_endscn FORMAT 99999999999999999
COLUMN versions_endtime FORMAT A24
COLUMN versions_xid FORMAT A16
COLUMN versions_operation FORMAT A1
COLUMN description FORMAT A11
SET LINESIZE 200
SELECT versions_startscn, versions_starttime,
versions_endscn, versions_endtime,
versions_xid, versions_operation,
description
FROM flashback_version_query_test
VERSIONS BETWEEN TIMESTAMP TO_TIMESTAMP('2004-03-29 14:59:08', 'YYYY-MM-DD HH24:MI:SS')
AND TO_TIMESTAMP('2004-03-29 14:59:36', 'YYYY-MM-DD HH24:MI:SS')
WHERE id = 1;
VERSIONS_STARTSCN VERSIONS_STARTTIME VERSIONS_ENDSCN VERSIONS_ENDTIME VERSIONS_XID V DESCRIPTION
------------------ ------------------------ ------------------ ------------------------ ---------------- - -----------
725212 29-MAR-04 02.59.16 PM 02001C0043030000 U THREE
725209 29-MAR-04 02.59.16 PM 725212 29-MAR-04 02.59.16 PM 0600030021000000 U TWO
725209 29-MAR-04 02.59.16 PM ONE
SELECT versions_startscn, versions_starttime,
versions_endscn, versions_endtime,
versions_xid, versions_operation,
description
FROM flashback_version_query_test
VERSIONS BETWEEN SCN 725202 AND 725219
WHERE id = 1;
VERSIONS_STARTSCN VERSIONS_STARTTIME VERSIONS_ENDSCN VERSIONS_ENDTIME VERSIONS_XID V DESCRIPTION
------------------ ------------------------ ------------------ ------------------------ ---------------- - -----------
725212 29-MAR-04 02.59.16 PM 02001C0043030000 U THREE
725209 29-MAR-04 02.59.16 PM 725212 29-MAR-04 02.59.16 PM 0600030021000000 U TWO
725209 29-MAR-04 02.59.16 PM ONE
The available pseudocolumn meanings are:
VERSIONS_STARTSCNorVERSIONS_STARTTIME8211; Starting SCN and TIMESTAMP when row took on this value. The value of NULL is returned if the row was created before the lower bound SCN ot TIMESTAMP.VERSIONS_ENDSCNorVERSIONS_ENDTIME8211; Ending SCN and TIMESTAMP when row last contained this value. The value of NULL is returned if the value of the row is still current at the upper bound SCN ot TIMESTAMP.VERSIONS_XID8211; ID of the transaction that created the row in it8217;s current state.VERSIONS_OPERATION8211; Operation performed by the transaction ((I)nsert, (U)pdate or (D)elete)
Flashback Transaction Query
Flashback transaction query can be used to get extra information about the transactions listed by flashback version queries. The VERSIONS_XID column values from a flashback version query can be used to query the FLASHBACK_TRANSACTION_QUERY view.
SELECT xid, operation, start_scn,commit_scn, logon_user, undo_sql
FROM flashback_transaction_query
WHERE xid = HEXTORAW('0600030021000000');
XID OPERATION START_SCN COMMIT_SCN
---------------- -------------------------------- ---------- ----------
LOGON_USER
------------------------------
UNDO_SQL
----------------------------------------------------------------------------------------------------
0600030021000000 UPDATE 725208 725209
SCOTT
update "SCOTT"."FLASHBACK_VERSION_QUERY_TEST" set "DESCRIPTION" = 'ONE' where ROWID = 'AAAMP9AAEAAAA
AYAAA';
0600030021000000 BEGIN 725208 725209
SCOTT
XID OPERATION START_SCN COMMIT_SCN
---------------- -------------------------------- ---------- ----------
LOGON_USER
------------------------------
UNDO_SQL
----------------------------------------------------------------------------------------------------
2 rows selected.
Flashback Table
The FLASHBACK TABLE command allows point in time recovery of individual tables subject to the following requirements.
- You must have either the
FLASHBACK ANY TABLEsystem privilege or haveFLASHBACKobject privilege on the table. - You must have SELECT, INSERT, DELETE, and ALTER privileges on the table.
- There must be enough information in the undo tablespace to complete the operation.
- Row movement must be enabled on the table (
ALTER TABLE tablename ENABLE ROW MOVEMENT;).
The following example creates a table, inserts some data and flashbacks to a point prior to the data insertion. Finally it flashbacks to the time after the data insertion.
CREATE TABLE flashback_table_test (
id NUMBER(10)
);
ALTER TABLE flashback_table_test ENABLE ROW MOVEMENT;
SELECT current_scn FROM v$database;
CURRENT_SCN
-----------
715315
INSERT INTO flashback_table_test (id) VALUES (1);
COMMIT;
SELECT current_scn FROM v$database;
CURRENT_SCN
-----------
715340
FLASHBACK TABLE flashback_table_test TO SCN 715315;
SELECT COUNT(*) FROM flashback_table_test;
COUNT(*)
----------
0
FLASHBACK TABLE flashback_table_test TO SCN 715340;
SELECT COUNT(*) FROM flashback_table_test;
COUNT(*)
----------
1
Flashback of tables can also be performed using timestamps.
FLASHBACK TABLE flashback_table_test TO TIMESTAMP TO_TIMESTAMP('2004-03-03 10:00:00', 'YYYY-MM-DD HH:MI:SS');
Flashback Drop (Recycle Bin)
In Oracle 10g the default action of a DROP TABLE command is to move the table to the recycle bin (or rename it), rather than actually dropping it. The PURGE option can be used to permanently drop a table.
The recycle bin is a logical collection of previously dropped objects, with access tied to the DROP privilege. The contents of the recycle bin can be shown using the SHOW RECYCLEBIN command and purged using the PURGE TABLE command. As a result, a previously dropped table can be recovered from the recycle bin.
CREATE TABLE flashback_drop_test (
id NUMBER(10)
);
INSERT INTO flashback_drop_test (id) VALUES (1);
COMMIT;
DROP TABLE flashback_drop_test;
SHOW RECYCLEBIN
ORIGINAL NAME RECYCLEBIN NAME OBJECT TYPE DROP TIME
---------------- ------------------------------ ------------ -------------------
FLASHBACK_DROP_T BIN$TstgCMiwQA66fl5FFDTBgA==$0 TABLE 2004-03-29:11:09:07
EST
FLASHBACK TABLE flashback_drop_test TO BEFORE DROP;
SELECT * FROM flashback_drop_test;
ID
----------
1
Tables in the recycle bin can be queried like any other table.
DROP TABLE flashback_drop_test;
SHOW RECYCLEBIN
ORIGINAL NAME RECYCLEBIN NAME OBJECT TYPE DROP TIME
---------------- ------------------------------ ------------ -------------------
FLASHBACK_DROP_T BIN$TDGqmJZKR8u+Hrc6PGD8kw==$0 TABLE 2004-03-29:11:18:39
EST
SELECT * FROM "BIN$TDGqmJZKR8u+Hrc6PGD8kw==$0";
ID
----------
1
If an object is dropped and recreated multiple times all dropped versions will be kept in the recycle bin, subject to space. Where multiple versions are present it8217;s best to reference the tables via the RECYCLEBIN_NAME. For any references to the ORIGINAL_NAME it is assumed the most recent object is drop version in the referenced question. During the flashback operation the table can be renamed.
FLASHBACK TABLE flashback_drop_test TO BEFORE DROP RENAME TO flashback_drop_test_old;
Several purge options exist.
PURGE TABLE tablename; -- Specific table. PURGE INDEX indexname; -- Specific index. PURGE TABLESPACE ts_name; -- All tables in a specific tablespace. PURGE TABLESPACE ts_name USER username; -- All tables in a specific tablespace for a specific user. PURGE RECYCLEBIN; -- The current users entire recycle bin. PURGE DBA_RECYCLEBIN; -- The whole recycle bin.
Several restrictions apply relating to the recycle bin.
- Only available for non-system, locally managed tablespaces.
- There is no fixed size for the recycle bin. The time an object remains in the recycle bin can vary.
- The objects in the recycle bin are restricted to query operations only (no DDL or DML).
- Flashback query operations must reference the recycle bin name.
- Tables and all dependent objects are placed into, recovered and purged from the recycle bin at the same time.
- Tables with Fine Grained Access policies aer not protected by the recycle bin.
- Partitioned index-organized tables are not protected by the recycle bin.
- The recycle bin does not preserve referential integrity.
Flashback Database
The FLASHBACK DATABASE command is a fast alternative to performing an incomplete recovery. In order to flashback the database you must have SYSDBA privilege and the flash recovery area must have been prepared in advance.
If the database is in NOARCHIVELOG it must be switched to ARCHIVELOG mode.
CONN sys/password AS SYSDBA ALTER SYSTEM SET log_archive_dest_1='location=d:\oracle\oradata\DB10G\archive\' SCOPE=SPFILE; ALTER SYSTEM SET log_archive_format='ARC%S_%R.%T' SCOPE=SPFILE; SHUTDOWN IMMEDIATE STARTUP MOUNT ALTER DATABASE ARCHIVELOG; ALTER DATABASE OPEN;
Flashback must be enabled before any flashback operations are performed.
CONN sys/password AS SYSDBA SHUTDOWN IMMEDIATE STARTUP MOUNT EXCLUSIVE ALTER DATABASE FLASHBACK ON; ALTER DATABASE OPEN;
With flashback enabled the database can be switched back to a previous point in time or SCN without the need for a manual incomplete recovery. In the following example a table is created, the database is then flashbacked to a time before the table was created.
-- Create a dummy table. CONN scott/tiger CREATE TABLE flashback_database_test ( id NUMBER(10) ); -- Flashback 5 minutes. CONN sys/password AS SYSDBA SHUTDOWN IMMEDIATE STARTUP MOUNT EXCLUSIVE FLASHBACK DATABASE TO TIMESTAMP SYSDATE-(1/24/12); ALTER DATABASE OPEN RESETLOGS; -- Check that the table is gone. CONN scott/tiger DESC flashback_database_test
Some other variations of the flashback database command include.
FLASHBACK DATABASE TO TIMESTAMP my_date; FLASHBACK DATABASE TO BEFORE TIMESTAMP my_date; FLASHBACK DATABASE TO SCN my_scn; FLASHBACK DATABASE TO BEFORE SCN my_scn;
The window of time that is available for flashback is determined by the DB_FLASHBACK_RETENTION_TARGET parameter. The maximum flashback can be determined by querying the V$FLASHBACK_DATABASE_LOG view. It is only possible to flashback to a point in time after flashback was enabled on the database and since the last RESETLOGS command.
Flashback Query Functions
The TIMESTAMP_TO_SCN and SCN_TO_TIMESTAMP functions have been added to SQL and PL/SQL to simplify flashback operations.
SELECT * FROM emp AS OF SCN TIMESTAMP_TO_SCN(SYSTIMESTAMP - 1/24); SELECT * FROM emp AS OF TIMESTAMP SCN_TO_TIMESTAMP(993240); DECLARE l_scn NUMBER; l_timestamp TIMESTAMP; BEGIN l_scn := TIMESTAMP_TO_SCN(SYSTIMESTAMP - 1/24); l_timestamp := SCN_TO_TIMESTAMP(l_scn); END; /
December 21, 2011 Articles 0 0
Recompiling Invalid Schema Objects
Operations such as upgrades, patches and DDL changes can invalidate schema objects. Provided these changes don8217;t cause compilation failures the objects will be revalidated by on-demand automatic recompilation, but this can take an unacceptable time to complete, especially where complex dependencies are present. For this reason it makes sense to recompile invalid objects in advance of user calls. It also allows you to identify if any changes have broken your code base. This article presents several methods for recompiling invalid schema objects.
- Identifying Invalid Objects
- The Manual Approach
- Custom Script
- DBMS_UTILITY.compile_schema
- UTL_RECOMP
- utlrp.sql and utlprp.sql
Identifying Invalid Objects
The DBA_OBJECTS view can be used to identify invalid objects using the following query.
COLUMN object_name FORMAT A30
SELECT owner,
object_type,
object_name,
status
FROM dba_objects
WHERE status = 'INVALID'
ORDER BY owner, object_type, object_name;
With this information you can decide which of the following recompilation methods is suitable for you.
The Manual Approach
For small numbers of objects you may decide that a manual recompilation is sufficient. The following example shows the compile syntax for several object types.
ALTER PACKAGE my_package COMPILE; ALTER PACKAGE my_package COMPILE BODY; ALTER PROCEDURE my_procedure COMPILE; ALTER FUNCTION my_function COMPILE; ALTER TRIGGER my_trigger COMPILE; ALTER VIEW my_view COMPILE;
Notice that the package body is compiled in the same way as the package specification, with the addition of the word 8220;BODY8221; at the end of the command.
An alternative approach is to use the DBMS_DDL package to perform the recompilations.
EXEC DBMS_DDL.alter_compile('PACKAGE', 'MY_SCHEMA', 'MY_PACKAGE');
EXEC DBMS_DDL.alter_compile('PACKAGE BODY', 'MY_SCHEMA', 'MY_PACKAGE');
EXEC DBMS_DDL.alter_compile('PROCEDURE', 'MY_SCHEMA', 'MY_PROCEDURE');
EXEC DBMS_DDL.alter_compile('FUNCTION', 'MY_SCHEMA', 'MY_FUNCTION');
EXEC DBMS_DDL.alter_compile('TRIGGER', 'MY_SCHEMA', 'MY_TRIGGER');
This method is limited to PL/SQL objects, so it is not applicable for views.
Custom Script
In some situations you may have to compile many invalid objects in one go. One approach is to write a custom script to identify and compile the invalid objects. The following example identifies and recompiles invalid packages and package bodies.
SET SERVEROUTPUT ON SIZE 1000000
BEGIN
FOR cur_rec IN (SELECT owner,
object_name,
object_type,
DECODE(object_type, 'PACKAGE', 1,
'PACKAGE BODY', 2, 2) AS recompile_order
FROM dba_objects
WHERE object_type IN ('PACKAGE', 'PACKAGE BODY')
AND status != 'VALID'
ORDER BY 4)
LOOP
BEGIN
IF cur_rec.object_type = 'PACKAGE' THEN
EXECUTE IMMEDIATE 'ALTER ' || cur_rec.object_type ||
' "' || cur_rec.owner || '"."' || cur_rec.object_name || '" COMPILE';
ElSE
EXECUTE IMMEDIATE 'ALTER PACKAGE "' || cur_rec.owner ||
'"."' || cur_rec.object_name || '" COMPILE BODY';
END IF;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.put_line(cur_rec.object_type || ' : ' || cur_rec.owner ||
' : ' || cur_rec.object_name);
END;
END LOOP;
END;
/
This approach is fine if you have a specific task in mind, but be aware that you may end up compiling some objects multiple times depending on the order they are compiled in. It is probably a better idea to use one of the methods provided by Oracle since they take the code dependencies into account.
DBMS_UTILITY.compile_schema
The COMPILE_SCHEMA procedure in the DBMS_UTILITY package compiles all procedures, functions, packages, and triggers in the specified schema. The example below shows how it is called from SQL*Plus.
EXEC DBMS_UTILITY.compile_schema(schema => 'SCOTT');
UTL_RECOMP
The UTL_RECOMP package contains two procedures used to recompile invalid objects. As the names suggest, the RECOMP_SERIAL procedure recompiles all the invalid objects one at a time, while the RECOMP_PARALLEL procedure performs the same task in parallel using the specified number of threads. Their definitions are listed below.
PROCEDURE RECOMP_SERIAL( schema IN VARCHAR2 DEFAULT NULL, flags IN PLS_INTEGER DEFAULT 0); PROCEDURE RECOMP_PARALLEL( threads IN PLS_INTEGER DEFAULT NULL, schema IN VARCHAR2 DEFAULT NULL, flags IN PLS_INTEGER DEFAULT 0);
The usage notes for the parameters are listed below.
- schema 8211; The schema whose invalid objects are to be recompiled. If NULL all invalid objects in the database are recompiled.
- threads 8211; The number of threads used in a parallel operation. If NULL the value of the 8220;job_queue_processes8221; parameter is used. Matching the number of available CPUs is generally a good starting point for this value.
- flags 8211; Used for internal diagnostics and testing only.
The following examples show how these procedures are used.
-- Schema level.
EXEC UTL_RECOMP.recomp_serial('SCOTT');
EXEC UTL_RECOMP.recomp_parallel(4, 'SCOTT');
-- Database level.
EXEC UTL_RECOMP.recomp_serial();
EXEC UTL_RECOMP.recomp_parallel(4);
-- Using job_queue_processes value.
EXEC UTL_RECOMP.recomp_parallel();
EXEC UTL_RECOMP.recomp_parallel(NULL, 'SCOTT');
There are a number of restrictions associated with the use of this package including:
- Parallel execution is perfomed using the job queue. All existing jobs are marked as disabled until the operation is complete.
- The package must be run from SQL*Plus as the SYS user, or another user with SYSDBA.
- The package expects the
STANDARD,DBMS_STANDARD,DBMS_JOBandDBMS_RANDOMto be present and valid. - Runnig DDL operations at the same time as this package may result in deadlocks.
utlrp.sql and utlprp.sql
The utlrp.sql and utlprp.sql scripts are provided by Oracle to recompile all invalid objects in the database. They are typically run after major database changes such as upgrades or patches. They are located in the $ORACLE_HOME/rdbms/admin directory and provide a wrapper on the UTL_RECOMP package. The utlrp.sql script simply calls the utlprp.sql script with a command line parameter of 8220;08243;. The utlprp.sql accepts a single integer parameter that indicates the level of parallelism as follows.
- 0 8211; The level of parallelism is derived based on the CPU_COUNT parameter.
- 1 8211; The recompilation is run serially, one object at a time.
- N 8211; The recompilation is run in parallel with 8220;N8221; number of threads.
Both scripts must be run as the SYS user, or another user with SYSDBA, to work correctly.
