首頁 > 軟體

ORACLE分割區錶轉換線上重定義DBMS_REDEFINITION

2022-07-07 14:04:54

一、DBMS_REDEFINITION(線上重定義)

參考MOS檔案:_How To Partition Existing Table Using DBMS_REDEFINITION (Doc ID 472449.1)  _

支援的資料庫版本:Oracle Database - Enterprise Edition - Version 9.2.0.4 and later

線上重定義是通過 物化檢視 實現的。

使用線上重定義的一些限制條件:

  • 1、必須有足夠的表空間來容納表的兩倍資料量。
  • 2、主鍵列不能被修改。
  • 3、表必須有主鍵。
  • 4、必須在同一個使用者下進行線上重定義。
  • 5、SYS和SYSTEM使用者下的表無法進行線上重定義。
  • 6、線上重定義無法採用nologging。
  • 7、如果中間表有新增列,則不能有NOT NULL約束

DBMS_REDEFINITION包:

  • ABSORT_REDEF_TABLE:清理重定義的錯誤和中止重定義;
  • CAN_REDEF_TABLE:檢查表是否可以進行重定義,儲存過程執行成功代表可以進行重定義;
  • COPY_TABLE_DEPENDENTS:同步索引和依賴的物件(包括索引、約束、觸發器、許可權等);
  • FINISH_REDEF_TABLE:完成線上重定義;
  • REGISTER_DEPENDENTS_OBJECTS:註冊依賴的物件,如索引、約束、觸發器等;
  • START_REDEF_TABLE:開始線上重定義;
  • SYNC_INTERIM_TABLE:增量同步資料;
  • UNREGISTER_DEPENDENT_OBJECT:不註冊依賴的物件,如索引、約束、觸發器等;
