Flashback Oracle Documentation Reading

Most of the documentation related to Flashback is located in the Backup and Recovery User's Guide
and the Oracle Database Developer's Guide .

basic concept

See 1.4 About Oracle Flashback Technology in the Backup and Recovery User's Guide .

Definition of Oracle Flashback Technology :

A set of Oracle Database features that provide an additional layer of data protection. These features include Oracle Flashback Query, Oracle Flashback Version Query, Oracle Flashback Transaction Query, Oracle Flashback Transaction, Oracle Flashback Table, Oracle Flashback Drop, and Oracle Flashback Database. 是一组技术,是备份和恢复的补充

You can use flashback features to view past states of data and rewind parts or all of your database. In general, flashback features are more efficient and less disruptive than media recovery in most situations in which they apply. Backup and restore are more lightweight

Logical Flashback Features

Flashback technologies other than Flashback Database are all logical flashbacks and do not depend on RMAN.

The so-called logic is because these features are operated at the logical level, and the Flashback Database mentioned later is operated at the physical level and depends on RMAN.

In addition to Oracle Flashback Drop, the logical flashback feature relies on undo data, which records the effect of each database update and the value overwritten in the update.

Oracle Database includes the following logical flashback features:

  • Oracle Flashback Query
    allows you to specify a target time and run a query against the database to see the results that appear at the target time. To recover from unwanted changes such as table updates, you can choose the target time before the error and run a query to retrieve the contents of the missing rows. The Oracle Database Developer's Guide explains how to use this feature.

  • Oracle Flashback Version Query
    allows you to view all versions of all rows that have ever existed in one or more tables during a specified time interval . You can also retrieve metadata about different versions of a row, including start and end times, the operation, and the transaction ID of the transaction that created that version. You can use this feature to recover missing data values ​​and audit changes to query tables. The Oracle Database Developer's Guide explains how to use this feature.

  • Oracle Flashback Transaction Query
    allows you to view changes made by a single transaction or all transactions within a specific time period. The Oracle Database Developer's Guide explains how to use this feature.

  • Oracle Flashback Transaction
    You can reverse the transaction . Oracle Database determines dependencies between transactions and actually creates a compensating transaction to undo unwanted changes. The database rewinds to a state as if that transaction, and any transactions that might depend on it, never happened. The Oracle Database Developer's Guide explains how to use this feature.

  • Oracle Flashback Table
    allows you to restore a table or a group of tables to an earlier specified point in time without taking any part of the database offline . In many cases, Flashback Table eliminates the need to perform more complex point-in-time recovery operations. Flashback Table automatically maintains associated properties such as current indexes, triggers, and constraints while restoring tables , allowing you to avoid finding and restoring database-specific properties. " Rewinding a Table with Flashback Table " explains how to use this feature.

  • Oracle Flashback Drop
    You can undo the effects of the DROP TABLE statement. " Rewinding a DROP TABLE Operation with Flashback Drop " explains how to use this feature.

A flashback data archive enables you to access data from a long time ago with some logical flashback functionality . A Flashback Data Archive consists of one or more tablespaces or portions of tablespaces. When creating a Flashback Data Archive, specify the name, retention period, and tablespace . You can also specify a default flashback data archive. The database automatically purges old historical data the day after the retention period expires.

You can turn flashback archiving on and off for individual tables. By default, flashback archiving is turned off for each table.

Flashback Database

Flashback Database enables you to restore an Oracle database to a previous point in time.

At the physical level , Oracle Flashback Database provides a more efficient data protection alternative than Database Point-in-Time Recovery (DBPITR) . If the current datafiles have unwanted changes, then you can use the RMAN command FLASHBACK DATABASE to restore the datafiles to their past contents. The end product is much like DBPITR's results, but is usually much faster because it does not require datafiles to be restored from backup, and requires less redo than media restoration .

Flashback Database uses flashback logs to access past versions of data blocks and some information in archived redo logs. Flashback Database requires you to configure a fast recovery area for the database , because flashback logs can only be stored there. Flashback logging is not enabled by default. The space used for flashback logs is managed automatically by the database and is balanced against the space required by other files in the flash recovery area.

Oracle Database also supports restore points as well as Flashback Database and Backup and Recovery. The restore point is an alias corresponding to the system change number (SCN) . You can create a restore point at any time if you anticipate the need to restore some or all of your database to what it was then. A guaranteed restore point ensures that you can use Flashback Database to bring the database back to the time of the restore point.

" Rewinding a Database with Flashback Database " Learn how to use the FLASHBACK DATABASE command to perform Flashback Database

Backup and Recovery Guidelines: 5.10.2.1 Considerations When Setting the Size of the Fast Recovery Area

If you plan to enable flashback logging, the flashback log generation is about the same as the redo log generation. For example, if you plan to set DB_FLASHBACK_RETENTION_TARGET to 24 hours, and if the database generates 20 GB of redo per day, a general rule of thumb is to allow 20 GB to 30 GB of disk space for flashback logs. The same rules apply for guaranteed restore points when flashback logging is enabled. For example, if the database generates 20GB of redo per day, and restore points are guaranteed to be kept for one day, then plan to allocate 20 to 30GB.

A few terms:

The return of the whole database to a prior consistent SCN by the FLASHBACK DATABASE command in RMAN or SQL. A database flashback is different from traditional media recovery because it does not involve the restore of physical files, instead restoring your current data files to past states using saved images of changed data blocks. This feature uses flashback logs and archived redo logs.

The recovery of an entire database to a specified past target time, SCN, or log sequence number.

Oracle-generated logs used to perform flashback database operations. The database can only write flashback logs to the fast recovery area. Flashback logs are written sequentially and are not archived. They cannot be backed up to disk.

  • fast recovery area
    An optional disk location that you can use to store recovery-related files such as control file and online redo log copies, archived redo log files, flashback logs, and RMAN backups. Oracle Database and RMAN manage the files in the fast recovery area automatically. You can specify the disk quota, which is the maximum size of the fast recovery area. Formerly referred to as flash recovery area.

  • restore point

A user-defined a name associated with an SCN of the database corresponding to the time of the creation of the restore point. A restore point can be a guaranteed restore point or a normal restore point.

  • system change number (SCN)
    A stamp that defines a committed version of a database at a point in time. Oracle assigns every committed transaction a unique SCN.

  • guaranteed restore point
    A restore point for which the database is guaranteed to retain the flashback logs for an Oracle Flashback Database operation. Unlike a normal restore point, a guaranteed restore point does not age out of the control file and must be explicitly dropped. Guaranteed restore points use space in the fast recovery area, which must be defined.

Background processes related to Flashback

RVWR and FBDA, both are optional. The former is related to Flashback Database, and the latter is related to Flashback Data Archive (also known as Flashback Time Travel).
insert image description here

详见Database Concepts和Oracle Database 21c Technical Architecture。

Using Flashback Technology

See Chapter 20 Using Oracle Flashback Technology in the Database Development Guide

Overview of Oracle Flashback Technology

Oracle Flashback Technology is a set of Oracle Database features that allow you to view the past state of database objects or return database objects to a previous state without using point-in-time media recovery.

With Flashback, you can:

  • Execute queries that return past data
  • Executes queries that return metadata showing a detailed history of database changes
  • Restore a table or row to a previous point in time
  • Automatically track and archive transactional data changes
  • Rollback a transaction and its dependent transactions while the database remains online

Oracle Flashback uses the Automatic Undo Management (AUM) system to obtain transaction metadata and historical data. They rely on undo data, which is a record of the impact of a single transaction. For example, if a user runs an UPDATE statement to change salary from 1000 to 1100, Oracle Database will store the value 1000 in the undo data.

Undo data is persistent and survives database shutdown. It is retained for the time specified by undo_retention (default 15 minutes), or up to the adjusted undo retention time if Automatic Undo Management (AUM) is present. By using the flashback feature, you can use undo data to query past data or recover from logical corruption. In addition to using it in the flashback feature, Oracle Database also uses undo data to perform these operations:

  • rollback active transaction
  • Recover an aborted transaction using database or process recovery
  • Provides read consistency for SQL queries

Note: After executing the CREATE TABLE statement, wait at least 15 seconds to commit any transactions to ensure that Oracle Flashback functionality (especially Oracle Flashback Version Query) reflects these transactions.

Note: Oracle Database recommends avoiding versions_starttime or column versions_endtimescn_to_timestamp
VERSIONS queries (including CTAS queries) to improve performance.

In the Data Consistency section of the document Database Concepts writes:

Oracle Database always enforces statement-level read consistency, which guarantees that the data that a single query returns is committed and consistent for a single point in time. Depending on the transaction isolation level, this point is the time at which the statement was opened or the time the transaction began. The Oracle Flashback Query feature enables you to specify this point in time explicitly.

Flashback features related to application development:

  • Flashback Query
    returns data from an earlier time through the AS OF clause of SELECT
  • Flashback Version Query
    uses this feature to retrieve metadata and historical data for a specific time interval (for example, to see all rows of a table that ever existed in a given time interval). The metadata for each row version includes start and end times, the type of change operation, and the identity of the transaction that created the row version. To create an Oracle Flashback Versions query, use the VERSIONS BETWEEN clause of the SELECT statement.
  • Flashback Transaction Query
    uses this functionality to retrieve metadata and historical data for a given transaction or for all transactions within a given time interval. To perform an Oracle Flashback Transaction query, see the static data dictionary view FLASHBACK_TRANSACTION_QUERY. Flashback Version Query provides transaction IDs for rows of interest.
  • The DBMS_FLASHBACK Package
    uses this feature to set the internal Oracle database clock to an earlier time so that you can check the latest data at that time, or roll back a transaction and its dependent transactions while the database remains online.
  • Flashback Transaction
    uses Flashback Transaction to roll back a transaction and its dependent transactions while the database remains online. This recovery operation uses the undo data to create and run a corresponding compensating transaction, returning the affected data to its original state. (Flashback transactions are part of the DBMS_FLASHBACK package).
  • Flashback Time Travel
    automatically tracks and archives historical versions of changes to Flashback Archive enabled tables using Flashback Time Travel, ensuring SQL-level access to database object versions without snapshot too old errors.

The flashback feature of partial database management is mainly used for data recovery. Typically, you use these functions only as a database administrator. include:

  • Flashback Table
    can use this function to restore the table to the state of a previous point in time. You can restore tables while the database is online, undoing only changes to specified tables.
  • Flashback Drop
    uses this feature to recover dropped tables. This function reverses the effect of the DROP TABLE statement.
  • Flashback Database
    uses this feature to quickly restore the database to an earlier point in time by using the recovery area. This is fast because you don't have to restore database backups.

Configuring Your Database for Oracle Flashback Technology

20.2.1 Configuring Your Database for Automatic Undo Management

To configure a database for Automatic Undo Management (AUM), you must:

  • Create an undo tablespace with enough space to hold the data required for the flashback operation.
    The more frequently users update data, the more space is required. Database administrators typically calculate space requirements.

  • Enable AUM. Configure the following database initialization parameters:

    • UNDO_MANAGEMENT (default is AUM)
    • UNDO_TABLESPACE
    • UNDO_RETENTION

    For fixed-size undo tablespaces, Oracle Database automatically tunes the system to provide the best undo retention time. For automatically extensible undo tablespaces, Oracle Database retains undo data longer than the maximum query duration specified by the UNDO_RETENTION parameter and the low threshold for undo retention.
    You can query V$UNDOSTAT. TUNED_UNDORETENTION to determine the amount of time to keep undo for the current undo tablespace.
    Setting UNDO_RETENTION does not guarantee that unexpired undo data will not be discarded. If the system needs more space, Oracle Database can overwrite unexpired undoes with recently generated undo data.

  • Specify the RETENTION GUARANTEE clause of the undo tablespace to ensure that unexpired undo data will not be discarded.

20.2.2 Configuring Your Database for Oracle Flashback Transaction Query

To configure a database for the Oracle Flashback Transaction Query feature, you or your database administrator must:

  • Make sure the Oracle database is running with version 10.0 compatibility.
  • Enable supplemental logging:
ALTER DATABASE ADD SUPPLEMENTAL LOG DATA;

Example of enabling process:

SQL> select SUPPLEMENTAL_LOG_DATA_MIN MIN, SUPPLEMENTAL_LOG_DATA_PK PK, SUPPLEMENTAL_LOG_DATA_UI UI, SUPPLEMENTAL_LOG_DATA_ALL ALL_LOG from v$database;

MIN      PK  UI  ALL
-------- --- --- ---
NO       NO  NO  NO

SQL> ALTER DATABASE ADD SUPPLEMENTAL LOG DATA;

Database altered.

SQL> select SUPPLEMENTAL_LOG_DATA_MIN MIN, SUPPLEMENTAL_LOG_DATA_PK PK, SUPPLEMENTAL_LOG_DATA_UI UI, SUPPLEMENTAL_LOG_DATA_ALL ALL_LOG from v$database;

MIN      PK  UI  ALL
-------- --- --- ---
YES      NO  NO  NO

20.2.3 Configuring Your Database for Flashback Transaction

The configuration process is as follows:

-- 启用归档
ALTER DATABASE ARCHIVELOG;
-- 打开至少一个archive log
ALTER SYSTEM ARCHIVE LOG CURRENT;
-- 如果之前没有配置,启用最小和主键补充日志记录
ALTER DATABASE ADD SUPPLEMENTAL LOG DATA;
ALTER DATABASE ADD SUPPLEMENTAL LOG DATA (PRIMARY KEY) COLUMNS;
-- 如果要跟踪外键依赖,请启用外键补充日志记录
-- 如果您有很多外键约束,启用外键补充日志记录可能不值得性能损失。
ALTER DATABASE ADD SUPPLEMENTAL LOG DATA (FOREIGN KEY) COLUMNS;

20.2.4 Enabling Oracle Flashback Operations on Specific LOB Columns

To enable flashback operations on specific LOB columns of a table, use the ALTER TABLE statement with the RETENTION option.

Because the undo data for LOB columns can be very large, you must define which LOB columns are used for flashback operations.

20.2.5 Granting Necessary Privileges

You or your database administrator must grant permissions to users, roles, or applications that must use these flashback features. That is, the authority to query the corresponding table and execute the corresponding process.