CREATE OR REPLACE PACKAGE SYS.dbms_redefinition AUTHID CURRENT_USER IS
  ------------
  --  OVERVIEW
  --
  -- This package provides the API to perform an online, out-of-place
  -- redefinition of a table
  --- =========
  --- CONSTANTS
  --- =========
  -- Constants for the options_flag parameter of start_redef_table
  cons_use_pk    CONSTANT PLS_INTEGER := 1;
  cons_use_rowid CONSTANT PLS_INTEGER := 2;
  -- Constants used for the object types in the register_dependent_object
  cons_index      CONSTANT PLS_INTEGER := 2;
  cons_constraint CONSTANT PLS_INTEGER := 3;
  cons_trigger    CONSTANT PLS_INTEGER := 4;
  cons_mvlog      CONSTANT PLS_INTEGER := 10;
  -- constants used to specify the method of copying indexes
  cons_orig_params CONSTANT PLS_INTEGER := 1;
  PRAGMA SUPPLEMENTAL_LOG_DATA(default, AUTO_WITH_COMMIT);
  -- NAME:     can_redef_table - check if given table can be re-defined
  -- INPUTS:   uname        - table owner name
  --           tname        - table name
  --           options_flag - flag indicating user options to use
  --           part_name    - partition name
  PROCEDURE can_redef_table(uname        IN VARCHAR2,
                            tname        IN VARCHAR2,
                            options_flag IN PLS_INTEGER := 1,
                            part_name    IN VARCHAR2 := NULL);
  PRAGMA SUPPLEMENTAL_LOG_DATA(can_redef_table, NONE);
  -- NAME:     start_redef_table - start the online re-organization
  -- INPUTS:   uname        - schema name
  --           orig_table   - name of table to be re-organized
  --           int_table    - name of interim table
  --           col_mapping  - select list col mapping
  --           options_flag - flag indicating user options to use
  --           orderby_cols - comma separated list of order by columns
  --                          followed by the optional ascending/descending
  --                          keyword
  --           part_name    - name of the partition to be redefined
  PROCEDURE start_redef_table(uname        IN VARCHAR2,
                              orig_table   IN VARCHAR2,
                              int_table    IN VARCHAR2,
                              col_mapping  IN VARCHAR2 := NULL,
                              options_flag IN BINARY_INTEGER := 1,
                              orderby_cols IN VARCHAR2 := NULL,
                              part_name    IN VARCHAR2 := NULL);
  -- NAME:     finish_redef_table - complete the online re-organization
  -- INPUTS:   uname        - schema name
  --           orig_table   - name of table to be re-organized
  --           int_table    - name of interim table
  --           part_name    - name of the partition being redefined
  PROCEDURE finish_redef_table(uname          IN VARCHAR2,
                               orig_table     IN VARCHAR2,
                               int_table      IN VARCHAR2,
                               part_name      IN VARCHAR2 := NULL);
  -- NAME:     abort_redef_table - clean up after errors or abort the
  --                               online re-organization
  -- INPUTS:   uname        - schema name
  --           orig_table   - name of table to be re-organized
  --           int_table    - name of interim table
  --           part_name    - name of the partition being redefined
  PROCEDURE abort_redef_table(uname        IN VARCHAR2,
                              orig_table   IN VARCHAR2,
                              int_table    IN VARCHAR2,
                              part_name    IN VARCHAR2 := NULL);
  -- NAME:     sync_interim_table - synchronize interim table with the original
  --                                table
  -- INPUTS:   uname        - schema name
  --           orig_table   - name of table to be re-organized
  --           int_table    - name of interim table
  --           part_name    - name of the partition being redefined
  PROCEDURE sync_interim_table(uname       IN VARCHAR2,
                               orig_table  IN VARCHAR2,
                               int_table   IN VARCHAR2,
                               part_name   IN VARCHAR2 := NULL);
  -- NAME:     register_dependent_object - register dependent object
  --
  -- INPUTS:   uname        - schema name
  --           orig_table   - name of table to be re-organized
  --           int_table    - name of interim table
  --           dep_type     - type of the dependent object
  --           dep_owner    - name of the dependent object owner
  --           dep_orig_name- name of the dependent object defined on table
  --                          being re-organized
  --           dep_int_name - name of the corressponding dependent object on
  --                          the interim table
  PROCEDURE register_dependent_object(uname         IN VARCHAR2,
                                      orig_table    IN VARCHAR2,
                                      int_table     IN VARCHAR2,
                                      dep_type      IN PLS_INTEGER,
                                      dep_owner     IN VARCHAR2,
                                      dep_orig_name IN VARCHAR2,
                                      dep_int_name  IN VARCHAR2);
  -- NAME:     unregister_dependent_object - unregister dependent object
  --
  -- INPUTS:   uname        - schema name
  --           orig_table   - name of table to be re-organized
  --           int_table    - name of interim table
  --           dep_type     - type of the dependent object
  --           dep_owner    - name of the dependent object owner
  --           dep_orig_name- name of the dependent object defined on table
  --                          being re-organized
  --           dep_int_name - name of the corressponding dependent object on
  --                          the interim table
  PROCEDURE unregister_dependent_object(uname         IN VARCHAR2,
                                        orig_table    IN VARCHAR2,
                                        int_table     IN VARCHAR2,
                                        dep_type      IN PLS_INTEGER,
                                        dep_owner     IN VARCHAR2,
                                        dep_orig_name IN VARCHAR2,
                                        dep_int_name  IN VARCHAR2);
  --  NAME:     copy_table_dependents
  --
  --  INPUTS:  uname             - schema name
  --           orig_table        - name of table to be re-organized
  --           int_table         - name of interim table
  --           copy_indexes      - integer value indicating whether to
  --                               copy indexes
  --                               0 - don't copy
  --                               1 - copy using storage params/tablespace
  --                                   of original index
  --           copy_triggers      - TRUE implies copy triggers, FALSE otherwise
  --           copy_constraints   - TRUE implies copy constraints, FALSE
  --                                otherwise
  --           copy_privileges    - TRUE implies copy privileges, FALSE
  --                                otherwise
  --           ignore errors      - TRUE implies continue after errors, FALSE
  --                                otherwise
  --           num_errors         - number of errors that occurred while
  --                                cloning ddl
  --           copy_statistics    - TRUE implies copy table statistics, FALSE
  --                                otherwise.
  --                                If copy_indexes is 1, copy index
  --                                related statistics, 0 otherwise.
  --           copy_mvlog         - TRUE implies copy table's MV log, FALSE
  --                                otherwise.
  PROCEDURE copy_table_dependents(uname              IN  VARCHAR2,
                                  orig_table         IN  VARCHAR2,
                                  int_table          IN  VARCHAR2,
                                  copy_indexes       IN  PLS_INTEGER := 1,
                                  copy_triggers      IN  BOOLEAN := TRUE,
                                  copy_constraints   IN  BOOLEAN := TRUE,
                                  copy_privileges    IN  BOOLEAN := TRUE,
                                  ignore_errors      IN  BOOLEAN := FALSE,
                                  num_errors         OUT PLS_INTEGER,
                                  copy_statistics    IN  BOOLEAN := FALSE,
                                  copy_mvlog         IN  BOOLEAN := FALSE);
END;

二、線上重定義表的步驟

1.建立未分割區的表

建立未分割區的表,如果存在,就不需要操作。

--前置準備:建立使用者,表空間,授權使用者。
SQL> create tablespace PARTITION;
SQL> create user par identified by par;
SQL> grant dba to par;
--建立表,索引,授權,同義詞
SQL> conn par/par
Connected.
-- Create table
create table student(
s_id number(8) PRIMARY KEY,
s_name varchar2(20) not null,
s_sex varchar2(8),
s_birdate date,
constraint u_1 unique(s_name),
constraint c_1 check (s_sex in ('MALE','FEMALE')))
tablespace PARTITION;
-- Add comments to the table 
comment on table STUDENT is '學生表';
-- Add comments to the columns 
comment on column STUDENT.s_name is '姓名';
comment on column STUDENT.s_sex is '性別';
comment on column STUDENT.s_birdate is '出生日期';
-- Create/Recreate indexes 
create index S_NAME_IDX on STUDENT (S_NAME, S_SEX) tablespace PARTITION;
-- Create SYNONYM
CREATE SYNONYM stu FOR student;
-- Grant/Revoke object privileges 
grant select, insert, delete on STUDENT to SCOTT;
--檢視表結構
SQL> desc stu
 Name					   Null?    Type
 ----------------------------------------- -------- ----------------------------
 S_ID					   NOT NULL NUMBER(8)
 S_NAME 				   NOT NULL VARCHAR2(20)
 S_SEX						    VARCHAR2(8)
 S_BIRDATE					    DATE
--插入資料
begin
  for i in 0 .. 24 loop
    insert into student values
      (i,
       'student_' || i,
       decode(mod(i, 2), 0, 'MALE', 'FEMALE'),
       add_months(to_date('2019-1-1', 'yyyy-mm-dd'), i));
  end loop;
  commit;
end;
/

2.確認表是否存在主鍵,表空間是否足夠,收集表統計資訊。

--檢視表主鍵
SQL> select cu.* from user_cons_columns cu, user_constraints au where cu.constraint_name = au.constraint_name and au.constraint_type = 'P' and au.table_name = 'STUDENT';
--檢視表大小和表空間
--檢視表空間
SQL> select tablespace_name from dba_segments where segment_type= 'TABLE' and segment_name='STUDENT' and owner='PAR';
--檢視表大小
SQL> select sum(bytes/1024/1024) from dba_segments where segment_type= 'TABLE' and segment_name='STUDENT' and owner='PAR';
--檢視表空間
select tbs_used_info.tablespace_name,
       tbs_used_info.alloc_mb,
       tbs_used_info.used_mb,
       tbs_used_info.max_mb,
       tbs_used_info.free_of_max_mb,
       tbs_used_info.used_of_max || '%' used_of_max_pct
  from (select a.tablespace_name,
               round(a.bytes_alloc / 1024 / 1024) alloc_mb,
               round((a.bytes_alloc - nvl(b.bytes_free,
                                          0)) / 1024 / 1024) used_mb,
               round((a.bytes_alloc - nvl(b.bytes_free,
                                          0)) * 100 / a.maxbytes) used_of_max,
               round((a.maxbytes - a.bytes_alloc + nvl(b.bytes_free,
                                                       0)) / 1048576) free_of_max_mb,
               round(a.maxbytes / 1048576) max_mb
          from (select f.tablespace_name,
                       sum(f.bytes) bytes_alloc,
                       sum(decode(f.autoextensible,
                                  'YES',
                                  f.maxbytes,
                                  'NO',
                                  f.bytes)) maxbytes
                  from dba_data_files f
                 group by tablespace_name) a,
               (select f.tablespace_name,
                       sum(f.bytes) bytes_free
                  from dba_free_space f
                 group by tablespace_name) b
         where a.tablespace_name = b.tablespace_name(+)) tbs_used_info
 order by tbs_used_info.used_of_max desc;