For Oracle Flashback Query and Oracle Flashback Versions Query

  • To allow access to specific objects during queries, grant READ or FLASHBACK permissions on those objects.
  • To allow queries on all tables, grant FLASHBACK ANY TABLE permission.

For Oracle Flashback Transaction Query

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

For the DBMS_FLASHBACK package

  • To allow access to functionality in the DBMS_FLASHBACK package, grant EXECUTE permission on DBMS_FLASHBACK.

for flashback time travel

To allow a specific user to enable flashback time travel on a table, or to use a specific flashback archive, grant the FLASHBACK ARCHIVE object permission on the flashback archive to that user. To grant the FLASHBACK ARCHIVE object privilege, you must be logged in as the SYSDBA system with the FLASHBACK ARCHIVE ADMINISTER system privilege.

To allow execution of these statements, grant the FLASHBACK ARCHIVE ADMINISTER system privilege:

  • CREATE FLASHBACK ARCHIVE
  • ALTER FLASHBACK ARCHIVE
  • DROP FLASHBACK ARCHIVE

To grant FLASHBACK ARCHIVE ADMINISTER system privileges, you must be logged in as SYSDBA.

To create a default flashback archive using CREATE/ALTER FLASHBACK ARCHIVE, you must be logged in as SYSDBA.

To disable flashback archiving for a table that has flashback archiving enabled, you must be logged in as SYSDBA or have the FLASHBACK ARCHIVE ADMINISTER system privilege.

Using Oracle Flashback Query (SELECT AS OF)

To use Oracle Flashback Query, use the SELECT statement with the AS OF clause. Oracle Flashback Query retrieves previously existing data. The query explicitly references a time in the past by timestamp or system change number (SCN). It returns the latest committed data at that point in time.

Uses for Oracle Flashback Query include:

  • Recover missing data or undo incorrectly committed changes.
    For example, if you delete or update rows by mistake, and then commit them, you can immediately undo the mistake.
  • Compare current data with corresponding data from an earlier time.
    For example, you can run a daily report to show yesterday's data changes. You can compare individual rows of table data or find intersections or unions of sets of rows.
  • Check the status of transaction data at a specific time.
    For example, you can verify the account balance for a certain day.
  • Select data that is valid at a specific time or at any time within a user-defined valid period.
    For example, you can find employees with valid employee information as of a specific timestamp or between a specified start and end time for a specified valid time period. (See Time Validity Support for more information .)
  • Simplifies application design by eliminating the need to store certain types of temporal data.
  • Oracle Flashback Query allows you to retrieve past data directly from the database.
  • Apply packaged applications, such as report generation tools, to past data.
  • Provides self-service error correction for applications, enabling users to undo and correct their errors.

SELECT AS OF can be followed by TIMESTAMP or SCN. TIMESTAMP can be absolute time or relative time, for example:

  • Absolute time: TO_TIMESTAMP('2004-04-04 09:30:00', 'YYYY-MM-DD HH:MI:SS')
  • Relative time: TIMESTAMP (SYSTIMESTAMP - INTERVAL '60' MINUTE)

Oracle Flashback Query Guidelines:

  • You can specify or omit the AS OF clause per table and specify different times for different tables. If the specified time is earlier than its creation time, the query will return zero rows for the table instead of causing an error.
  • You can use the AS OF query clause to perform data definition language (DDL) operations such as create and truncate tables or data manipulation language (DML) statements such as INSERT and DELETE in the same session as Oracle Flashback Query.
  • To use the results of Oracle Flashback Query in DDL or DML statements that affect the current state of the database, use the AS OF clause in the INSERT or CREATE TABLE AS SELECT statement.
  • If a possible 3 second error (maximum) is important for Oracle Flashback Query in your application, use SCN instead of timestamp. See Oracle Flashback Technology General Guide .
  • You can create views that refer to past data by using the AS OF clause in the SELECT statement that defines the view.
  • You can use the AS OF clause in self-join or set operations such as INTERSECT and MINUS to extract or compare data at two different times.
  • You can use the AS OF clause in a query to check which data is valid at a specific time.

Using Oracle Flashback Version Query

Use Oracle Flashback Versions Query to retrieve different versions of a particular row that existed during a given time interval. A row version is created each time a COMMIT statement is executed.
Note: After executing the CREATE TABLE statement, wait at least 15 seconds for any transactions to be committed to ensure that Oracle Flashback Version queries reflect these transactions.

Use the VERSIONS BETWEEN clause of the SELECT statement to specify an Oracle Flashback Versions query. The syntax is:

-- 其中start和end分别表示要查询的时间间隔的开始和结束的表达式。
VERSIONS BETWEEN { SCN | TIMESTAMP } start AND end

or:

-- 其中 user_valid_time 是指用户指定的有效时间段
-- 如 Temporal Validity Support 中所述。
VERSIONS PERIOD FOR user_valid_time [ BETWEEN TIMESTAMP start AND end ]

Oracle Flashback Versions Query returns a table containing rows for each version of the row that existed at any time during the specified interval. Each row in the table contains a metadata pseudo-column about the row version, which reveals when and how a particular change (possibly wrongly) occurred in the database.

The following table describes the metadata pseudo-columns about row versions. The VERSIONS_* pseudo-columns only have values ​​for transaction-time flashback version queries (that is, queries with a BETWEEN TIMESTAMP start AND end clause).

Pseudo column names describe
VERSIONS_STARTSCN
VERSIONS_STARTTIME
The starting system change number (SCN) or TIMESTAMP when the row version was created. This pseudocolumn identifies when the data first had a value reflected in the row version. Use this pseudocolumn to identify the past target time for Oracle Flashback Table or Oracle Flashback Query.
If this pseudo-column is NULL, the row version was created before the start.
VERSIONS_ENDSCN
VERSIONS_ENDTIME
The SCN or TIMESTAMP when the row version expires.
If this pseudo-column is NULL, then the row version was current at the time of the query, or the row corresponds to a DELETE operation.
VERSIONS_XID The identifier of the transaction that created the row version.
VERSIONS_OPERATION The operations performed by the transaction: I insert, D delete, U update. The version is the version of the row that was inserted, deleted, or updated; that is, the row after the INSERT operation, the row before the DELETE operation, or the row affected by the UPDATE operation.
For user updates of index keys, Oracle Flashback Versions Query may treat an UPDATE operation as two operations, DELETE and INSERT, represented as two version rows, D followed by I VERSIONS_OPERATION.

The given row version is valid from its time VERSIONS_START* up to but not including its time VERSIONS_END*. That is, time t is satisfied VERSIONS_START* <= t < VERSIONS_END*.

The following is a typical query:

SELECT versions_startscn, versions_starttime,
       versions_endscn, versions_endtime,
       versions_xid, versions_operation,
       last_name, salary
  FROM employees
  VERSIONS BETWEEN TIMESTAMP
      TO_TIMESTAMP('2008-12-18 14:00:00', 'YYYY-MM-DD HH24:MI:SS')
  AND TO_TIMESTAMP('2008-12-18 17:00:00', 'YYYY-MM-DD HH24:MI:SS')
  WHERE first_name = 'John';

You can use VERSIONS_XID with Oracle Flashback Transaction Query (described in the next section) to locate metadata for this transaction, including the SQL required to undo row changes and the user responsible for the changes.

Flashback Version Query only allows index-only access using IOTs (Index Organized Tables), but does not allow fast full scans using indexes.

Using Oracle Flashback Transaction Query

Use Oracle Flashback Transaction Query to retrieve metadata and historical data for a given transaction or all transactions for a given time interval. Oracle Flashback Transaction Query queries the static data dictionary view FLASHBACK_TRANSACTION_QUERY, whose columns are described in the Oracle Database Reference .

The UNDO_SQL column shows the SQL code that is the logical opposite of the DML operation performed by the transaction. You can often use this code to reverse the logical steps taken during a transaction. However, there are cases where the UNDO_SQL code is not exactly the opposite of the original transaction's code. For example, an UNDO_SQL INSERT operation may not reinsert a row into the table with the same ROWID as the deleted row.

This statement queries the FLASHBACK_TRANSACTION_QUERY view for transaction information, including transaction ID, operation, operation start and end SCN, user responsible for the operation, and SQL code showing the inverse of the operation logic:

SELECT xid, operation, start_scn, commit_scn, logon_user, undo_sql
FROM flashback_transaction_query
WHERE xid = HEXTORAW('000200030000002D');

This statement uses Oracle Flashback Versions Query as a subquery to associate each row version with the LOGON_USER responsible for the row's data changes:

SELECT xid, logon_user
FROM flashback_transaction_query
WHERE xid IN (
  SELECT versions_xid FROM employees VERSIONS BETWEEN TIMESTAMP
  TO_TIMESTAMP('2003-07-18 14:00:00', 'YYYY-MM-DD HH24:MI:SS') AND
  TO_TIMESTAMP('2003-07-18 17:00:00', 'YYYY-MM-DD HH24:MI:SS')
);

Note: If you query FLASHBACK_TRANSACTION_QUERY without specifying an XID in the WHERE clause, the query will scan many irrelevant rows, degrading performance.

Using Oracle Flashback Transaction Query with Oracle Flashback Version Query

In this example, the database administrator does the following:

DROP TABLE emp;
CREATE TABLE emp (
  empno   NUMBER PRIMARY KEY,
  empname VARCHAR2(16),
  salary  NUMBER
);
INSERT INTO emp (empno, empname, salary) VALUES (111, 'Mike', 555);
COMMIT;

DROP TABLE dept;
CREATE TABLE dept (
  deptno   NUMBER,
  deptname VARCHAR2(32)
);
INSERT INTO dept (deptno, deptname) VALUES (10, 'Accounting');
COMMIT;

There is now one row for emp and one row for dept. In terms of row versions, each table has one version of a row. Suppose an erroneous transaction deletes empno 111 from table emp:

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

Next, the transaction reinserts empno 111 into the emp table with the new employee name:

INSERT INTO emp (empno, empname, salary) VALUES (111, 'Tom', 777);
UPDATE emp SET salary = salary + 100 WHERE empno = 111;
UPDATE emp SET salary = salary + 50 WHERE empno = 111;
COMMIT;

A database administrator detects an application error and must diagnose the problem. The database administrator issues this query to retrieve the version of the row corresponding to empno 111 in the emp table. This query uses the Oracle Flashback version to query pseudocolumns:

SELECT versions_xid XID, versions_startscn START_SCN,
  versions_endscn END_SCN, versions_operation OPERATION,
  empname, salary
FROM emp
VERSIONS BETWEEN SCN MINVALUE AND MAXVALUE
WHERE empno = 111;

The result is similar to:

XID               START_SCN    END_SCN O EMPNAME              SALARY
---------------- ---------- ---------- - ---------------- ----------
09001100B2200000   10093466            I Tom                     927
030002002B210000   10093459            D Mike                    555
0800120096200000   10093375   10093459 I Mike                    555
 
3 rows selected.

The resulting table rows are sorted by time in descending order. The third row corresponds to the version of the row in table emp inserted into the table when the table was created. The second row corresponds to the row in emp that was deleted by the erroneous transaction. The first row corresponds to the reinserted version of the row in emp with the new employee's name.

The DBA identifies transaction 030002002B210000 as an error transaction and uses Oracle Flashback Transaction Query to audit all changes made by this transaction:

SELECT  xid, start_scn, commit_scn, operation, logon_user, undo_sql
FROM flashback_transaction_query
WHERE xid = HEXTORAW('030002002B210000');

The result is similar to:

XID               START_SCN COMMIT_SCN OPERATION LOGON_USER
---------------- ---------- ---------- --------- ------------------------------
UNDO_SQL
--------------------------------------------------------------------------------
 
030002002B210000   10093452   10093459 DELETE    HR
insert into "HR"."EMP"("EMPNO","EMPNAME","SALARY") values ('111','Mike','655');
 
030002002B210000   10093452   10093459 INSERT    HR
delete from "HR"."DEPT" where ROWID = 'AAATjuAAEAAAAJrAAB';
 
030002002B210000   10093452   10093459 UPDATE    HR
update "HR"."EMP" set "SALARY" = '555' where ROWID = 'AAATjsAAEAAAAJ7AAA';
 
030002002B210000   10093452   10093459 BEGIN     HR
 
 
4 rows selected.

The above results are in positive order, and actually correspond to the following transactions before:

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

To view details of the erroneous transaction and all subsequent transactions, the database administrator executes the following query:

COLUMN operation FORMAT A9
COLUMN table_name FORMAT A10
COLUMN table_owner FORMAT A11

SELECT xid, start_scn, commit_scn, operation, table_name, table_owner
FROM flashback_transaction_query
WHERE table_owner = 'HR'
AND start_timestamp >=
  TO_TIMESTAMP ('2002-04-16 11:00:00','YYYY-MM-DD HH:MI:SS');

The result is similar to:

XID               START_SCN COMMIT_SCN OPERATION TABLE_NAME TABLE_OWNER
---------------- ---------- ---------- --------- ---------- -----------
02000E0074200000   10093435   10093446 INSERT    DEPT       HR
030002002B210000   10093452   10093459 DELETE    EMP        HR
030002002B210000   10093452   10093459 INSERT    DEPT       HR
030002002B210000   10093452   10093459 UPDATE    EMP        HR
0800120096200000   10093374   10093375 INSERT    EMP        HR
09001100B2200000   10093462   10093466 UPDATE    EMP        HR
09001100B2200000   10093462   10093466 UPDATE    EMP        HR
09001100B2200000   10093462   10093466 INSERT    EMP        HR
 
8 rows selected.

Note: Since the preceding query does not specify an XID in the WHERE clause, it scans many irrelevant rows, reducing performance.

Note that in order to make the self-test results exactly the same as above, you need to complete the settings in the section Configuring Your Database for Oracle Flashback Technology, and grant the corresponding permissions to the hr user. Otherwise there will be minor differences.

Using DBMS_FLASHBACK Package

The DBMS_FLASHBACK package provides the same functionality as Oracle Flashback Query, but Oracle Flashback Query is sometimes more convenient .

The DBMS_FLASHBACK package is like a time machine: you can turn back the clock, execute normal queries as if at an earlier time, and come back to the present. Since you can use the DBMS_FLASHBACK package to perform queries on past data without special clauses such as AS OF or VERSIONS BETWEEN, you can reuse existing PL/SQL code to query the database earlier.