--如果表空間不夠,提前增加表空間大小
alter tablespace PARTITION add datafile;
--收集統計資訊(可忽略)
EXEC DBMS_STATS.gather_table_stats('PAR', 'STUDENT', cascade => TRUE);

3.呼叫DBMS_REDEFINITION.CAN_REDEF_TABLE()

呼叫DBMS_REDEFINITION.CAN_REDEF_TABLE()過程,確認表是否滿足重定義的條件。

SQL> EXEC Dbms_Redefinition.can_redef_table('PAR', 'STUDENT');
PL/SQL procedure successfully completed.

4.建立一個空的中間表

在用一個使用者中建立一個空的中間表,根據重定義後你期望得到的結構建立中間表。比如:採用分割區表(間隔分割區),增加了COLUMN等。

在中間表上建立觸發器、索引和約束,並進行相應的授權。任何包含中間表的完整性約束應將狀態置為disabled。(此步驟也可以放在同步資料後操作)

--建立間隔分割區(增加列s_phone)
create table STUDENT_PAR
(
  s_id      NUMBER(8) not null,
  s_name    VARCHAR2(20) not null,
  s_sex     VARCHAR2(8),
  s_birdate DATE,
  s_phone   number
)
tablespace PARTITION
PARTITION BY RANGE(s_birdate)
INTERVAL (NUMTOYMINTERVAL(1,'MONTH')) STORE IN (partition)
(PARTITION STUDENT_201901 VALUES LESS THAN (TO_DATE('2019-02-01 00:00:00', 'SYYYY-MM-DD Hh34:MI:SS', 'NLS_CALENDAR=GREGORIAN')));
--臨時中間表上建立如下:
--建立主鍵約束
alter table STUDENT_PAR add primary key (S_ID) using index tablespace PARTITION;
--建立唯一索引約束
alter table STUDENT_PAR add constraint U_1_PAR unique (S_NAME) using index tablespace PARTITION;
--建立check約束
alter table STUDENT_PAR add constraint C_1_PAR check (s_sex in ('MALE','FEMALE'));
--建立索引
CREATE INDEX S_NAME_IDX_PAR ON STUDENT_PAR (S_NAME,S_SEX) tablespace PARTITION;
--建立同義詞
CREATE SYNONYM stu_par FOR STUDENT_PAR;
--新增描述
COMMENT ON TABLE  STUDENT_PAR IS '學生表';
COMMENT ON COLUMN STUDENT_PAR.s_name IS '姓名';
COMMENT ON COLUMN STUDENT_PAR.s_sex IS '性別';
COMMENT ON COLUMN STUDENT_PAR.s_birdate IS '出生日期';
--授權
GRANT SELECT,INSERT,DELETE ON STUDENT_PAR TO scott; 

5.呼叫DBMS_REDEFINITION.START_REDEF_TABLE

呼叫DBMS_REDEFINITION.START_REDEF_TABLE()過程,並提供下列引數:被重定義的表的名稱、中間表的名稱、列的對映規則、重定義方法。

如果對映方法沒有提供,則認為所有包括在中間表中的列用於表的重定義。如果給出了對映方法,則只考慮對映方法中給出的列。如果沒有給出重定義方法,則預設使用主鍵方式。

SQL> BEGIN
DBMS_REDEFINITION.start_redef_table(
uname => 'PAR', 
orig_table => 'STUDENT',
int_table => 'STUDENT_PAR');
END;
/
PL/SQL procedure successfully completed.

6.(可選)在建立索引之前將新表與臨時名稱同步

Notes:如果在執行DBMS_REDEFINITION.START_REDEF_TABLE()過程和執行DBMS_REDEFINITION.FINISH_REDEF_TABLE()過程直接在重定義表上執行了大量的DML操作,那麼可以選擇執行一次或多次的SYNC_INTERIM_TABLE()過程,此操作可以減少最後一步執行FINISH_REDEF_TABLE()過程時的鎖定時間。