You must have EXECUTE permission on the DBMS_FLASHBACK package.

Using the DBMS_FLASHBACK package in PL/SQL code:

  1. Specify a time in the past by calling DBMS_FLASHBACK.ENABLE_AT_TIME or DBMS_FLASHBACK.ENABLE_AT_SYSTEM_CHANGE_NUMBER.
  2. Execute regular queries (that is, queries without special flashback feature syntax such as AS OF). Do not perform DDL or DML operations. Queries the database at a specified past time.
  3. Return to the present by calling DBMS_FLASHBACK.DISABLE.
    You must call DBMS_FLASHBACK.DISABLE before calling DBMS_FLASHBACK.ENABLE_AT_TIME or DBMS_FLASHBACK.ENABLE_AT_SYSTEM_CHANGE_NUMBER again. You cannot nest enable/disable pairs.

To use a cursor to store query results, open the cursor before calling DBMS_FLASHBACK.DISABLE. After storing the results and calling DBMS_FLASHBACK.DISABLE, you can:

Perform INSERT or UPDATE operations using past stored results to modify the current database state.

Compare current data with past data. After calling DBMS_FLASHBACK.DISABLE, open the second cursor. Get from the first cursor to retrieve past data; get from the second cursor to retrieve current data. You can store past data in a temporary table, then use set operators such as MINUS or UNION to compare or combine past and current data.

You can call DBMS_FLASHBACK.GET_SYSTEM_CHANGE_NUMBER at any time to get the current system change number (SCN). DBMS_FLASHBACK.GET_SYSTEM_CHANGE_NUMBER returns the current SCN, regardless of whether DBMS_FLASHBACK.ENABLE was called before.

Using Flashback Transaction

The DBMS_FLASHBACK.TRANSACTION_BACKOUT procedure rolls back a transaction and its dependent transactions while the database remains online. This recovery operation uses the undo data to create and run compensating transactions that return the affected data to its original state.

Transactions that are rolled back are subject to the following restrictions:

  • They cannot perform DDL operations that change the logical structure of the database tables.
  • They cannot use large object (LOB) data types:
    • BFILE
    • BLOB
    • CLOB
    • NCLOB
  • They cannot use features that LogMiner does not support.
    The features supported by LogMiner depend on the value of the COMPATIBLE initialization parameter for the database whose transaction is being rolled back. The default is the version number of the latest major release.
    Flashback Transaction inherits LogMiner's support for SQL data types. Therefore, if LogMiner fails due to an unsupported SQL datatype in the transaction, the flashback transaction will also fail.
    Certain data types, although supported by LogMiner, do not generate undo information as part of operations that modify such columns. Therefore, Flashback Transactions does not support tables containing these data types. These include tables with BLOB, CLOB, and XML types.

A transaction dependency means that in the context of a flashback transaction, transaction 2 can depend on transaction 1 in any of the following ways:

  • Write-Write Dependency
    Transaction 1 changes a row of the table, and transaction 2 subsequently changes the same row.
  • Primary key dependency
    A table has a primary key constraint on column c. In one row of the table, column c has the value v. Transaction 1 deletes the row, and then transaction 2 inserts a row into the same table, assigning the value v to column c.
  • Foreign key dependency
    In table b, column b1 has a foreign key constraint on column a1 of table a. Transaction 1 changes the value in a1, and then transaction 2 changes the value in b1.

The parameters of the TRANSACTION_BACKOUT procedure are:

  • number of transactions to roll back
  • List of transactions to undo, identified by name or XID
  • Time hint, if you identify transactions by name
  • Specifies a time before any transaction starts.
  • Backout options in the table below
options describe
CASCADE Undo the specified transaction and all dependent transactions in a sequential fashion (that is, first undo the parent transaction, then undo the child transactions).
Without CASCADE, it will error if no dependent transactions are specified.
NOCASCADE default. Cancels the specified transactions, which should have no dependent transactions. The first related transaction resulted in an error and appeared in *_FLASHBACK_TXN_REPORT.
NOCASCADE_FORCE Roll back the specified transaction, ignoring related transactions. The server runs the undo SQL statements for the specified transaction in reverse order of commit time.
If the constraints are not broken and you are happy with the result, you can commit the changes; otherwise, you can roll them back.
NONCONFLICT_ONLY Cancels changes to nonconflicting rows of the specified transaction. The database remains consistent, but transaction atomicity is lost.

TRANSACTION_BACKOUT analyzes transaction dependencies, performs DML operations, and generates reports. TRANSACTION_BACKOUT does not commit the DML operations it performs as part of transaction undo, but it holds all required locks on rows and tables in the correct form, preventing other dependencies from entering the system. To make transaction revocation permanent, you must explicitly commit the transaction.

To see the reports generated by TRANSACTION_BACKOUT, query the static data dictionary views *_FLASHBACK_TXN_STATE and *_FLASHBACK_TXN_REPORT.

The static data dictionary views *_FLASHBACK_TXN_STATE show whether a transaction is active or aborted. If a transaction appears in this view, it will be cancelled.

*_FLASHBACK_TXN_STATEMaintained atomically to compensate for transactions. If the compensating transaction is reversed, all changes it made are also reversed, *_FLASHBACK_TXN_STATE reflects this. For example, if compensating transaction ct undoes transactions t1 and t2, then t1 and t2 appear in *_FLASHBACK_TXN_STATE. If ct itself is later revoked, the effects of t1 and t2 are restored, and t1 and t2 disappear from *_FLASHBACK_TXN_STATE.

The static data dictionary views *_FLASHBACK_TXN_REPORT provide detailed reports for each transaction rolled back.

Using Flashback Time Travel

It can be considered that Flashback Time Travel and Flashback Data Archive are equivalent, and the former is based on the technology of the latter

Flashback time travel provides the ability to track and store transactional changes during the lifetime of a table.

Flashback time travel is useful for compliance with record phase policies and audit reports.

Flashback Archive (Flashback Archive) consists of one or more table spaces or a part of them. You can have multiple flashback archives. If you are logged in as SYSDBA, you can specify a default Fashback Archive for the system. Flashback Archives are configured with a retention time . Data archived in a flashback archive will be retained for the retention time specified when the flashback archive was created.

When choosing a flashback archive for a particular table, consider the table's data retention requirements and the retention time of the flashback archive for which you have the FLASHBACK ARCHIVE object privilege.

By default, Flashback Archive is not enabled for any table. Consider enabling Flashback Archive for user context tracking and database hardening.

  • User context tracking . Metadata information used to track transactions can include (if the feature is enabled) user context, which makes it easier to determine which user made which changes to a table.
    To set the user context level (determine how much user context to save), use the DBMS_FLASHBACK_ARCHIVE.SET_CONTEXT_LEVEL procedure. To access context information, use the DBMS_FLASHBACK_ARCHIVE.GET_SYS_CONTEXT function.
  • Database hardening . You can associate a set of tables together in the Application, and enable Flashback Archive on all of them with a single command. Database hardening also enables you to lock all tables with a single command, preventing any DML on those tables until they are subsequently unlocked. Database Hardening is designed to make it easier to use Flashback Time Travel to track and secure an application's security-sensitive tables.
    To register an application for database hardening, use the DBMS_FLASHBACK_ARCHIVE.REGISTER_APPLICATION procedure, which is described in Oracle Database PL/SQL Packages and Types Reference.

You can also use Flashback Time Travel in various scenarios such as forced digital shredding, access to historical data, selective data recovery and auditing.

flashback time travel restrictions

  • You cannot enable Flashback Archive on tables with LONG datatype or nested table columns.
  • You cannot enable Flashback Archive on nested tables, temporary tables, external tables, materialized views, advanced query (AQ) tables, mixed partition tables, or non-table objects.
  • Flashback Archive does not support DDL statements that move, split, merge, or merge partitions or subpartitions, move tables, or convert LONG columns to LOB columns.
  • Adding or enabling constraints (including foreign key constraints) on a table with Flashback Archive enabled fails with ORA-55610. Support for dropping or disabling constraints (including foreign key constraints) on tables that have Flashback Archive enabled.
  • After enabling Flashback Archive on a table, Oracle recommends initially waiting at least 20 seconds before inserting data into the table, and waiting up to 5 minutes before using Flashback Query on the table.
  • Dropping a Flashback Archive base table requires disabling Flashback Archive on the base table before dropping the base table. Disabling the Flashback Archive will delete the historical data, while disassociating the Flashback Archive will preserve the historical data. On the other hand, truncation of base tables is supported, and historical data will remain available in the flashback archive.
  • If Flashback Archive is enabled on a table, but Automatic Undo Management (AUM) is disabled, an ORA-55614 error occurs when you try to modify the table.
  • Flashback Archive cannot be enabled if the table uses any of the following Flashback Time Travel reserved words as column names: STARTSCN, ENDSCN, RID, XID, OP, OPERATION.

20.9.1 DDL Statements on Tables Enabled for Flashback Archive

Flashback Archive supports only these DDL statements:

  • An ALTER TABLE statement that does any of the following:
    • Add, delete, rename or modify columns
    • Add, delete or rename constraints
    • Delete or truncate partition or subpartition operations
  • truncate table statement
  • RENAME statement to rename a table

Flashback Archive does not support DDL statements that move, split, merge, or merge partitions or subpartitions, move tables, or convert LONG columns to LOB columns.

For example, the following DDL statement causes error ORA-55610 when used on a table enabled for Flashback Archive:

  • ALTER TABLE statement that includes an UPGRADE TABLE clause, with or without an INCLUDING DATA clause
  • ALTER TABLE statement for move or exchange partition or subpartition operations
  • DROP TABLE statement

If you must use unsupported DDL statements on a table enabled for Flashback Archive, use the DBMS_FLASHBACK_ARCHIVE.DISASSOCIATE_FBA procedure to disassociate a base table from its Flashback Archive . To later reassociate the flashback archive with the base table, use the DBMS_FLASHBACK_ARCHIVE.REASSOCIATE_FBA procedure. Additionally, to drop a table enabled for Flashback Archive, you must first disable Flashback Archive on the table using the ALTER TABLE ... NO FLASHBACK ARCHIVE clause.

20.9.2 Creating a Flashback Archive

You can create a flashback archive using the CREATE FLASHBACK ARCHIVE statement.

Create a flashback archive using the CREATE FLASHBACK ARCHIVE statement, specifying:

  • The name of the flashback archive
  • The name of the first tablespace for the flashback archive
  • (Optional) The maximum amount of space that the flashback archive can use in the first tablespace.
    The default is unlimited. You must specify this value unless your space quota on the first tablespace is also unlimited; otherwise, an ORA-55621 error will occur.
  • Retention time (the number of days the table's flashback archive data is guaranteed to be stored)
  • (Optional) Whether to optimize data storage in history tables maintained in Flashback Archive, use [NO] OPTIMIZE DATA.
    The default is to not optimize data.

If you are logged in as SYSDBA, you can also specify that this is the system's default flashback archive. If this option is omitted, you can still make this flashback archive the default at a later stage.

Oracle recommends that all users who must use Flashback Archive have unlimited quotas on the Flashback Archive tablespace; however, if this is not the case, you must grant these users sufficient quota on the tablespace.

Example:

CREATE FLASHBACK ARCHIVE DEFAULT fla1 TABLESPACE tbs1
  QUOTA 10G RETENTION 1 YEAR;
CREATE FLASHBACK ARCHIVE fla2 TABLESPACE tbs2 RETENTION 2 YEAR;

20.9.3 Altering a Flashback Archive

With the ALTER FLASHBACK ARCHIVE statement, you can:

  • Changing the retention time for flashback archives
  • Clear some or all data
  • Add, modify and drop tablespaces. NOTE: Deleting all tablespaces for the flashback archive will result in an error.

If you are logged in as SYSDBA, you can also use the ALTER FLASHBACK ARCHIVE statement to make a specific file the system's default flashback archive.

Example:

ALTER FLASHBACK ARCHIVE fla1 SET DEFAULT;
ALTER FLASHBACK ARCHIVE fla1 ADD TABLESPACE tbs3 QUOTA 5G;
ALTER FLASHBACK ARCHIVE fla1 ADD TABLESPACE tbs4;
ALTER FLASHBACK ARCHIVE fla1 MODIFY TABLESPACE tbs3 QUOTA 20G;
ALTER FLASHBACK ARCHIVE fla1 MODIFY TABLESPACE tbs1;
ALTER FLASHBACK ARCHIVE fla1 MODIFY RETENTION 2 YEAR;
-- 表空间 tbs2 未被删除。
ALTER FLASHBACK ARCHIVE fla1 REMOVE TABLESPACE tbs2;
ALTER FLASHBACK ARCHIVE fla1
  PURGE BEFORE TIMESTAMP (SYSTIMESTAMP - INTERVAL '1' DAY);
ALTER FLASHBACK ARCHIVE fla1 PURGE BEFORE SCN 728969;

20.9.4 Dropping a Flashback Archive

You can delete a flashback archive with the DROP FLASHBACK ARCHIVE statement.

Deleting a flashback archive deletes its historical data, but not its tablespaces.

Example:

DROP FLASHBACK ARCHIVE fla1;

20.9.5 Specifying the Default Flashback Archive

You can specify a default flashback archive using the CREATE or ALTER FLASHBACK ARCHIVE statement.

The system's default flashback archive is the default flashback archive for every user who does not have their own default flashback archive.

By default, the system does not have a default Flashback Archive. If you are logged in as SYSDBA, you can specify a default flashback archive in any of the following ways:

  • Specify the name of an existing flashback archive in the SET DEFAULT clause of the ALTER FLASHBACK ARCHIVE statement. For example:
ALTER FLASHBACK ARCHIVE fla1 SET DEFAULT;
  • When creating a flashback archive, include DEFAULT in the CREATE FLASHBACK ARCHIVE statement. For example:
CREATE FLASHBACK ARCHIVE DEFAULT fla2 TABLESPACE tbs1
  QUOTA 10G RETENTION 1 YEAR;

20.9.6 Enabling and Disabling Flashback Archive

By default, Flashback Archive is disabled for all tables. You can enable Flashback Archive for a table if you have the FLASHBACK ARCHIVE object permission on the Flashback Archive used for that table.

To enable Flashback Archive for a table, include the FLASHBACK ARCHIVE clause in the CREATE TABLE or ALTER TABLE statement. In the FLASHBACK ARCHIVE clause, you can specify the flashback archive that stores the historical data of the table. The default is the system's default flashback archive. An error will occur if you specify a flashback archive that does not exist.

An error occurs if a table has flashback archive enabled and you try to enable it again with a different flashback archive.

Once Flashback Archive is enabled for a table, it can only be disabled if you have the FLASHBACK ARCHIVE ADMINISTER system privilege or are logged in as SYSDBA. To disable flashback archiving for a table, specify NO FLASHBACK ARCHIVE on the ALTER TABLE statement. (It is not necessary to specify NO FLASHBACK ARCHIVE on the CREATE TABLE statement, as this is the default.)

Example:

CREATE TABLE employee (EMPNO NUMBER(4) NOT NULL, ENAME VARCHAR2(10),
  JOB VARCHAR2(9), MGR NUMBER(4)) FLASHBACK ARCHIVE;
CREATE TABLE employee (EMPNO NUMBER(4) NOT NULL, ENAME VARCHAR2(10),
  JOB VARCHAR2(9), MGR NUMBER(4)) FLASHBACK ARCHIVE fla1;
ALTER TABLE employee FLASHBACK ARCHIVE;
ALTER TABLE employee FLASHBACK ARCHIVE fla1;
ALTER TABLE employee NO FLASHBACK ARCHIVE;

20.9.7 Viewing Flashback Archive Data

You can view information about flashback archive files in the static data dictionary view.

view describe
*_FLASHBACK_ARCHIVE Display information about flashback archive files
*_FLASHBACK_ARCHIVE_TS show tablespaces for flashback archive files
*_FLASHBACK_ARCHIVE_TABLES Display information about tables enabled for flashback archive

20.9.8 Transporting Flashback Archive Data between Databases

You can export and import Flashback Archive base tables along with their history to another database using the FLASHBACK_ARCHIVE_MIGRATE package and the Oracle Transportable Tablespaces feature.

DBMS_FLASHBACK_ARCHIVE_MIGRATE Allows migrating Flashback Archive enabled tables from a database on any version where this package exists to any database on any version that supports flashback time travel.

20.9.9 Flashback Time Travel Scenarios

Scenario: Using Flashback Time Travel to Implement Digital Shredding
Your company wants to "shred" (delete) historical data changes to the Taxes table after ten years. When you created the flashback archive for the Taxes table, you specified a ten-year retention period:

CREATE FLASHBACK ARCHIVE taxes_archive TABLESPACE tbs1 RETENTION 10 YEAR;

When historical data from tax transactions is older than ten years, it is purged. (The tax forms themselves, as well as transaction history data less than ten years old, are not purged.)

Scenario: Using Flashback Time Travel to Access Historical Data
You want to be able to retrieve the stock of all items at the beginning of the year from the table inventory, and the stocks for each symbol in the portfolio from the table stock_data at the close of business on any specified day of the year price.

CREATE FLASHBACK ARCHIVE DEFAULT fla1 TABLESPACE tbs1
  QUOTA 10G RETENTION 5 YEAR;
ALTER TABLE inventory FLASHBACK ARCHIVE;
ALTER TABLE stock_data FLASHBACK ARCHIVE;
-- 要检索 2007 年初所有项目的库存
SELECT product_number, product_name, count FROM inventory AS OF
  TIMESTAMP TO_TIMESTAMP ('2007-01-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS');
-- 要在 2007 年 7 月 23 日收盘时检索投资组合中每个代码的股票价格
SELECT symbol, stock_price FROM stock_data AS OF
  TIMESTAMP TO_TIMESTAMP ('2007-07-23 16:00:00', 'YYYY-MM-DD HH24:MI:SS')
  WHERE symbol IN my_portfolio;

Scenario: Generating Reports Using Flashback Time Travel
You want users to be able to generate reports from the table investments for data stored over the past five years.
There seems to be no difference from the previous scene.

CREATE FLASHBACK ARCHIVE DEFAULT fla2 TABLESPACE tbs1
  QUOTA 20G RETENTION 5 YEAR;
ALTER TABLE investments FLASHBACK ARCHIVE;
SELECT * FROM investments AS OF
  TIMESTAMP TO_TIMESTAMP ('2006-12-31 16:00:00', 'YYYY-MM-DD HH24:MI:SS')
  WHERE name = 'LISA';

Scenario: Audit Using Flashback Time Travel
A health insurance company must audit a medical clinic.

CREATE FLASHBACK ARCHIVE DEFAULT fla4 TABLESPACE tbs1
  QUOTA 100G RETENTION 10 YEAR;
ALTER TABLE Billings FLASHBACK ARCHIVE;
-- 2007 年 5 月 1 日,客户在某些诊断和测试中被收取了错误的费用。 
-- 要查看截至 2007 年 5 月 1 日的记录,公司使用以下查询:
SELECT date_billed, amount_billed, patient_name, claim_Id,
  test_costs, diagnosis FROM Billings AS OF TIMESTAMP
  TO_TIMESTAMP('2007-05-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS');

Scenario: Restoring Data Using Flashback Time Travel
An end user recovers from a previously committed erroneous transaction in the database. The undo data for the erroneous transaction is no longer available, but Flashback Query works seamlessly because the required historical information is available in the Flashback Archive.

Lisa manages a software development group whose products are selling well. On November 3, 2007, she decided to give all three-level employees with more than two years of work experience a 10% salary increase and a promotion to four levels. Lisa asks Bob, her human resources representative, to make a change.

Using the HR web application, Bob updates the employee table, giving Lisa's third-level employee a 10% raise and a promotion to fourth-level. Bob then comes home from work for the day, unaware that he's ignoring the two-year work experience requirement in the deal. A few days later, Lisa checks to see if Bob has completed the update and sees that everyone in the group has gotten a raise! She immediately called Bob and asked him to correct the mistake.

At first, Bob thinks that there is no way to restore the employee table to its previous state without taking a backup. Then he remembered that the employee table had flashback archive enabled.

First, he verifies that no other transaction modified the employees table after him: the transaction query's commit timestamp corresponds to Bob's transaction two days ago.

Next, Bob uses these statements to restore the employee table to the state it was in before his erroneous change:

DELETE EMPLOYEE WHERE MANAGER = 'LISA JOHNSON';
INSERT INTO EMPLOYEE
  SELECT * FROM EMPLOYEE
    AS OF TIMESTAMP (SYSTIMESTAMP - INTERVAL '2' DAY)
      WHERE MANAGER = 'LISA JOHNSON';

General Guidelines for Oracle Flashback Technology

Consider these best practices when using the flashback technique.

  • Avoid issuing Flashback Queries on a table before Flashback Archive is enabled on the table. Yes, enable Flashback Archive before performing any DML operations on the table.
-- 在此示例中,操作序列将返回 a=1 的行。 
-- 这可能看起来像一个不正确的结果,为避免这种情况,您必须在插入任何行之前启用闪回存档。
CREATE TABLE foo (a NUMBER);
VAR scn NUMBER;
BEGIN 
   SELECT DBMS_FLASHBACK.GET_SYSTEM_CHANGE_NUMEBR INTO :scn FROM DUAL;
END;
INSERT INTO foo VALUES (1);
COMMIT;
ALTER TABLE foo FLASHBACK ARCHIVE;
UPDATE foo SET a=2 WHERE a=1;
COMMIT;
SELECT * FROM foo AS OF SCN :scn;
  • Use the DBMS_FLASHBACK.ENABLE and DBMS_FLASHBACK.DISABLE procedures around SQL code that you do not control, or when you want to use the same past time for multiple consecutive queries.
  • For convenience, use Oracle Flashback Query, Oracle Flashback Version Query, or Oracle Flashback Transaction Query for the SQL code you write. For example, Oracle Flashback Query is flexible enough to compare and store results in a single query.
  • To get the SCN to use the flashback feature later, use DBMS_FLASHBACK.GET_SYSTEM_CHANGE_NUMBER.
  • To calculate or retrieve past times for use in queries, use the function return value as the timestamp or SCN parameter. For example, add or subtract an INTERVAL value to or from the value of the SYSTIMESTAMP function.
  • Use Oracle Flashback Query, Oracle Flashback Version Query, and Oracle Flashback Transaction Query locally or remotely. An example of a remote Oracle Flashback Query is:
SELECT * FROM employees@some_remote_host AS OF 
    TIMESTAMP (SYSTIMESTAMP - INTERVAL '60' MINUTE);
  • To ensure database consistency, perform a COMMIT or ROLLBACK operation before querying past data.
  • Remember that all flashback processing uses the current session settings, such as national language and character set, not the settings in effect at the time of the query.
  • Keep in mind that DDL that changes the structure of a table (such as dropping/modifying columns, moving tables, dropping partitions, truncating tables/partitions, and adding constraints) invalidates any existing undo data for the table . Error ORA-01466 occurs if you attempt to retrieve data from some time before such DDL was executed. DDL operations that change table storage attributes (such as PCTFREE, INITRANS, and MAXTRANS) do not invalidate undo data.
  • To query past data at a precise time, use SCN. If you use timestamps, the actual query time may be up to 3 seconds earlier than the time you specify . Oracle Database uses SCNs internally and maps them to timestamps with a granularity of 3 seconds.
    For example, suppose SCN values ​​1000 and 1005 map to timestamps 8:41 AM and 8:46 AM, respectively. Queries between 8:41:00 and 8:45:59 AM map to SCN 1000; Oracle Flashback Query at 8:46 AM maps to SCN 1005. Therefore, if you specify a time later than a DDL operation (such as creating a table), Oracle Database may use the SCN immediately before the DDL operation, resulting in error ORA-01466.
  • You cannot retrieve past data from dynamic performance (V$) views. Queries on such views return the current data.
  • You can perform queries on past data in static data dictionary views such as *_TABLES.
    Note: If past data cannot be retrieved using static data dictionary views, the corresponding base tables can be queried to retrieve the data. However, Oracle does not recommend that you use the base tables directly because they are normalized and most data is stored in an encrypted format.
  • You can enable data storage optimization for a history table maintained by Flashback Archive by specifying OPTIMIZE DATA when creating or altering the Flashback Archive history table.
    OPTIMIZE DATA optimizes the storage of data in the history table by using any of the following functions, the default is not to optimize the storage of data in the history table. :
    • Advanced Row Compression
    • Advanced LOB Compression
    • Advanced LOB Deduplication
    • Segment-level compression tiering
    • Row-level compression tiering
  • After creating a VPD policy, consider creating an equivalent policy for the Flashback Archive history table.

Performance Guidelines for Oracle Flashback Technology

  • Use the DBMS_STATS package to generate statistics for all tables involved in Oracle Flashback Query. Keep up-to-date statistics. Oracle Flashback Query uses a cost-based optimizer that relies on these statistics.

  • Minimize the amount of undo data that must be accessed. Use a query to select a small collection of past data using an index, rather than scanning the entire table. If a full table must be scanned, add a parallel hint to the query.
    The performance cost in I/O is the cost of paging in data and undo blocks that are not in the buffer cache. The performance cost of CPU usage is the cost of applying the undo information to the affected data blocks. Flashback operations are CPU bound when operating on recent changes .
    Oracle recommends that you have sufficient buffer cache so that the archiver's version queries find undo data in the buffer cache. Buffer cache access is significantly faster than disk access.

  • If performing very large transactions on the tracking table (for example, affecting more than 1 million rows), set the large pool size high enough (at least 1 GB) so that parallel queries do not have to allocate new blocks from the SGA.

  • For Oracle Flashback Edition queries, an index structure is used. Oracle Database retains undo data for index changes and data changes. The performance of Oracle Flashback Edition queries based on index lookups is an order of magnitude faster than full table scans that would otherwise be required.

  • In Oracle Flashback Transaction Query, the xid column is of type RAW(8). To take advantage of an index built on the xid column, use the HEXTORAW conversion function: HEXTORAW(xid).

  • Oracle Flashback Query against materialized views does not take advantage of query rewrite optimizations.

Multitenant Container Database Restrictions for Oracle Flashback Technology

These Oracle Flashback Technology features are not available for multi-tenant container databases (CDB):

  • CDBs in shared undo mode do not support Flashback Transactional Queries. It is only supported in native undo mode.
  • CDB does not support flashback transaction rollback.

Using Flashback Database and Restore Points

For details, see Chapter 7 of the Database Backup and Recovery Guide: Using Flashback Database and Restore Points

Use RMAN to configure, monitor, and maintain restore points as part of an overall data protection strategy.

This chapter describes Flashback Database and restore points. It discusses configuring, monitoring, and maintaining these functions as part of an overall data protection strategy.

Note: For more information on recovery scenarios using Flashback Database and normal and guaranteed restore points, see Chapter 18: Performing Flashback and Database Point-in-Time Recovery .

7.1 Overview of Flashback Database, Restore Points and Guaranteed Restore Points

Oracle Flashback Database and Recovery Points are related data protection features that enable you to rewind data in time to correct any problems caused by logical data corruption or user error within a specified time window.

These features provide a more efficient alternative to point-in-time recovery and do not require the database to be backed up before recovery. The effect is similar to database point-in-time recovery (DBPITR). Flashback Database and Restore Points are not only useful in traditional database recovery situations, but also in database upgrades, application deployments, and testing scenarios where test databases must be created and recreated quickly. Flashback Database also provides an efficient alternative to rebuilding a failed primary database after a Data Guard failover .

Restore points provide functionality related to Flashback Database and other media recovery operations. In particular, a guaranteed restore point created at a system change number (SCN) ensures that you can use Flashback Database to rewind the database back to this SCN. You can use Restore Points and Flashback Database independently or together.

Flashback Database can be accessed through RMAN and SQL as FLASHBACK DATABASE. You can quickly recover databases from logical data corruption or user error in any language. The following example returns the database to the specified SCN or restore point:

FLASHBACK DATABASE TO RESTORE POINT 'before_upgrade';
FLASHBACK DATABASE TO SCN 202381;

7.1.1 About Flashback Database

Flashback Database is similar in effect to traditional point-in-time recovery. It enables you to restore the database to its state at some recent time. Flashback Database is much faster than point-in-time recovery because it does not require datafiles to be restored from backup and fewer changes need to be applied from archived redo logs.

If the data files are intact, you can use Flashback Database to recover most unwanted changes to the database. You can return a database to its previous incarnation state and undo the effects of the ALTER DATABASE OPEN RESETLOGS statement. " Rewinding a Database Using Flashback Database " explains how to use the FLASHBACK DATABASE command to reverse database changes.

The definition of incarnation is as follows:

A separate version of a database. The incarnation of the database changes when you open it with the RESETLOGS option, but you can recover backups from a prior incarnation so long as the necessary redo is available.

Flashback Database uses its own logging mechanism, creating flashback logs and storing them in the flash recovery area. You can only use Flashback Database if flashback logs are available. To take advantage of this feature, you must set up your database in advance to create flashback logs.

To enable Flashback Database, you need to configure a flash recovery area and set a flashback retention target . This retention target specifies how long you can rewind the database using Flashback Database.

From then on, the database periodically copies an image of every changed block in every datafile into the flashback log. These block images can later be reused to reconstruct the data file content at any point in time the log was captured.

When you use Flashback Database to rewind a database to a target time in the past, the command determines which blocks changed after the target time and restores them from the flashback logs. The database restores the version of each block immediately before the target time. The database then uses the redo logs to reapply the changes made after those blocks were written to the flashback logs.

Redo logs on disk or tape must be available for the entire time period spanned by flashback logs. For example, if the flashback retention target is 1 week, you must ensure that you have access to the online and archived redo logs that contain all changes from the past week . In practice, redo logs typically take much longer than the flashback retention target to support point-in-time recovery.

7.1.2 About Flashback Database Window

The SCN range that currently has enough flashback log data to support the FLASHBACK DATABASE command is called the Flashback Database window. The Flashback Database window cannot extend further than the earliest SCN in the available flashback logs.

You cannot back up flashback logs to a location other than the flash recovery area. To increase the likelihood of retaining enough flashback logs to fit the Flashback Database window, you can increase the space in the flash recovery area.

If the flash recovery area is not large enough to accommodate files such as flashback logs and archived redo logs and other backups required by the retention policy, the database may delete flashback logs from the earliest SCN onwards to make room for other files . Therefore, the Flashback Database window may be shorter than the Flashback Retention Target, depending on the size of the flash recovery area, other backups that must be retained, and how much Flashback Log data is required. The Flashback Reserved Target is a target and does not guarantee that Flashback Database will be available .

If you cannot use FLASHBACK DATABASE because the Flashback Database window is not long enough, you can usually use database point-in-time recovery (DBPITR) to achieve similar results. Guaranteed restore points are the only way to ensure that you can go back to a specific point in time using Flashback Database or to guarantee the size of the flashback window .

Note: Certain database operations, such as dropping tablespaces, cannot be reversed using Flashback Database. For more information, see " Limitations of Flashback Database ."

7.1.3 Limitations of Flashback Database

Because Flashback Database works by undoing changes to data files that existed when the command was run, it has certain limitations.

  • Flashback Database can only undo changes made to the data files by Oracle Database. It cannot be used to repair media failure, or to recover from accidentally deleted data files.
  • You cannot use Flashback Database alone to retrieve lost data files. If you flash the database back to a time when the deleted datafile existed in the database, only the datafile entry will be added to the control file. Lost datafiles can only be recovered by using RMAN to fully restore and restore the datafiles.
  • If the database control file is restored or recreated from backup, all accumulated flashback log information will be discarded. You cannot use FLASHBACK DATABASE to go back to a point in time before the control file was restored or recreated.
  • When using Flashback Database with a target time in which a NOLOGGING operation is in progress, block corruption is likely to occur in the database objects and data files affected by the NOLOGGING operation. For example, if you perform a direct path INSERT operation in NOLOGGING mode, and the operation runs from 9:00 to 9:15 on April 3, 2005, you later use Flashback Database to go back to the target time of 09:07 at that One day, object and data files updated by a direct path INSERT may leave block corruption after the Flashback Database operation completes.
    If possible, avoid using Flashback Database with a target time or SCN that coincides with NOLOGGING operations. Also, perform a full or incremental backup of the affected datafiles immediately after any NOLOGGING operation to ensure recovery to a point in time after the operation. If you want to use Flashback Database to go back to a point in time during operations such as direct path INSERTs, consider doing so in LOGGING mode.

7.1.4 About Normal Restore Points

Creating a generic restore point assigns a restore point name to an SCN or a specific point in time.

Therefore, the restore point is used as a bookmark or alias for this SCN. Before doing anything you might have to undo, you can create a normal restore point. The control file stores the name and SCN of the restore point.

If you use flashback or point-in-time recovery, you can use the name of the restore point instead of time or SCN. The following commands support the use of restore points:

  • RECOVER DATABASE and FLASHBACK DATABASE commands in RMAN
  • FLASHBACK TABLE statement in SQL

Creating a normal restore point eliminates the need to manually record the SCN ahead of time or use features such as Flashback Query to determine the correct SCN after the fact.

Ordinary restore points are lightweight. The control file can maintain records of thousands of normal restore points without significant impact on database performance. Normal restore points eventually fall out of the control file if not manually deleted, so they do not require ongoing maintenance.

7.1.5 About Guaranteed Restore Points

Like normal restore points, guaranteed restore points act as an alias for the SCN during restore operations. A major difference is that restore points are guaranteed to never go beyond the scope of the control file and must be explicitly deleted .

In general, you can use a guaranteed restore point as an alias for the SCN and use any command that works for a normal restore point. Information about where and how to use normal restore points also applies to guaranteed restore points, unless otherwise noted.

Guaranteed restore points ensure that you can use Flashback Database to rewind the database to the state at the restore point SCN even if flashback log generation is disabled??? . If flashback logging is enabled, guaranteed restore points force retention of the flashback logs required by Flashback Database to any SCN after the earliest guaranteed restore point. Therefore, if you enable flashback logging, you can rewind the database to any SCN in the continuum, not just to a single SCN.

Note: If flashback logging is disabled, then you cannot directly flash the database back to the SCN guaranteed to be between the restore point and the current time. However, you can first flash back to the guaranteed restore point and then restore to an SCN between the guaranteed restore point and the current time.

If the recovery area has enough disk space to store the required logs, then you can use guaranteed restore points to rewind the entire database to a known good state from days or weeks ago. As with Flashback Database, even the effects of NOLOGGING operations (such as direct load inserts) can be reversed with guaranteed restore points.

Note: The limitations that apply to Flashback Database also apply to guaranteed restore points. For example, dropping a tablespace prevents the affected datafiles from being flashed back to a guaranteed restore point. For more information, see "Limitations of Flashback Database." Also, the database compatibility parameter cannot be set to a higher database version when there are guaranteed restore points in the database. Attempting to do so will result in an error. This limitation exists because Flashback Database currently cannot reverse the effect of increasing the database version with the compatibility initialization parameter.

In fact, guaranteed restore points provide a useful alternative to storage snapshots .

Storage snapshots are often used to protect databases before risky operations such as large-scale database updates or application patches or upgrades . Instead of creating snapshots or duplicating databases to test operations, you can create guaranteed restore points on the primary or physical standby database. You can then perform risky operations if you are sure you want to keep the required flashback logs.

7.1.6 Overview of Restore Points in a Multitenant Environment

You can create healthy and guaranteed restore points in a pluggable database (PDB). PDB restore points can only be accessed by the PDB that defines them.

PDB restore point

A PDB restore point is a bookmark to a point in time or SCN in a particular pluggable database (PDB). It applies only to the PDB for which it was created, and only for operations on that PDB. A PDB restore point represents a PDB subincarnation at the point in time it was created.

A PDB restore point can be either a normal restore point or a guaranteed restore point. A guaranteed PDB restore point guarantees that you can flashback the PDB to this restore point.

A PDB restore point can be used to perform a Flashback Database operation or point-in-time recovery of only the PDB in which it was created.

Note: Creating guaranteed PDB restore points requires careful consideration, as such restore points prevent re-use of the flashback logs required in a multi-tenant container database (CDB). This may affect the operation of the CDB as the flash recovery area may run out of space.

Clean up PDB restore points

A clean PDB restore point is a PDB restore point created when the PDB is shut down and the PDB has no outstanding transactions. Clean PDB restore points are only available for CDBs using shared undo.

Clean PDB restore points can be normal restore points or guaranteed restore points. Create a clean PDB restore point explicitly with the CREATE CLEAN RESTORE POINT command. For CDBs using shared undo, if the PDB is closed and has no outstanding transactions, any PDB restore points created will be marked as clean PDB restore points.

If you anticipate that you may need to rewind the PDB to a specific point in time, for example, to a state before an application upgrade, it is recommended that you create a clean PDB guaranteed restore point.

For a CDB that uses shared undo, Flashback Database operations are faster on clean PDB restore points than on SCN or other restore points that are not clean PDB restore points. This is because RMAN does not need to restore any backups when flashing back a clean PDB restore point.

Namespace for PDB restore points
Each pluggable database (PDB) has its own restore point namespace. Therefore, you can define PDB restore points with the same name in multiple PDBs.

In a multi-tenant environment, when you use a restore point name in a PDB or for PDB operations, the name is first interpreted as the PDB restore point for the associated PDB. If no PDB restore point with the specified name is found, it is interpreted as a CDB restore point.

7.2 About Logging for Flashback Database and Guaranteed Restore Points

Logging for Flashback Database and Guaranteed Restore Points involves capturing images of datafile blocks before changes are applied. The FLASHBACK DATABASE command can use these images to return datafiles to their previous state.

The main difference between normal flashback logging and guaranteed recovery point logging is when blocks are logged and whether the logs can be deleted in response to space pressure in the flash recovery area. These differences affect log space usage and database performance.

Your recoverability goals determine in part whether to enable logging for Flashback Database, use guaranteed restore points, or both. The performance and space usage impact of these features, whether used individually or together, can also influence your decision.

7.2.1 Guaranteed Restore Points and Fast Recovery Area Space Usage

Certain rules determine the use of space in the flash recovery area.

When you create guaranteed restore points, you must monitor the free space in the flash recovery area with or without full Flashback Database logging enabled. " Managing Flashback Log Space in the Flash Recovery Area " explains how to monitor flash recovery area disk space usage.

The following rules govern the creation, retention, overwriting, and deletion of flashback logs in the flash recovery area:

  • If the flash recovery area has sufficient space, create flashback logs if necessary to meet the flashback retention goal.
  • Flashback logs can be reused or deleted if they are old enough that they are no longer needed to meet the flashback retention goal.
  • If the database must create flashback logs and the flash recovery area is full or there is no disk space, the oldest flashback logs are reused.
    Note: Reusing the oldest flashback logs shortens the Flashback Database window . If enough flashback logs are reused due to insufficient disk space, the flashback retention goal may not be met.
  • If the fast recovery area is full, the archived redo logs that can be recovered according to the rules of the fast recovery area will be automatically deleted by the fast recovery area to make room for other files. In this case, any flashback logs that need to use that redo log file to use FLASHBACK DATABASE will also be deleted.
    According to the flash recovery area rules, a file is recyclable when one of the following conditions is met: (1) The file is reported as obsolete and not required by Flashback Database. For example, the file is outside the DB_FLASHBACK_RETENTION_TARGET parameter. (2) The file has been backed up to tape.
  • Files in the flash recovery area are not eligible for deletion or reuse if they are required to meet a guaranteed restore point. However, archived redo logs required to satisfy guaranteed restore points may be deleted after backup to disk or tape. When you use the RMAN FLASHBACK DATABASE command, if the archived redo logs required to satisfy the specified guaranteed restore point are not available in the flash recovery area, restore them from backup.
    Retaining flashback logs and other files required to satisfy guaranteed restore points, as well as files required to satisfy backup retention policies, can cause the flash recovery area to completely fill up. If your flash recovery area is full, see " Responding to a Full Flash Recovery Area ."

Warning: If no files are eligible for deletion from the flash recovery area due to the retention policy and the requirement to guarantee restore points, the database will behave as if it encountered a disk full condition. In many cases this will cause your database to stall. See " Responsively Full Flash Recovery Area ."

7.2.2 About Logging for Guaranteed Restore Points with Flashback Logging Disabled

Suppose you create guaranteed restore points when Flashback Database logging is disabled. In this case, when a datafile block is modified for the first time after a guaranteed recovery point, the database stores the pre-modified image of the block in the flashback log. Therefore, flashback logs preserve the contents of each changed data block when creating guaranteed restore points. Subsequent modifications to the same block will not cause the contents to be recorded again , unless another guaranteed restore point is created after the block was last modified, or a subsequent Flashback Database operation has restored the original contents of the block. When you use Flashback Database to restore a database to the same restore point multiple times, it is common practice to delete and recreate the guaranteed restore point each time . This will delete old flashback logs and ensure that the flash recovery area quota is not exceeded.

This method of recording has the following important consequences:

  • FLASHBACK DATABASE can use block images to recreate datafile content when a restore point is guaranteed.
  • For workloads that repeatedly modify the same data, disk space usage may be lower than normal flashback logging. Requires less space because each changed block is recorded only once . Applications with a small number of inserts may benefit from this disk space saving. This advantage is less likely for applications with high-volume or high-volume inserts. The performance overhead of logging for guaranteed restore points may also be lower without Flashback Database logging enabled.

Let's say your primary goal is to be able to restore the database to the time a guaranteed restore point was created. In this case, it is usually more efficient to turn off flashback logging and use only guaranteed restore points . For example, suppose you perform an application upgrade on your database host over the weekend. You can create a guaranteed restore point at the beginning of the upgrade. If the upgrade fails, use the FLASHBACK DATABASE command to undo the changes.

7.2.3 About Logging for Flashback Database with Guaranteed Restore Points Defined

If Flashback Database is enabled and one or more guaranteed restore points are defined, the database will perform normal flashback logging.

In this case, the recovery area retains the flashback logs required to flash back to any time between the current and current oldest defined guaranteed recovery point. Flashback logs are not deleted due to space pressure if required to meet guarantees.

Flashback logging incurs some performance overhead . Depending on the activity pattern on the database, it can also cause significant space pressure in the flash recovery area . Therefore, you should monitor the space used in the flash recovery area.

7.3 Prerequisites for Flashback Database and Restore Points

To ensure the successful operation of Flashback Database and guaranteed restore points, you must first set some key database options.
Flashback Database
Configure the following database settings before enabling Flashback Database:

  • Your database must be running in ARCHIVELOG mode because archive logs are used for Flashback Database operations.
  • You must enable the flash recovery area because flashback logs can only be stored in the flash recovery area.
  • For Oracle Real Application Clusters (Oracle RAC) databases, the flash recovery area must be in the cluster file system or in ASM.
  • To create a restore point in CDB, the COMPATIBLE initialization parameter must be set to 12.1.0 or later.

Guaranteed Restore Points
To use guaranteed restore points, the database must meet the following additional prerequisites: The COMPATIBLE initialization parameter must be set to 10.2.0 or higher.

Note: There are no special prerequisites that need to be set before using normal restore points.

Restore Points in PDBs
To create restore points in a pluggable database (PDB), the COMPATIBLE initialization parameter must be set to 12.2.0 or later.

7.4 Using Normal and Guaranteed Restore Points

You can create, monitor and delete normal and guaranteed restore points.

7.4.1 Creating CDB Restore Points

To create or guarantee a restore point in a multitenant container database (CDB), use the CREATE RESTORE POINT SQL command. Provide a name for the restore point and specify whether it is a guaranteed restore point or a normal restore point (default).

To create a CDB restore point:

  1. Make sure you meet the prerequisites described in Prerequisites for Flashback Database and restore points.
  2. Connect SQL*Plus to the root directory as a normal user with SYSDBA or SYSBACKUP authority.
  3. Make sure CDB is turned on or mounted. If the CDB is mounted, it must be cleanly shut down (unless it is a physical standby database).
  4. Run the CREATE RESTORE POINT statement to create a CDB restore point
CREATE RESTORE POINT cdb_before_upgrade;
CREATE RESTORE POINT cdb_grp_before_upgrade GUARANTEE FLASHBACK DATABASE;

7.4.2 Creating PDB Restore Points

You can use the CREATE RESTORE POINT SQL statement to create a normal PDB restore point, a guaranteed PDB restore point, or a clean PDB restore point in a pluggable database (PDB).

You can create a PDB restore point while connected to the PDB or the root directory. When the PDB uses shared undo, you can create a clean restore point only if the PDB does not have any outstanding transactions.

To create a PDB restore point while connected to the PDB :

  1. Make sure you meet the prerequisites described in Prerequisites for Flashback Database and restore points.
  2. Connect SQL*Plus to the PDB as a normal user or a local user with SYSDBA or SYSBACKUP authority.
  3. If you create a clean PDB restore point in a CDB that uses shared undo, you must shut down the PDB.
  4. If a multitenant container database (CDB) is mounted, it must always be down (unless it is a physical standby database).
  5. Set the current container to PDB.
  6. Create a PDB restore point using the CREATE RESTORE POINT command.

To create a PDB restore point while connected to CDB :

  1. Make sure you meet the prerequisites described in Prerequisites for Flashback Database and restore points.
  2. Connect SQL*Plus to the root directory of the target database as a normal user with SYSDBA or SYSBACKUP authority.
  3. If you create a clean PDB restore point in a CDB that uses shared undo, you must shut down the PDB.
  4. A CDB containing a PDB can be opened or loaded. If a CDB is installed, it must always be shut down (unless it is a physical standby database).
  5. Set current container as root
  6. Create a PDB restore point using the CREATE RESTORE POINT command with the FOR PLUGGABLE DATABASE clause

7.4.3 Listing Restore Points Using the LIST Command

Use the LIST command to list a specific restore point or all restore points known to the RMAN repository.

Example:

-- SQL Plus
LIST RESTORE POINT restore_point_name;
LIST RESTORE POINT ALL;
-- RMAN
LIST RESTORE POINT ALL;

Note: The LIST command does not display details such as the PDB incarnation number and whether the restore point is a PDB restore point. To view additional details about restore points in a multi-tenant environment, see the next section: List restore points using the V$RESTORE_POINT view.

7.4.4 Listing Restore Points Using the V$RESTORE_POINT View

You can use the V$RESTORE_POINT control file view to get information about all currently defined restore points (normal and guaranteed), including CDB restore points and PDB restore points.

The V$RESTORE_POINT view contains additional information about restore points in a multi-tenant environment that is not displayed by the LIST RESTORE POINT command. This includes details such as the pluggable database (PDB) incarnation that created the PDB restore point, and whether the restore point is a PDB restore point or a clean PDB restore point.

Example:

SELECT name, guarantee_flashback_database, pdb_restore_point, clean_pdb_restore_point, pdb_incarnation#, storage_sizeFROM v$restore_point;

NAME                         GUARANTEE_  PDB_RESTORE_POINT  CLEAN_PDB_RESTORE_POINT  STORAGE_SIZE
--------                     ----------  ----------------   -----------------------  ------------
CDB_GRP_BEFORE_PATCH            YES         NO                  NO                     84586
PDB_GRP_BEFORE_UPGRADE_TEMP     YES         YES                 NO                      4562
CDB_RP1                         NO          NO                  NO                         0
PDB1_BEFORE_PATCHING            NO          YES                 NO                         0
MYPDB_CLEAN_GRP_BEFORE_UPGRADE  NO          YES                 YES                        0    

For a normal restore point, STORAGE_SIZE is zero. For a guaranteed restore point, STORAGE_SIZE indicates the approximate number of bytes of disk space in the flash recovery area bound to hold the logs needed to guarantee a FLASHBACK DATABASE to that restore point.

7.4.5 Dropping Restore Points

You can use the DROP RESTORE POINT SQL*Plus statement to delete a restore point when you are sure that an existing restore point is not needed, or when you want to create a restore point using the name of an existing restore point.

SQL> DROP RESTORE POINT before_app_upgrade;
Restore point dropped.

The same statement is used to delete normal restore points and guaranteed restore points.

NOTE: Normal restore points will eventually age out of the control file, even if not explicitly deleted. The rules governing the retention of restore points in the control file are:

  • The most recent 2048 restore points are always kept in the control file, regardless of their age.
  • Any restore point newer than the value of CONTROL_FILE_RECORD_KEEP_TIME (default 7) will be kept, no matter how many restore points are defined.

Normal restore points that do not meet any of these conditions may age out of the control file.

Guaranteed that a restore point will never exceed the age of the control file. They persist until they are explicitly removed.

7.5 Using Flashback Database

To use flashback logging with the target database, you must enable Flashback Database. Certain guidelines can be followed to ensure optimal performance of Flashback Database.

7.5.1 Enabling Flashback Database

Enable Flashback Database using the ALTER DATABASE command.

To enable flashback logging:

  1. Configure the recovery area as described in "Enabling the Fast Recovery Area".
  2. Make sure the DB instance is turned on or mounted. If the instance is mounted, the database must be shut down cleanly, unless it is a physical standby database. Other Oracle Real Application Clusters (Oracle RAC) instances can be in any mode.
  3. (Optional) Set DB_FLASHBACK_RETENTION_TARGET to the length of the desired flashback window in minutes, the default is 1440 minutes, which is 1 day.
ALTER SYSTEM SET DB_FLASHBACK_RETENTION_TARGET=4320 SCOPE=BOTH; # 3 days
  1. Enable the Flashback Database feature for the entire database
ALTER DATABASE FLASHBACK ON;
  1. (Optional) Disable flashback logging for a specific tablespace. If you disable Flashback Database for a tablespace, you must take its datafiles offline before running Flashback Database.
    By default, flashback logs are generated for all permanent tablespaces. You can reduce overhead by disabling flashback logging for specific tablespaces, as the following example shows:
ALTER TABLESPACE tbs_3 FLASHBACK OFF;
-- ALTER TABLESPACE tbs_3 FLASHBACK ON;

When you enable Flashback Database while the database is open, there is a high chance that the command will not get the memory it needs. If the command fails because of this, retry the command later or after shutting down and restarting the instance.

When you enable Flashback Database on a physical standby database, you can flashback the standby database. The standby flashback database has some applications in the Data Guard environment .

7.5.2 Disabling Flashback Database Logging

Disable Flashback Database using the ALTER DATABASE command.

On a mounted or open DB instance, issue the following command:

ALTER DATABASE FLASHBACK OFF;

7.5.3 Configuring the Environment for Optimal Flashback Database Performance

Maintaining flashback logs has relatively limited overhead on the DB instance . Changed blocks are written from memory to the flashback log at relatively infrequent regular intervals to limit processing and I/O overhead.

To achieve good performance for large production databases with Flashback Database enabled, Oracle recommends the following:

  • Use a faster file system for your flash recovery area, preferably without an operating system file cache.
    The files created by the database in the flash recovery area (including the flashback logs) are usually very large. The operating system file cache is often ineffective for these files and may actually increase the CPU overhead of reading and writing them. Therefore, it is recommended to use a file system that avoids the operating system file cache, such as Automatic Storage Management (ASM).
  • Configure enough disk spindles for the file system holding the flash recovery area.
    For large production databases, multiple disk spindles may be required to support the disk throughput required for the database to efficiently write to the flashback log.
  • If the storage system used to hold the flash recovery area does not have non-volatile RAM, try configuring the file system on a striped storage volume.
    Use a relatively small stripe size, such as 128 KB. This technique enables each write to the flashback log to be distributed across multiple axes, improving performance.
  • For large databases, set the initialization parameter LOG_BUFFER to at least 8 MB.

The logging overhead for Flashback Database depends on the mix of reads and writes in the database workload. When you have a write-intensive workload, Flashback Database logging is expensive because it has to log all those database changes. Queries do not change data and therefore do not affect Flashback Database's logging activity.

7.5.4 Monitoring the Effect of Flashback Database on Performance

There are several data analysis methods that can be used to monitor the Flashback Database workload on a system.

  • AWR Reporting
    The Automatic Workload Repository (AWR) automatically collects database statistics by collecting, processing, and maintaining performance statistics for database problem detection and self-tuning. You can compare AWR reports before and after enabling Flashback Database to monitor performance impact.
  • AWR snapshots
    You can view AWR snapshots to pinpoint system usage caused by flashback logging. For example, if flashback buf free by RVWR is the top wait event, then you know that Oracle Database cannot write to the flashback log anytime soon. Therefore, you may wish to tune the file system and storage used by the flash recovery area, possibly using the techniques described in "Configuring Your Environment for Optimal Flashback Database Performance"
  • V$FLASHBACK_DATABASE_STATView The view
    V$FLASHBACK_DATABASE_STATshows the number of bytes of flashback data recorded by the database. Each row in the view shows accumulated statistics (usually over an hour). The FLASHBACK_DATA and REDO_DATA columns describe the number of bytes of flashback data and redo data written during the interval, respectively, while the DB_DATA column describes the number of bytes of data blocks read and written. The FLASHBACK_DATA and REDO_DATA columns correspond to sequential writes, while the DB_DATA columns correspond to random reads and writes.
  • V SYSSTAT view Because of the difference between sequential I/O and random I/O, a better indicator of I/O overhead is the number of I/O operations issued for the flashback log. The table below shows the V SYSSTAT view. Because of the difference between sequential I/O and random I/O, a better indicator of I/O overhead is the number of I/O operations issued for the flashback log. The table below shows the VS Y SST A T view Because of the difference between sequential I / O and random I / O , a better indicator of I / O overhead is the number of I / O operations issued for the flashback log . The V SYSSTAT statistics shown in the table below tell you the number of I/O operations issued by the instance for various purposes.
column name column meaning
Physical write I/O request The number of write operations issued by the write data block
Physical read I/O request Number of read operations issued for reading data blocks
Redo writes The number of write operations issued to write to the redo log
Flashback log writes The number of write operations issued to write to the flashback log
Flashback log write bytes The total size, in bytes, of Flashback Database data written from this instance

7.5.5 About Flashback Writer (RVWR) Behavior with I/O Errors

When flashback or guaranteed restore points are enabled, the background process RVWR writes flashback data to the Flashback Database log in the flash recovery area.

If RVWR encounters an I/O error, the following behavior is expected:

  • If any guaranteed restore points are defined, the instance will fail if RVWR encounters an I/O error.
  • If no guaranteed restore point is defined, the instance is not affected if RVWR encounters an I/O error. Please be aware of the following:
    • On the primary database, Oracle Database automatically disables Flashback Database when the database is opened. All existing transactions and inquiries are not affected. This behavior is expected for single instance and Oracle RAC databases.
    • On a physical or logical standby database, RVWR appears to have stopped responding, periodically retrying I/O. This could eventually cause managed recovery of either the logical standby database or the physical standby database to hang. (Oracle Database does not cause the standby instance to fail because it does not want to cause the primary database to fail in maximum protection mode.) To resolve this issue, you can issue a SHUTDOWN ABORT or ALTER DATABASE FLASHBACK OFF command.

Perform flashback and database point-in-time recovery

See Chapter 18, Performing Flashback and Database Point-in-Time Recovery, of the Backup and Recovery Guide

RMAN enables you to query for unwanted database changes and select and execute an appropriate recovery strategy based on Oracle Flashback Technology and database backups.

In Chapter 30 of the Backup and Recovery Guide: 30 Performing User-Managed Database Flashback and Recovery describes the user-managed Flashback Database, but I don't see any difference from what is described in this chapter:

A user-managed backup and recovery strategy means a method that does not depend on RMAN. Use the flashback features of Oracle Database in a user-managed backup and recovery strategy.

In section 2.8 of the Backup and Restore Guide, there is a quick guide available.

18.1 Overview of Oracle Flashback Technology and Database Point-in-Time Recovery

This overview describes the purpose and basic concepts of Oracle Flashback Technology and database point-in-time recovery.

18.1.1 Purpose of Flashback and Database Point-in-Time Recovery

Certain situations lend themselves to using the point-in-time recovery or flashback feature to return a database or database objects to their state at a previous point in time.

Some typical situations include:

  • User error or corruption can delete desired data or introduce corrupted data. For example, a user or DBA might mistakenly delete or update the contents of one or more tables, delete database objects that are still needed during an application update, or run a bulk update that fails mid-run.
  • The database upgrade failed or an error occurred in the upgrade script.
  • A full database recovery after a media failure cannot succeed because you don't have all the redo logs or incremental backups you need.

18.1.2 About Point-in-Time Recovery and Flashback Features

Database point-in-time recovery (DBPITR) and flashback features enable you to restore a database to a previous point in time.

DBPITR is the most basic solution for unwanted database changes. It is sometimes called incomplete recovery because it does not use all available redo or completely recovers all changes to the database. In this case, you restore the entire database backup, then apply the redo logs or incremental backups to recreate all changes up to a point in time before the unwanted change.

If the unwanted database changes are widespread but limited to specific tablespaces, you can use Tablespace Point-in-Time Recovery (TSPITR) to return those tablespaces to an earlier system change number while unaffected tablespaces remain available .

If the unwanted database changes are limited to specific tables or table partitions, you can use previously created RMAN backups to return only those objects to a point in time before the unwanted changes occurred.

Oracle Database also provides a set of features collectively known as Flashback Technologies, which enable viewing past states of data and rolling data back and forth in time without restoring the database from backup. Depending on the changes made to the database, flashback technology can often restore unwanted changes more quickly and with less impact on database availability.

For multi-tenant environments, there may be some dependencies between database point-in-time recovery (DBPITR) and flashback operations.

For pluggable databases (PDBs) that use local undo, DBPITR and flashback operate independently of each other.

Starting with Oracle Database 21c, you can perform a PDB flashback or point-in-time recovery operation on an orphaned PDB incarnation within the same database incarnation or an orphaned PDB incarnation within an ancestor database incarnation. In one CDB, you can flashback or PITR multiple PDBs simultaneously to different databases and PDB incarnations with the ancestor incarnation of the current database.

18.1.3 Basic Concepts of Database Point-in-Time Recovery

DBPITR works on a physical level , returning data files to a state in the past at a target time.

In an RMAN DBPITR operation, you specify the target SCN, log sequence, restore point, or time. RMAN restores the database from backups taken before the target time, and then applies the incremental backups and logs to recreate all changes to the datafiles between the time of the backup and the end of the restore. When the endpoint is specified as SCN, the database applies the redo logs and stops after each redo thread or the specified SCN, whichever occurs first. When the end point is specified as a time, the database internally determines an appropriate SCN for the specified time, and then restores to this SCN.

If your backup strategy is well designed and your database is running in ARCHIVELOG mode, then DBPITR is an option in almost all cases. Given a target SCN, data files can be restored from backup and efficiently restored without user intervention. However, RMAN DBPITR has the following disadvantages:

  • You cannot return selected objects to their previous state, only the entire database .
  • Your entire database is unavailable during DBPITR .
  • DBPITR can be time consuming because RMAN must restore all datafiles. Additionally, RMAN may need to restore redo logs and incremental backups to restore datafiles. This process may take longer if the backup is on tape.

You can perform point-in-time recovery (PITR) of one or more PDBs. Backups created before the PITR operation are still valid and available in the event of a media failure.

During a PDB PITR operation, all of the PDB's data files are restored in-place. If the CDB uses shared undo, the UNDO tablespace cannot be recovered in-place because it is shared by all PDBs in the CDB. Therefore, RMAN restores the UNDO, SYSTEM, and SYSAUX tablespaces to the secondary target, and then uses the undo information to restore the PDB to the target time.

After configuring the flash recovery area, RMAN uses it as a secondary target during PDB PITR. If the flash recovery area is not configured, use the AUXILIARY DESTINATION clause to specify the location to store the auxiliary database files. If the flash recovery area does not have enough space to restore the root and undo tablespaces, use the AUXILIARY DESTINATION clause to specify an alternate location.

In a Data Guard environment, in order for the standby database to follow the primary database where the PDB was restored to a specific point in time, you may need to flashback the entire standby database, restore the PDB, or flash back the PDB.

18.1.4 Basic Concepts of Flashback Technology

The flashback feature of Oracle Database is more efficient than media recovery in most available cases. You can use them to investigate the past state of the database.

18.1.4.1 About Physical Flashback Features Useful in Backup and Recovery

Oracle Flashback Database is the most efficient alternative to DBPITR .

Unlike other flashback features, it works on a physical level and restores the current data file to its contents at some point in the past. The results are similar to those of DBPITR, including OPEN RESETLOGS, but Flashback Database is generally faster because it does not require you to restore data files and only requires limited redo apply compared to media recovery.

Flashback Database requires a flash recovery area. To enable logging for Flashback Database, you must set the DB_FLASHBACK_RETENTION_TARGET initialization parameter and issue the ALTER DATABASE FLASHBACK ON statement.

During normal operation, the database periodically writes old images of datafile blocks to the flashback log. Flashback logs are written sequentially , usually in batches. In some respects, flashback logs are like a continuous backup. The database automatically creates, deletes, and resizes flashback logs in the recovery area. Flashback logs are not archived. All you need to know about flashback logs is to monitor performance and determine disk space allocation for the recovery area.

When you perform a Flashback Database operation, the database uses the flashback logs to access past versions of data blocks and also uses some data from the archived redo logs. Therefore, you cannot enable Flashback Database after a failure has been discovered, and then use Flashback Database to retroactively identify the failure. You can use the Guaranteed Restore Point feature to protect the contents of a database at a fixed point in time, such as before a risky database change.

If any unrecoverable operation is encountered during the required small amount of redo apply, it will result in logically corrupted data blocks. This causes Oracle errors when accessing such blocks.

You can perform Flashback Database operations on an entire multitenant container database (CDB) or a specific pluggable database (PDB).

NOTE: You cannot flashback only on root. You must flashback the entire CDB.

Flashback Database on an entire CDB enables you to rewind an entire CDB (including all of its PDBs) to a previous point in time. The target time can be specified by a system change number (SCN), log sequence number, restore point, or time.

Flashback Database on a PDB enables you to undo unwanted changes caused by logical data corruption or user error in that PDB. While Flashback Database is being executed on a particular PDB, other PDBs can remain open and running.

The desired target point in time is specified by a PDB restore point, CDB restore point, SCN, or time expression. A flashback operation on the PDB to a CDB restore point is equivalent to a flashback operation on the PDB to the restore point SCN on the CDB incarnation. In general, for PDBs, flashing back to a PDB restore point is more accurate than flashing back to a CDB restore point. This is because a PDB restore point represents the PDB child incarnation at the point in time it was created.

Multiple flashback operations can be performed on a single PDB. However, you can only flashback a PDB to one of its ancestor incarnations. A PDB must always remain compatible with past incarnations of the entire database incarnation.

PDB backups are still valid even after performing a Flashback Database operation on the PDB. You can use these backups to perform recovery in the event of a media failure. This type of PDB recovery can be recovered through the database reset log and the PDB reset log.

After performing the same operations on the primary database, you can also perform Flashback Database operations on the PDBs on the physical standby database.

18.1.4.2 About Logical Flashback Features Useful in Backup and Recovery

The logical flashback feature is used to restore a table and its contents to a past time.

The logical properties are as follows:

  • Flashback Table
    You can restore a table or a group of tables to a specified earlier point in time without taking any part of the database offline. In many cases, Flashback Table eliminates the need to perform more complex point-in-time recovery operations. Flashback Table automatically maintains associated attributes, such as current indexes, triggers, and constraints, while restoring the table, without requiring you to find and restore application-specific attributes.

  • Flashback DROP
    You can reverse the effect of the DROP TABLE statement.

All logical flashback features except Flashback Drop rely on undo data . Primarily used to provide read consistency for SQL queries and rolled back transactions, an undo record contains the information needed to reconstruct data as it existed at a past time and checks for records of changes since a past time.

Flashback Discard relies on a mechanism called the recycle bin , which the database uses to manage discarded database objects until the space they occupy is required by new data. There is no fixed amount of space allocated to the recycle bin, nor is there any guarantee how long discarded objects will remain in the recycle bin. Depending on system activity, discarded objects may remain in the recycle bin for seconds or months.

18.1.4.3 About Undo and Flashback Database Operations for PDBs

A multitenant container database (CDB) can use shared undo or local undo. The technique that RMAN uses to perform Flashback Database operations depends on the type of CDB unconfiguration.

When the CDB uses native undo, performing Flashback Database operations on a pluggable database (PDB) is very simple because only the data files associated with that PDB need to be modified .

In a CDB that uses shared undo, a set of tablespaces is shared by all PDBs. Undo data from multiple PDBs may be mixed in undo tablespaces, even within a single data block. Therefore, when RMAN performs a flashback database operation on the PDB, it will automatically use an auxiliary instance to restore the shared undo tablespace and some tablespaces in the root, and then restore the data to the required point in time. This process may involve restoring backups of relatively small amounts of data. When you perform a Flashback Database operation on a PDB to a clean PDB restore point, no auxiliary instance or restore backup is required.

By default, auxiliary instances are created in the fast recovery area. You can use the AUXILIARY DESTINATION clause on the FLASHBACK DATABASE command to specify an alternate location for an auxiliary instance.

18.1.5 About Managing Redo Corruption in CDBs

RMAN provides methods for managing redo corruption of data blocks in a PDB.

In rare cases, redo logs in a multi-tenant container database (CDB) may become corrupted. In this case, if the affected data blocks reside in only one pluggable database (PDB), you can do one of the following:

  • Perform a flashback operation on the PDB to a point in time before the corruption, then open the PDB with RESETLOGS
  • Restore the PDB execution time point to the time point before the corruption, and then use RESETLOGS to open the PDB

After performing one of these steps on the primary, any standbys of this primary can also skip corrupted redo, provided you perform the steps required to enable the standby to follow the primary after performing PITR or flashback on the PDB .

18.2 Rewinding a Table with Flashback Table

Flashback Table uses the information in the undo tablespace instead of the restored backup to retrieve the table. When a flashback table operation occurs, new rows are deleted and old rows are reinserted. While performing a flashback of a table, the rest of the database remains available.

To rewind a table to a previous point in time:

18.2.1 Prerequisites for Flashback Table

To perform a flashback table operation, the table must be eligible for flashback and the user performing the operation must have the required privileges.

You must have the following privileges to use the Flashback Table feature:

  • You must have been granted the FLASHBACK ANY TABLE system privilege, or you must have the FLASHBACK object privilege on the table.
  • You must have READ or SELECT, INSERT, DELETE, and ALTER permissions on the table.
  • To flash a table back to a restore point, you must have the SELECT ANY DICTIONARY or FLASHBACK ANY TABLE system privilege or the SELECT_CATALOG_ROLE role.

For an object to be eligible for flashback, the following prerequisites must be met:

  • The object must not contain the following categories: tables belonging to a cluster, materialized views, advanced queuing (AQ) tables, static data dictionary tables, system tables, remote tables, object tables, nested tables, or individual table partitions or subpartitions.
  • The structure of the table must not be changed between the current time and the target flashback time .
    The following data definition language (DDL) operations change the structure of a table: upgrade, move, or truncate a table; add constraints to a table, add a table to a cluster; modify or drop a column; add, drop, merge, split, merge, or truncate a partition; Subpartitions (except adding range partitions).
  • Row movement must be enabled on the table , indicating that the rowid has changed since the flashback occurred.
    This limitation exists because if the application stores rowids before the flashback, there is no guarantee that those rowids correspond to the same rows after the flashback. If your application relies on rowids, then you cannot use Flashback Table.
  • Undo data in an undo tablespace must extend far enough back in time to meet the flashback target time, or SCN.
    The point at which you can perform a flashback table is determined by the undo retention period (the minimum time that undo data is kept before being recycled) and the table space characteristics. Undo data contains information about a block of data before it was changed. Flashback operations use undo to recreate the original data.
    To ensure undo information is preserved for Flashback Table operations, Oracle recommends setting the UNDO_RETENTION parameter of the undo tablespace to 86400 seconds (24 hours) or longer.

NOTE: FLASHBACK TABLE ... TO BEFORE DROP uses the Flashback Drop functionality, not Flashback Table, and is therefore not subject to these prerequisites.

18.2.2 Performing a Flashback Table Operation

To use the Flashback Table feature on one or more tables, use the FLASHBACK TABLE SQL statement with a target time or SCN.

  1. Make sure you meet the prerequisites described in "Prerequisites for Flashback Table".
  2. (Optional) To keep database triggers enabled during Flashback Table operations, see Keeping Triggers Enabled During Flashback Table.
  3. As a normal user or a local user with SYSDBA or SYSBACKUP authority, connect SQL*Plus to the PDB containing the table. Identifies the current database (CDB) SCN.
  4. Identifies the time, SCN, or restore point to return the table to .
-- 查询还原点
SELECT NAME, SCN, TIME FROM V$RESTORE_POINT;
  1. Ensures that enough undo data exists to rewind the table to the specified target.
-- 如果设置了 UNDO_RETENTION 初始化参数,并且开启了撤销保留保证(在undo表空间上设置)
-- 则可以用以下查询确定撤消数据保留多长时间
SELECT NAME, VALUE/60 MINUTES_RETAINED
FROM   V$PARAMETER
WHERE  NAME = 'undo_retention';
  1. Make sure row movement is enabled for all objects rewound with flashback table
ALTER TABLE hr.temp_employees ENABLE ROW MOVEMENT;
  1. Determine whether the table to be flashed back depends on other tables. If there are dependencies, decide whether to also flash back these tables
SELECT other.owner, other.table_name
FROM   sys.all_constraints this, sys.all_constraints other
WHERE  this.owner = schema_name
AND    this.table_name = table_name
AND    this.r_owner = other.owner
AND    this.r_constraint_name = other.constraint_name
AND    this.constraint_type='R';
  1. Execute the FLASHBACK TABLE statement on the object to be flashed back.
    Note: The mapping of timestamps to SCNs is not always accurate. When you use timestamps with the FLASHBACK TABLE statement, the time at which the table is flashed back may differ by up to about 3 seconds from the time specified for TO_TIMESTAMP . If an exact point in time is required, use SCN instead of time.
  2. Optionally, query the table to examine the data.

By default, the database disables triggers on affected tables before performing a Flashback Table operation. After the operation, the database returns the trigger to its pre-operation state (enabled or disabled).

To keep triggers enabled during a table flashback, add the ENABLE TRIGGERS clause to the FLASHBACK TABLE statement.

18.3 Rewinding a DROP TABLE Operation with Flashback Drop

You can retrieve objects from the recycle bin using the FLASHBACK TABLE ... TO BEFORE DROP statement.

18.3.1 About Flashback Drop

Flashback Drop reverses the effect of the DROP TABLE operation. Flashback Drop is faster than other recovery mechanisms that can be used in this situation, such as point-in-time recovery, and does not cause downtime or lose recent transactions.

When a table is dropped, the database does not immediately drop the space associated with the table. Instead, the table is renamed and put into the recycle bin along with any associated objects. System-generated names for recycle bin objects are unique. You can query objects in the recycle bin just like you can query other objects.

Flashback operations retrieve tables from the recycle bin. When retrieving a dropped table, you can specify the table's original user-specified name or a system-generated name .

When you drop a table, the table goes to the recycle bin along with all its dependent objects . Likewise, when you perform a Flashback Drop, objects are usually retrieved together. When you restore a table from the recycle bin, dependent objects such as indexes do not get back their original names; they retain the system-generated recycle bin name. Oracle Database retrieves all indexes defined on the table (except bitmap join indexes), and all triggers and constraints defined on the table (except referential integrity constraints that refer to other tables).

Some dependent objects, such as indexes, may have been recycled due to space pressure. In this case, the reclaimed dependent objects cannot be retrieved from the recycle bin.

18.3.2 Prerequisites of Flashback Drop

Prerequisites must be met before performing a flashback delete operation.

The user permissions required for operations related to Flashback Drop and Recycle Bin are as follows:

  • DROP
    Any user with DROP permission on an object can delete the object, putting it in the recycle bin.
  • FLASHBACK TABLE ... TO BEFORE DROP
    The authority for this statement is linked to the authority for DROP. That is, any user who can delete objects can perform a flashback delete to retrieve deleted objects from the recycle bin.
  • The PURGE
    permission to clear the recycle bin is associated with the DROP permission. Any user with DROP TABLE, DROP ANY TABLE, or PURGE DBA_RECYCLE_BIN authority can purge objects from the recycle bin.
  • READ or SELECT and FLASHBACK objects in the recycle bin
    A user must have READ or SELECT and FLASHBACK permission on objects in the recycle bin to query objects in the recycle bin. Any users who had READ or SELECT permission on the object before it was deleted will continue to have READ or SELECT permission on the object in the recycle bin. A user must have FLASHBACK privilege to query any objects in the recycle bin, as these objects are from the past state of the database.

Objects must meet the following prerequisites to be eligible to be retrieved from the recycle bin:

  • The recycle bin applies only to non-system, locally managed tablespaces . If a table is in a non-system, locally managed tablespace, but one or more of its dependent segments (objects) are in a dictionary-managed tablespace, those objects will be protected by the recycle bin.
  • Tables on which fine-grained auditing (FGA) and virtual private database (VPD) policies are defined are not protected by the recycle bin.
  • Partitioned index-organized tables are not protected by the recycle bin.
  • The table must not be purged by the user or the Oracle database with the PURGE command during a space reclamation operation.

18.3.3 Performing a Flashback Drop Operation

Restore objects from the recycle bin using the FLASHBACK TABLE ... TO BEFORE DROP statement. You can specify the name of the table in the recycle bin or the original table name.

SHOW RECYCLEBIN;
SELECT object_name AS recycle_name, original_name, type FROM recyclebin;
SELECT * FROM  "BIN$gk3lsj/3akk5hg3j2lkl5j3d==$0";
-- 注意:如果您有必要的权限,那么您也可以对回收站中的表使用闪回查询
-- 但只能使用回收站名称而不是原始表名称。 您不能对回收站中的对象使用数据操作语言 (DML) 或 DDL 语句。
FLASHBACK TABLE "BIN$gk3lsj/3akk5hg3j2lkl5j3d==$0" TO BEFORE DROP;
FLASHBACK TABLE "BIN$gk3lsj/3akk5hg3j2lkl5j3d==$0" TO BEFORE DROP 
  RENAME TO hr.emp_demo;
SELECT INDEX_NAME FROM USER_INDEXES WHERE  TABLE_NAME = 'EMPLOYEE_DEMO';
ALTER INDEX "BIN$JKS983293M1dsab4gsz/I249==$0" RENAME TO I_EMP_DEMO;
-- 如果检索到的表在放入回收站之前具有引用约束,则重新创建它们。
-- 此步骤必须手动执行,因为回收站不会保留表上的引用约束。

You can create and delete multiple objects with the same original name. All discarded objects are stored in the recycle bin.
The principle is that although the object names are the same, the objects have different names in the recycle bin. And objects can be determined by creation time.

Or you can reply individually, since the most recently deleted table with this original name is retrieved first from the recycle bin with its original name.

18.4 Rewinding a Database with Flashback Database

Flashback Database reverses unwanted changes by returning the database to its state at a previous point in time.

18.4.1 Prerequisites of Flashback Database

Flashback Database works by undoing changes to data files that existed when the command was run. Prerequisites must be met to perform Flashback Database operations.

To use the FLASHBACK DATABASE command to return database contents to a point in time within the flashback window, your database must have been previously configured with flashback logging . To return the database to a guaranteed restore point, you must have defined the guaranteed restore point in advance .

Note the following important prerequisites:

  • No data files are currently missing or corrupt. You can only use FLASHBACK DATABASE to rewind changes made to the datafiles by Oracle Database, not to repair media failures.
  • You are not trying to recover from an accidentally deleted data file or undo a change to the database name.
  • You did not attempt to use FLASHBACK DATABASE to return to a point in time before the control file was restored or recreated. If the database control file is restored or recreated from backup, all accumulated flashback log information will be discarded.
  • You did not try to use FLASHBACK DATABASE to undo compatibility changes.

18.4.2 Performing a Flashback Database Operation

You can use the FLASHBACK DATABASE command to rewind an entire multitenant container database (CDB) to a point in time in the past.

This topic describes the basic techniques for performing a database flashback, specifying the desired target point in time using a time expression, the name of a normal or guaranteed restore point, or an SCN. It makes the following assumptions:

  • You are rewinding the database to a point in time in the current database incarnation.
  • The SCN used in the FLASHBACK DATABASE command refers to the SCN in the immediate ancestor path of the database incarnation. The avatar is located at this path if it has not been discarded since the database was previously opened with the RESETLOGS option.

To perform a Flashback Database operation on the entire CDB:

  1. Make sure you meet the prerequisites described in "Prerequisites for Flashback Database".
  2. Connect SQL*Plus to the target CDB and determine the required SCN, restore point or point in time for the FLASHBACK DATABASE command
-- 获取闪回数据库窗口中最早的SCN
SELECT OLDEST_FLASHBACK_SCN, OLDEST_FLASHBACK_TIME
FROM V$FLASHBACK_DATABASE_LOG;
-- 获取当前的SCN
SELECT CURRENT_SCN FROM V$DATABASE;
-- 查询可用的保证还原点
SELECT NAME, SCN, TIME, DATABASE_INCARNATION#,
       GUARANTEE_FLASHBACK_DATABASE
FROM   V$RESTORE_POINT
WHERE  GUARANTEE_FLASHBACK_DATABASE='YES';
 
NAME                   SCN TIME                  DATABASE_INCARNATION# GUA
--------------- ---------- --------------------- --------------------- ---
BEFORE_CHANGES     5753126 04-MAR-12 12.39.45 AM                     2 YES

-- 注意:如果闪回窗口没有足够远地回溯到过去以达到所需的目标时间,
-- 并且如果您在所需的时间没有保证的还原点,那么您可以通过使用数据库时间点恢复
  1. Consistently close the database, make sure it is not open by any instance, then mount it
SHUTDOWN IMMEDIATE;
STARTUP MOUNT;
  1. Repeat the query in step 2 of this procedure

Some flashback logging data is generated when the database is shut down. If the flashback logs are deleted due to space pressure on the flash recovery area, your target SCN may become inaccessible.
5. Connect to root as a normal user with SYSDBA or SYSBACKUP privileges
6. To view the preconfigured channels, run RMAN's SHOW command. Because during a flashback operation, RMAN may need to restore archived redo logs from backup.

SHOW ALL;
  1. Run the FLASHBACK DATABASE command to perform a flashback operation on the entire CDB to the specified point in time. You can specify a target time using an SCN, a time expression, or a CDB restore point.
  2. Open the CDB as read-only in SQL*Plus and run some queries to verify the database contents
ALTER DATABASE OPEN READ ONLY;

If you are satisfied with the state of the database, then end the process at step 9. If you are not satisfied with the state of the database, skip to step 10.

  1. If you are satisfied with the result, then do one of the following mutually exclusive operations
-- 操作A
-- 通过使用 RESETLOGS 选项打开数据库,使数据库可用于更新。
SHUTDOWN IMMEDIATE
STARTUP MOUNT
ALTER DATABASE OPEN RESETLOGS;
-- 注意:执行此 OPEN RESETLOGS 操作后,将放弃 FLASHBACK DATABASE 的目标 SCN 之后对数据库的所有更改。 
-- 您可以使用“将数据库倒带到一个被遗弃的化身分支中的一个 SCN”中的技术,将数据库返回到该 SCN 范围,同时它们仍保留在闪回窗口中。

-- 操作B
-- 使用 Oracle Data Pump Export 对状态已损坏的对象进行逻辑备份。
-- 然后,使用 RMAN 将数据库恢复到当前时间:
RECOVER DATABASE;
-- 此步骤通过将重做日志中的所有更改重新应用到数据库并将其返回到最近的 SCN 来取消闪回数据库的影响。
-- 重新打开数据库读/写后,您可以使用数据泵导入实用程序导入导出的对象。
  1. If you find that you are using the wrong restore point, time or SCN for flashback, then mount the database and do one of the following mutually exclusive options
-- 操作A
-- 如果您选择的目标时间在过去还不够远,则使用另一个 FLASHBACK DATABASE 命令将数据库倒回更远的时间
FLASHBACK DATABASE TO SCN 42963;  #earlier than current SCN 

-- 操作B
-- 如果您选择的目标 SCN 距离过去太远,则使用 RECOVER DATABASE UNTIL 将数据库及时前移到所需的 SCN:
RECOVER DATABASE UNTIL SCN 56963; #later than current SCN 

-- 操作C
-- 如果要完全取消 FLASHBACK DATABASE 命令的影响,则可以使用不带 UNTIL 子句或 SET UNTIL 命令的 RECOVER DATABASE 命令执行数据库的完全恢复:
RECOVER DATABASE;
-- RECOVER DATABASE 命令将所有更改重新应用到数据库,将其返回到最近的 SCN。
  1. Open the PDB, since the PDB is not automatically opened when the CDB is opened
ALTER PLUGGABLE DATABASE ALL OPEN;
ALTER PLUGGABLE DATABASE my_pdb OPEN;

18.4.3 Performing a Flashback Database Operation for PDBs

You can use the FLASHBACK DATABASE command to perform Flashback Database operations on a single pluggable database (PDB). Only the data files associated with this PDB are modified. The remaining PDBs in the CDB are unaffected and can be used.

This topic describes the basic techniques for performing a PDB flashback, specifying the desired target point in time using a time expression, the name of a normal or guaranteed restore point, or an SCN. It makes the following assumptions:

  • You are rewinding the PDB to a point in time in the current database incarnation.
  • The SCN used in the FLASHBACK DATABASE command refers to the SCN in the immediate ancestor path of the PDB incarnation.

To perform a Flashback Database operation for a PDB:

  1. Connect to root as an ordinary user with SYSDBA or SYSBACKUP authority, as described in Establishing a Database Connection Using RMAN.
  2. Make sure CDB is turned on
  3. Determining the required SCN, restore point, or point in time for Flashback Database commands
  4. Make sure that the PDBs on which Flashback Database operations must be performed are closed. Other PDBs can be opened and run
  5. Performs Flashback Database operations on the specified PDB to the desired point in time
FLASHBACK PLUGGABLE DATABASE my_pdb TO SCN 24368 AUXILIARY DESTINATION '+data';
FLASHBACK PLUGGABLE DATABASE my_pdb TO RESTORE POINT before_appl_changes AUXILIARY DESTINATION '/temp/aux_dest';
FLASHBACK PLUGGABLE DATABASE my_pdb TO TIME "TO_DATE('03/20/15','MM/DD/YY')";
  1. For PDBs that use shared undo, you can optionally include the AUXILIARY DESTINATION clause to specify the location of an auxiliary instance that stores data files restored as part of a Flashback Database operation. If this clause is omitted, the auxiliary instance is created in the flash recovery area.
  2. Open the PDB with RESETLOGS
ALTER PLUGGABLE DATABASE my_pdb OPEN RESETLOGS;

18.4.4 Performing a Flashback Operation on a PDB to an Ancestor or Orphan Incarnation

slightly.

18.4.5 Monitoring Flashback Database

The data dictionary views contain information for monitoring Flashback Database.

When you use Flashback Database to rewind a database to a past target time, Flashback Database determines which blocks changed after the target time and restores them from the flashback logs. This is called the restore phase . After this phase is complete, Flashback Database then uses the redo logs to reapply the changes that were made after the blocks were written to the flashback logs. This is called the recovery phase .

The progress of Flashback Database during the recovery phase can be monitored by querying the V$SESSION_LONGOPS view. opname is Flashback Database. Under the TOTALWORK column is the number of megabytes of flashback logs that must be read. The SOFAR column in the following example lists the current number of megabytes read.

-- Tracking Flashback Database Progress - Restore Phase

SQL> SELECT sofar, totalwork, units FROM v$session_longops WHERE opname = 'Flashback Database';
 
SOFAR  TOTALWORK  UNITS
-----  ---------- --------------------------------
   17          60 Megabytes

The progress of Flashback Database during the recovery phase can be monitored by querying the view V$RECOVERY_PROGRESS.

18.5 Performing Database Point-in-Time Recovery

slightly.

18.6 Performing Point-in-Time Recovery of Application PDBs

slightly.

18.7 Performing Point-in-Time Recovery of Sparse Databases

slightly.

18.8 Flashback and Database Point-in-Time Recovery Scenarios

slightly.

Guess you like

Origin blog.csdn.net/stevensxiao/article/details/128784141