--模擬業務不停,DML表資料寫入
insert into STUDENT values(25,'student_25','MALE',to_date('2020-8-1', 'yyyy-mm-dd'));
update student set s_sex='FEMALE' where s_id = 20;
commit;
--比對student和student_par資料
select s_id,s_name,s_sex,s_birdate from student
minus
select s_id,s_name,s_sex,s_birdate from student_par;
      S_ID S_NAME		S_SEX	 S_BIRDATE
---------- -------------------- -------- ------------------
	20 student_20		FEMALE	 01-SEP-20
	25 student_25		MALE	 01-AUG-20
--同步資料到臨時表
BEGIN
dbms_redefinition.sync_interim_table(
uname => 'PAR', 
orig_table => 'STUDENT',
int_table => 'STUDENT_PAR');
END;
/
--資料已全部同步到臨時表
select s_id,s_name,s_sex,s_birdate from student
minus
select s_id,s_name,s_sex,s_birdate from student_par;
no rows selected

7.執行DBMS_REDEFINITION.FINISH_REDEF_TABLE

執行DBMS_REDEFINITION.FINISH_REDEF_TABLE()過程完成表的重定義。這個過程中,原始表會被獨佔模式鎖定一小段時間,具體時間和表的資料量有關。

執行完FINISH_REDEF_TABLE()過程後,原始表重定義後具有了中間表的屬性、索引、約束、授權和觸發器。中間表上disabled的約束在原始表上處於enabled狀態。

--收集par table的統計資訊
EXEC DBMS_STATS.gather_table_stats('PAR', 'STUDENT_PAR', cascade => TRUE);
--結束線上重定義過程
BEGIN
dbms_redefinition.finish_redef_table(
uname => 'PAR', 
orig_table => 'STUDENT',
int_table => 'STUDENT_PAR');
END;
/
SQL> select table_name,PARTITION_NAME from user_tab_partitions where table_name in ('STUDENT','STUDENT_PAR');
SQL> select table_name,index_name from user_indexes where table_name in ('STUDENT','STUDENT_PAR');

此時,臨時表(及其索引)已成為“真實”表,並且它們的名稱已在名稱詞典中切換。

8.重新命名所有約束和索引以匹配原始名稱

--drop中間表或者rename原來的約束
a.drop table STUDENT_PAR;
b.
ALTER TABLE STUDENT_PAR RENAME CONSTRAINT U_1 TO U_1_20210411;
ALTER TABLE STUDENT_PAR RENAME CONSTRAINT C_1 TO C_1_20210411;
ALTER INDEX S_NAME_IDX RENAME TO S_NAME_IDX_20210411;
ALTER INDEX U_1 RENAME TO U_1_20210411;
--rename 新分割區表的約束和索引
ALTER TABLE STUDENT RENAME CONSTRAINT U_1_PAR TO U_1;
ALTER TABLE STUDENT RENAME CONSTRAINT C_1_PAR TO C_1;
ALTER INDEX S_NAME_IDX_PAR RENAME TO S_NAME_IDX;
ALTER INDEX U_1_PAR RENAME TO U_1;
--檢視索引,約束名稱是否正確
select table_name,index_name from user_indexes where table_name in ('STUDENT','STUDENT_PAR') order by table_name;
TABLE_NAME		       INDEX_NAME
------------------------------ ------------------------------
STUDENT 		       S_NAME_IDX
STUDENT 		       SYS_C0011401
STUDENT 		       U_1
STUDENT_PAR		       S_NAME_IDX_20210411
STUDENT_PAR		       U_1_20210411
STUDENT_PAR		       SYS_C0011395
SQL> desc stu
 Name					   Null?    Type
 ----------------------------------------- -------- ----------------------------
 S_ID					   NOT NULL NUMBER(8)
 S_NAME 				   NOT NULL VARCHAR2(20)
 S_SEX						    VARCHAR2(8)
 S_BIRDATE					    DATE
 S_PHONE					    NUMBER

以上就是ORACLE分割區錶轉換線上重定義DBMS_REDEFINITION的詳細內容,更多關於ORACLE分割區錶轉換線上重定義的資料請關注it145.com其它相關文章!


IT145.com E-mail:sddin#qq.com