segunda-feira, 30 de agosto de 2010

Simulando um Workload de Produção

Objetivo:
As mudanças nas configurações do ambiente de produção são consideradas críticas e a única forma de mitigar os riscos é a relização de testes o mais próximo possível da realidade da produção e que represente um dia de pico de atividades. Muitas ferramentas foram desenvolvidas com essa finalidade ao longo dos anos, mas nenhuma delas consegue simular um workload real de um base de produção, agora foi disponibilizada uma new feature na versão 11g (RAT - Real Application Testing) que possibilita a reprodução de um Workload de produção durante um periodo desejado em ambiente de teste.
A utilização da new feature RAT é muito simples utilizando o Enterprise Manager, mas vamos fazer uma simulação utilizando as API’s do Oracle para entender melhor o conceito desse novo recurso.


Ambiente:
SO: Linux 2.6.9-67.0.0.0.1.EL i686 i386 GNU/Linux
Base: Oracle Database 11.2.0.1.0


Tópicos:
1. Preparando o ambiente para a simulação;
2. Capturando o Workload de Produção;
3. Pré-processamento do Workload de Produção;
4. Executado o Workload capturado numa base de teste;
5. Analisando a execução de teste e gerando relatório;

1. Preparando o ambiente para simulação


1.1 Baixe o arquivo zip com os scripts e descompacte os arquivos em um diretório de trabalho no servidor linux de teste:
http://st-curriculum.oracle.com/obe/db/11g/r2/prod/manage/dbreplay/files/dbreplay.zip


1.2 Abra um terminal Linux, acesse o diretório onde você gravou os scripts e execute o script “first_time.sh”:



[oracle@odbsrv02 scripts]$ pwd
/u02/dbreplay/scripts
[oracle@odbsrv02 scripts]$ chmod 755 *.sh
[oracle@odbsrv02 scripts]$ ./first_time.sh
rm: cannot remove `wcr_demo': No such file or directory
make: *** [clean] Error 1
gcc -c -I. -I/u01/app/oracle/product/11.2.0/lab1/rdbms/public test_common.c
gcc -c -I. -I/u01/app/oracle/product/11.2.0/lab1/rdbms/public wcr_demo.c
gcc -g -o wcr_demo test_common.o wcr_demo.o -L/u01/app/oracle/product/11.2.0/lab1/lib -lclntsh
[oracle@odbsrv02 scripts]$

Obs: O erro apontado pode ser ignorado.


1.3 Altere a senha do usuário sys no script wcr_demo_init.sh de acordo com o seu ambiente e execute este script;



[oracle@odbsrv02 scripts]$ ./wcr_demo_init.sh

SQL*Plus: Release 11.2.0.1.0 Production on Thu Aug 5 10:35:21 2010

Copyright (c) 1982, 2009, Oracle. All rights reserved.


Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

SQL>
User altered.

SQL>
User altered.

SQL>
SQL> Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

SQL*Plus: Release 11.2.0.1.0 Production on Thu Aug 5 10:35:22 2010

Copyright (c) 1982, 2009, Oracle. All rights reserved.


Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

SQL>
SQL> Connected.
SQL>
SQL> drop table wcr_grid
*
ERROR at line 1:
ORA-00942: table or view does not exist


SQL> drop table wcr_grid
*
ERROR at line 1:
ORA-00942: table or view does not exist


SQL>
Table created.

SQL>
SQL> SET ECHO ON
SQL> SET FEEDBACK 1
SQL> SET NUMWIDTH 10
SQL> SET LINESIZE 80
SQL> SET TRIMSPOOL ON
SQL> SET TAB OFF
SQL> SET PAGESIZE 100
SQL>
SQL> connect scott/tiger
Connected.
SQL>
SQL> delete from wcr_grid;

0 rows deleted.

SQL>
SQL> declare
2 id number;
3 x number;
4 y number;
5 c varchar2(100);
6 begin
7 x := 0;
8 y := 0;
9 id := 0;
10 c := 'black';
11
12 for i in 1..10 loop
13
14 for i in 1..10 loop
15
16 insert into wcr_grid values (id, x, y, c);
17 y := y + 1;
18 id := id + 1;
19
20 end loop;
21
22 x := x + 1;
23 y := 0;
24
25 end loop;
26 end;
27 /

PL/SQL procedure successfully completed.

SQL>
SQL> commit;

Commit complete.

SQL> Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
[oracle@odbsrv02 scripts]$

.


1.4 Adicione o diretório de scripts à variável de ambiente PATH e adicione o diretório $ORACLE_HOME/lib à variável de ambiente LD_LIBRARY_PATH:


[oracle@odbsrv02 scripts]$ export PATH=.:$PATH
[oracle@odbsrv02 scripts]$ export LD_LIBRARY_PATH=$ORACLE_HOME/lib


2. Capturando o Workload de Produção


2.1 Desative o Banco de Dados – Este procedimento não é obrigatório, mas é recomendado para evitar a captura de transações incompletas, ou seja, as transações que iniciaram antes do inicio do processo de captura;



[oracle@odbsrv02 bin]$ ./emctl stop dbconsole
Oracle Enterprise Manager 11g Database Control Release 11.2.0.1.0
Copyright (c) 1996, 2009 Oracle Corporation. All rights reserved.
https://odbsrv02.localdomain:5501/em/console/aboutApplication
Stopping Oracle Enterprise Manager 11g Database Control ...
... Stopped.
[oracle@odbsrv02 bin]$ lsnrctl stop

LSNRCTL for Linux: Version 11.2.0.1.0 - Production on 05-AUG-2010 11:06:51

Copyright (c) 1991, 2009, Oracle. All rights reserved.

Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1)))
The command completed successfully
[oracle@odbsrv02 bin]$ sqlplus / as sysdba

SQL*Plus: Release 11.2.0.1.0 Production on Thu Aug 5 11:07:02 2010

Copyright (c) 1982, 2009, Oracle. All rights reserved.


Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

SQL> shutdown immediate;
Database closed.
Database dismounted.
ORACLE instance shut down.
SQL> exit
Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
[oracle@odbsrv02 bin]$

.


2.2 Antes de iniciar o Banco de Dados faça um Cold Backup que será restaurado na base de teste, dessa forma podemos garantir que os dados da aplicação do inicio da captura do workload serão os mesmos no inicio do “Replay”;


2.3 Crie um diretório para armazenar os arquivos de captura do workload:



[oracle@odbsrv02 dbreplay]$ mkdir /u02/dbreplay/workload
[oracle@odbsrv02 dbreplay]$ cd /u02/dbreplay/workload
[oracle@odbsrv02 workload]$ pwd
/u02/dbreplay/workload
[oracle@odbsrv02 workload]$

.


2.4 Inicie o Banco de Dados em modo restrito para evitar que usuários acessem a base e iniciem transações antes de iniciarmos a captura do workload:



[oracle@odbsrv02 workload]$ lsnrctl start

LSNRCTL for Linux: Version 11.2.0.1.0 - Production on 05-AUG-2010 11:46:59

Copyright (c) 1991, 2009, Oracle. All rights reserved.

Starting /u01/app/oracle/product/11.2.0/lab1/bin/tnslsnr: please wait...

TNSLSNR for Linux: Version 11.2.0.1.0 - Production
System parameter file is /u01/app/oracle/product/11.2.0/lab1/network/admin/listener.ora
Log messages written to /u01/app/oracle/diag/tnslsnr/odbsrv02/listener/alert/log.xml
Listening on: (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(KEY=EXTPROC1)))
Listening on: (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=odbsrv02.localdomain)(PORT=1521)))

Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1)))
STATUS of the LISTENER
------------------------
Alias LISTENER
Version TNSLSNR for Linux: Version 11.2.0.1.0 - Production
Start Date 05-AUG-2010 11:47:00
Uptime 0 days 0 hr. 0 min. 0 sec
Trace Level off
Security ON: Local OS Authentication
SNMP OFF
Listener Parameter File /u01/app/oracle/product/11.2.0/lab1/network/admin/listener.ora
Listener Log File /u01/app/oracle/diag/tnslsnr/odbsrv02/listener/alert/log.xml
Listening Endpoints Summary...
(DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(KEY=EXTPROC1)))
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=odbsrv02.localdomain)(PORT=1521)))
Services Summary...
Service "PLSExtProc" has 1 instance(s).
Instance "PLSExtProc", status UNKNOWN, has 1 handler(s) for this service...
The command completed successfully
[oracle@odbsrv02 workload]$ sqlplus / as sysdba

SQL*Plus: Release 11.2.0.1.0 Production on Thu Aug 5 11:47:07 2010

Copyright (c) 1982, 2009, Oracle. All rights reserved.

Connected to an idle instance.

SQL> startup restrict;
ORACLE instance started.

Total System Global Area 795127808 bytes
Fixed Size 1339456 bytes
Variable Size 276828096 bytes
Database Buffers 511705088 bytes
Redo Buffers 5255168 bytes
Database mounted.
Database opened.
SQL>
SQL> select logins from v$instance;

LOGINS
----------
RESTRICTED

SQL>

.


2.5 Inicie a captura do workload, este procedimento retira automaticamente a base do modo restrito:



SQL> create directory "ago10" as '/u02/dbreplay/workload';

Directory created.

SQL>
SQL> begin
2 dbms_workload_capture.start_capture ( name => '2010Ago',
3 dir => 'ago10');
4 end;
5 /

PL/SQL procedure successfully completed.

SQL>
SQL> select logins from v$instance;

LOGINS
----------
ALLOWED

SQL>

Name => Nome que você atribui a essa captura de workload
Dir => Especifique um diretório que vai receber os arquivos de workload
Duration => Especifique quantos segundos a captura vai durar

Dos três parametros somente o “Dir” é obrigatório, você pode omitir o parâmetro
“Duration” e encerrar a captura manualmente utilizando a procedure FINISH_CAPTURE
da package DBMS_WORKLOAD_CAPTURE.


.


2.6 Volte para a sessão Linux do tópico 1 e inicie o script que vai simular o workload:



[oracle@odbsrv02 scripts]$ pwd
/u02/dbreplay/scripts
[oracle@odbsrv02 scripts]$ ./wcr_demo_workload.sh
[1] 5937
[2] 5938
[3] 5939
[4] 5940
[5] 5941
[6] 5942
[7] 5943
Color: blue, Thinktime: 0.010000, Number of pixels:100, Number of updates:3000 Initial delay:0 updates per commit:1
Color: salmon, Thinktime: 0.000010, Number of pixels:100, Number of updates:2000 Initial delay:40 updates per commit:1
Color: orange, Thinktime: 0.000010, Number of pixels:100, Number of updates:2000 Initial delay:30 updates per commit:1
Color: yellow, Thinktime: 0.000010, Number of pixels:100, Number of updates:2000 Initial delay:10 updates per commit:1
[8] 5944
Color: red, Thinktime: 0.010000, Number of pixels:100, Number of updates:3000 Initial delay:0 updates per commit:1
Color: green, Thinktime: 0.010000, Number of pixels:100, Number of updates:3000 Initial delay:0 updates per commit:1
Color: black, Thinktime: 0.010000, Number of pixels:100, Number of updates:3000 Initial delay:0 updates per commit:1
[9] 5948
[10] 5954
[11] 5956
[12] 5957

SQL*Plus: Release 11.2.0.1.0 Production on Thu Aug 5 13:38:09 2010

Copyright (c) 1982, 2009, Oracle. All rights reserved.


SQL*Plus: Release 11.2.0.1.0 Production on Thu Aug 5 13:38:09 2010

Copyright (c) 1982, 2009, Oracle. All rights reserved.


SQL*Plus: Release 11.2.0.1.0 Production on Thu Aug 5 13:38:09 2010

Copyright (c) 1982, 2009, Oracle. All rights reserved.


SQL*Plus: Release 11.2.0.1.0 Production on Thu Aug 5 13:38:10 2010

Copyright (c) 1982, 2009, Oracle. All rights reserved.


SQL*Plus: Release 11.2.0.1.0 Production on Thu Aug 5 13:38:10 2010

Copyright (c) 1982, 2009, Oracle. All rights reserved.


Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options


Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

SQL> SQL>
Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

SQL>
Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

SQL>
Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

SQL> Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

PL/SQL procedure successfully completed.

SQL> Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

PL/SQL procedure successfully completed.

SQL> Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

PL/SQL procedure successfully completed.

SQL> Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

PL/SQL procedure successfully completed.

SQL> Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
[12] Done q.sh
[11] - Done q.sh
[10] + Done q.sh
[9] + Done q.sh
[8] + Done q.sh
[7] + Done wcr_demo -d 40 -c salmon -t 0.00001 -u 2000
[6] + Done wcr_demo -d 30 -c orange -t 0.00001 -u 2000
[5] + Done wcr_demo -c yellow -d 10 -t 0.00001 -u 2000
[4] + Done wcr_demo -u 3000 -t 0.01 -c black
[3] + Done wcr_demo -u 3000 -t 0.01 -c blue
[2] + Done wcr_demo -u 3000 -t 0.01 -c green
[1] + Done wcr_demo -u 3000 -t 0.01 -c red
[oracle@odbsrv02 scripts]$

.


2.7 Quando todas as sessões encerrarem, desative a captura de workload:



SQL> begin
2 dbms_workload_capture.finish_capture ();
3 end;
4 /

PL/SQL procedure successfully completed.

SQL>

.


2.8 Verifique o relatório gerado no diretório:


       /u02/dbreplay/workload/wcr_cr.text


Database Capture Report For LAB1

DB Name DB Id Release RAC Capture Name Status
------------ ----------- ----------- --- -------------------------- ----------
LAB1 2204424562 11.2.0.1.0 NO 2010Ago COMPLETED


Start time: 05-Aug-10 15:14:07 (SCN = 5050437)
End time: 05-Aug-10 16:45:12 (SCN = 5124608)
Duration: 1 hour 31 minutes 5 seconds
Capture size: 8.02 MB
Directory object: ago10
Directory path: /u02/dbreplay/workload
Directory shared in RAC: TRUE
Filters used: 0 EXCLUSION filters

Captured Workload Statistics DB: LAB1 Snaps: 212-254
-> 'Value' represents the corresponding statistic aggregated
across the entire captured database workload.
-> '% Total' is the percentage of 'Value' over the corresponding
system-wide aggregated total.

Statistic Name Value % Total
---------------------------------------- ------------- ---------
DB time (secs) 2162.97 99.90
Average Active Sessions 0.40
User calls captured 36367 99.30
User calls captured with Errors 0
Session logins 25 18.38
Transactions 36000 98.44

.


3. Pré-processamento do Workload de Produção


3.1 Para dar sequência nesta simulação precisamos restaurar o backup que foi feito antes da execução do Workload simulado nas etapas anteriores, no nosso exemplo vamos utilizar uma maquina virtual clone do servidor inicial;


3.2 Crie o diretório para receber os arquivos de workload:



[oracle@odbsrv12 dbreplay]$ pwd
/u02/dbreplay
[oracle@odbsrv12 dbreplay]$ mkdir captura
[oracle@odbsrv12 dbreplay]$ cd captura/
[oracle@odbsrv12 captura]$ pwd
/u02/dbreplay/captura
[oracle@odbsrv12 captura]$

[oracle@odbsrv12 captura]$ sqlplus / as sysdba

SQL*Plus: Release 11.2.0.1.0 Production on Fri Aug 6 03:40:44 2010

Copyright (c) 1982, 2009, Oracle. All rights reserved.


Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

SQL> create directory captura as '/u02/dbreplay/captura';

Directory created.

SQL>

.


3.3 Transfira os arquivos de captura gerados na etapa 2.5 no diretório: /u02/dbreplay/workload para a base onde você vai reproduzir o workload no diretório: /u02/dbreplay/captura;


3.4 Execute o processo de pré-processamento do Workload:



SQL> begin
2 dbms_workload_replay.process_capture (capture_dir => 'CAPTURA');
3 end;
4 /

PL/SQL procedure successfully completed.

SQL>

OBS: Este processo vai criar um novo diretório (pp11.2.0.1.0) dentro do diretório
“/u02/dbreplay/captura” onde serão armazenados os arquivos que serão utilizados
no REPLAY do workload.

.


4. Executado o Workload capturado numa base de teste

4.1 Antes de executar o Replay algumas configurações precisam ser realizadas para evitar erros no processo de Replay e a alteração indevida de dados na produção:



* Altere o horário para o mesmo horário da captura do workload em produção;
* Resolva todas as referências externas ao Banco de d ados
(DBLinks, Directories, external tables, URLs, etc...)

.


4.2 Para reproduzir o workload capturado precisamos de uma ou mais instalação de client Oracle 11g e os arquivos pre-processados da captura do workload precisam estar acessíveis aos clients;


4.3 Antes de iniciarmos precisamos verificar quantos clients serão necessários para executar o Replay do workload:



F:\Oracle\OBE\Oracle11g_Mngmt_Replay\workload>wrc mode=calibrate replaydir=.

Workload Replay Client: Release 11.2.0.1.0 - Production on Seg Ago 23 15:15:08 2010

Copyright (c) 1982, 2009, Oracle and/or its affiliates. All rights reserved.


Report for Workload in: .
-----------------------

Recommendation:
Consider using at least 1 clients divided among 1 CPU(s)
You will need at least 48 MB of memory per client process.
If your machine(s) cannot match that number, consider using more clients.

Workload Characteristics:
- max concurrency: 13 sessions
- total number of sessions: 26

Assumptions:
- 1 client process per 50 concurrent sessions
- 4 client process per CPU
- 256 KB of memory cache per concurrent session
- think time scale = 100
- connect time scale = 100
- synchronization = TRUE


F:\Oracle\OBE\Oracle11g_Mngmt_Replay\workload>


Obs: O processo de calibragem sugere que um client será suficiente para processar
as 26 sessões do workload capturado.

.


4.4 Conecte numa sessão SQLPlus e prepare o processo de Replay:



F:\Oracle\OBE\Oracle11g_Mngmt_Replay\workload>sqlplus /nolog

SQL*Plus: Release 11.2.0.1.0 Production on Seg Ago 23 15:12:24 2010

Copyright (c) 1982, 2010, Oracle. All rights reserved.

SQL> connect sys/oracle@lab12 as sysdba;
Conectado.
SQL> BEGIN
2 DBMS_WORKLOAD_REPLAY.initialize_replay (replay_name => 'test_capture_1',
3 replay_dir => 'CAPTURA');
4 DBMS_WORKLOAD_REPLAY.prepare_replay (synchronization => TRUE);
5 END;
6 /

Procedimento PL/SQL concluído com sucesso.

SQL>

.


4.5 Inicie o client para execução do Replay:



F:\Oracle\OBE\Oracle11g_Mngmt_Replay\workload>wrc system/oracle@lab12 mode=replay replaydir=. CONNECTION_OVERRIDE=TRUE

Workload Replay Client: Release 11.2.0.1.0 - Production on Seg Ago 23 16:29:24 2010

Copyright (c) 1982, 2009, Oracle and/or its affiliates. All rights reserved.


Wait for the replay to start (16:29:24)

Obs1: O processo de Replay só será iniciado após a execução da próxima etapa.

Obs2: O parametro CONNECTION_OVERRIDE esta sendo utilizado pois o workload de teste
gerado na base de captura foi executado de um client no mesmo servidor do banco e
o Replay esta sendo executado em um client que não esta no servidor do banco.


.


4.6 Após iniciar o client na etapa anterior para executar o workload, este permanecerá parado até que seja executado o comando "start" abaixo numa sessão de SQLPLUS:



SQL> BEGIN
2 DBMS_WORKLOAD_REPLAY.start_replay;
3 END;
4 /

Procedimento PL/SQL concluído com sucesso.

SQL>

.


4.7 Quando o processo de Replay estiver concluido a sessão de client apresentará a mensagem de finalização:



F:\Oracle\OBE\Oracle11g_Mngmt_Replay\workload>wrc system/oracle@lab12 mode=replay replaydir=. CONNECTION_OVERRIDE=TRUE

Workload Replay Client: Release 11.2.0.1.0 - Production on Seg Ago 23 16:29:24 2010

Copyright (c) 1982, 2009, Oracle and/or its affiliates. All rights reserved.


Wait for the replay to start (16:29:24)
Replay started (16:30:16)
Replay finished (17:45:25)

F:\Oracle\OBE\Oracle11g_Mngmt_Replay\workload>

.


5. Analisando a execução de teste e gerando relatório

5.1 Emita o relatório comparativo da Captura e Replay e verifique as diferenças entre os dois processos:



SQL> select dbms_workload_replay.report(1,'TEXT') from dual;

DBMS_WORKLOAD_REPLAY.REPORT(1,'TEXT')
----------------------------------------------------------------------------------------------------------------------
DB Replay Report for test_capture_1
---------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------
| DB Name | DB Id | Release | RAC | Replay Name | Replay Status |
----------------------------------------------------------------------------
| LAB1 | 2204424562 | 11.2.0.1.0 | NO | test_capture_1 | COMPLETED |
----------------------------------------------------------------------------

Replay Information
--------------------------------------------------------------------------
| Information | Replay | Capture |
--------------------------------------------------------------------------
| Name | test_capture_1 | 2010Ago |
--------------------------------------------------------------------------
| Status | COMPLETED | COMPLETED |
--------------------------------------------------------------------------
| Database Name | LAB1 | LAB1 |
--------------------------------------------------------------------------
| Database Version | 11.2.0.1.0 | 11.2.0.1.0 |
--------------------------------------------------------------------------
| Start Time | 06-08-10 08:42:50 | 05-08-10 15:14:07 |
--------------------------------------------------------------------------
| End Time | 06-08-10 09:40:48 | 05-08-10 16:45:12 |
--------------------------------------------------------------------------
| Duration | 57 minutes 58 seconds | 1 hour 31 minutes 5 seconds |
--------------------------------------------------------------------------
| Directory Object | CAPTURA | CAPTURA |
--------------------------------------------------------------------------
| Directory Path | /u02/dbreplay/captura | /u02/dbreplay/captura |
--------------------------------------------------------------------------

Replay Options
---------------------------------------------------------
| Option Name | Value |
---------------------------------------------------------
| Synchronization | SCN |
---------------------------------------------------------
| Connect Time | 100% |
---------------------------------------------------------
| Think Time | 100% |
---------------------------------------------------------
| Think Time Auto Correct | TRUE |
---------------------------------------------------------
| Number of WRC Clients | 1 (1 Completed, 0 Running ) |
---------------------------------------------------------

Replay Statistics
-----------------------------------------------------------------
| Statistic | Replay | Capture |
-----------------------------------------------------------------
| DB Time | 2236.754 seconds | 2162.968 seconds |
-----------------------------------------------------------------
| Average Active Sessions | .64 | .4 |
-----------------------------------------------------------------
| User calls | 36367 | 36367 |
-----------------------------------------------------------------
| Network Time | 380.858 seconds | . |
-----------------------------------------------------------------
| Think Time | 4002.013 seconds | . |
-----------------------------------------------------------------

Replay Divergence Summary
-------------------------------------------------------------------
| Divergence Type | Count | % Total |
-------------------------------------------------------------------
| Session Failures During Replay | 0 | 0.00 |
-------------------------------------------------------------------
| Errors No Longer Seen During Replay | 0 | 0.00 |
-------------------------------------------------------------------
| New Errors Seen During Replay | 0 | 0.00 |
-------------------------------------------------------------------
| Errors Mutated During Replay | 0 | 0.00 |
-------------------------------------------------------------------
| DMLs with Different Number of Rows Modified | 0 | 0.00 |
-------------------------------------------------------------------
| SELECTs with Different Number of Rows Fetched | 0 | 0.00 |
-------------------------------------------------------------------

.

sexta-feira, 6 de agosto de 2010

Upgrade Oracle10gR2 para Oracle11gR2

Objetivo:

Precisamos fazer um upgrade de uma base Oracle 10gR2 para 11gR2, existem vários procedimentos que podemos utilizar para realizar este upgrade, neste exemplo vamos realizar um upgrade manual utilizando alguns scripts da Oracle disponíveis no diretório $ORACLE_HOME/rdbms/admin de uma instalação do Oracle 11gR2.


Ambiente:
SO: Linux 2.6.9-67.0.0.0.1.EL i686 i386 GNU/Linux
Base: Oracle Database 10.2.0.5.0


Tópicos:

1. Instalando os binários do Oracle 11gR2;
2. Verificando os pré-requisitos;
3. Preparando o banco para Upgrade;
4. Realizando o Upgrade da base;
5. Tarefas após o Upgrade da base;


1. Instalando os binários do Oracle 11gR2


  • Unzip dos arquivos de instalação em um filesystem no servidor que hospeda a base 10gR2, neste exemplo /u02/install;

  • Instale os binários do Oracle 11gR2 utilizando o OUI no diretório: /u01/app/oracle/product/11.2.0/lab1;


2. Verificando os pré-requisitos;

    2.1 Crie um diretório para o Upgrade:
    [oracle@odbsrv02 oracle]$ mkdir /u01/app/oracle/upgrade
      2.2 Copie o script pré-upgrade (utlu112i.sql) do $ORACLE_HOME/rdbms/admin para o diretório de Upgrade:
      [oracle@odbsrv02 upgrade]$ cd /u01/app/oracle/product/11.2.0/lab1/rdbms/admin
      [oracle@odbsrv02 admin]$ cp utlu112i.sql /u01/app/oracle/upgrade
      [oracle@odbsrv02 admin]$ ll /u01/app/oracle/upgrade
      total 188
      -rw-r--r-- 1 oracle oinstall 185744 Jul 9 00:10 utlu112i.sql
      [oracle@odbsrv02 admin]$
      2.3 Conecte-se a base 10g e execute o script de pré-upgrade gravando o resultado num arquivo de log:
      [oracle@odbsrv02 admin]$ cd /u01/app/oracle/upgrade
      [oracle@odbsrv02 upgrade]$ sqlplus / as sysdba

      SQL*Plus: Release 10.2.0.5.0 - Production on Fri Jul 9 00:12:16 2010

      Copyright (c) 1982, 2010, Oracle. All Rights Reserved.


      Connected to:
      Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - Production
      With the Partitioning, OLAP, Data Mining and Real Application Testing options

      SQL> @utlu112i;


      2.4 Abaixo podemos vizualizar o resultado do script:

      
      Oracle Database 11.2 Pre-Upgrade Information Tool    07-09-2010 00:17:12
      .
      **********************************************************************
      Database:
      **********************************************************************
      --> name:          LAB1
      --> version:       10.2.0.5.0
      --> compatible:    10.2.0.1.0
      --> blocksize:     8192
      --> platform:      Linux IA (32-bit)
      --> timezone file: V4
      .
      **********************************************************************
      Tablespaces: [make adjustments in the current environment]
      **********************************************************************
      --> SYSTEM tablespace is adequate for the upgrade.
      .... minimum required size: 764 MB
      .... AUTOEXTEND additional space required: 224 MB
      --> UNDOTBS1 tablespace is adequate for the upgrade.
      .... minimum required size: 76 MB
      --> SYSAUX tablespace is adequate for the upgrade.
      .... minimum required size: 545 MB
      .... AUTOEXTEND additional space required: 215 MB
      --> TEMP tablespace is adequate for the upgrade.
      .... minimum required size: 61 MB
      .... AUTOEXTEND additional space required: 31 MB
      --> EXAMPLE tablespace is adequate for the upgrade.
      .... minimum required size: 94 MB
      .
      **********************************************************************
      Flashback: OFF
      **********************************************************************
      **********************************************************************
      Update Parameters: [Update Oracle Database 11.2 init.ora or spfile]
      **********************************************************************
      WARNING: --> "java_pool_size" needs to be increased to at least 64 MB
      .
      **********************************************************************
      Renamed Parameters: [Update Oracle Database 11.2 init.ora or spfile]
      **********************************************************************
      -- No renamed parameters found. No changes are required.
      .
      **********************************************************************
      Obsolete/Deprecated Parameters: [Update Oracle Database 11.2 init.ora or spfile]
      **********************************************************************
      --> background_dump_dest         11.1       DEPRECATED   replaced by
      "diagnostic_dest"
      --> user_dump_dest               11.1       DEPRECATED   replaced by
      "diagnostic_dest"
      --> core_dump_dest               11.1       DEPRECATED   replaced by
      "diagnostic_dest"
      .
      **********************************************************************
      Components: [The following database components will be upgraded or installed]
      **********************************************************************
      --> Oracle Catalog Views         [upgrade]  VALID
      --> Oracle Packages and Types    [upgrade]  VALID
      --> JServer JAVA Virtual Machine [upgrade]  VALID
      --> Oracle XDK for Java          [upgrade]  VALID
      --> Oracle Workspace Manager     [upgrade]  VALID
      --> OLAP Analytic Workspace      [upgrade]  VALID
      --> OLAP Catalog                 [upgrade]  VALID
      --> EM Repository                [upgrade]  VALID
      --> Oracle Text                  [upgrade]  VALID
      --> Oracle XML Database          [upgrade]  VALID
      --> Oracle Java Packages         [upgrade]  VALID
      --> Oracle interMedia            [upgrade]  VALID
      --> Spatial                      [upgrade]  VALID
      --> Data Mining                  [upgrade]  VALID
      --> Expression Filter            [upgrade]  VALID
      --> Rule Manager                 [upgrade]  VALID
      --> Oracle OLAP API              [upgrade]  VALID
      .
      **********************************************************************
      Miscellaneous Warnings
      **********************************************************************
      WARNING: --> Database is using a timezone file older than version 11.
      .... After the release migration, it is recommended that DBMS_DST package
      .... be used to upgrade the 10.2.0.5.0 database timezone version
      .... to the latest version which comes with the new release.
      WARNING: --> Database contains schemas with stale optimizer statistics.
      .... Refer to the Upgrade Guide for instructions to update
      .... schema statistics prior to upgrading the database.
      .... Component Schemas with stale statistics:
      ....   SYS
      ....   OLAPSYS
      ....   SYSMAN
      WARNING: --> Database contains schemas with objects dependent on network
      packages.
      .... Refer to the Upgrade Guide for instructions to configure Network ACLs.
      .... USER HR has dependent objects.
      .... USER ORACLE_OCM has dependent objects.
      WARNING: --> EM Database Control Repository exists in the database.
      .... Direct downgrade of EM Database Control is not supported. Refer to the
      .... Upgrade Guide for instructions to save the EM data prior to upgrade.
      WARNING:--> recycle bin in use.
      .... Your recycle bin is turned on and it contains
      .... 1 object(s).  It is REQUIRED
      .... that the recycle bin is empty prior to upgrading
      .... your database.
      .... The command:  PURGE DBA_RECYCLEBIN
      .... must be executed immediately prior to executing your upgrade.
      .
      
      PL/SQL procedure successfully completed.
      
      SQL>
      
      .

      3. Preparando o banco para Upgrade;
      3.1 Antes de iniciar o upgrade verifique as recomendações apontadas no relatório gerado pelo script pré-upgrade e realize as modificações necessárias para atender aos pré-riquisitos do upgrade.

      3.2 Atualize as estatísticas apontadas no relatório:

      
      SQL> EXECUTE DBMS_STATS.GATHER_SCHEMA_STATS('CTXSYS',DBMS_STATS.AUTO_SAMPLE_SIZE);
      
      PL/SQL procedure successfully completed.
      
      SQL> EXECUTE DBMS_STATS.GATHER_SCHEMA_STATS('OLAPSYS',DBMS_STATS.AUTO_SAMPLE_SIZE);
      
      PL/SQL procedure successfully completed.
      
      SQL> EXECUTE DBMS_STATS.GATHER_SCHEMA_STATS('SYSMAN',DBMS_STATS.AUTO_SAMPLE_SIZE);
      
      PL/SQL procedure successfully completed.
      
      SQL> EXECUTE DBMS_STATS.GATHER_DICTIONARY_STATS();
      
      PL/SQL procedure successfully completed.
      
      SQL>
      
      .

      3.3 Desative a fila de processos Batch:

      
      SQL> alter system set job_queue_processes=0 scope=BOTH;
      
      System altered.
      
      SQL>
      
      Obs: Se houver algum script agendado na crontab do Linux, tambem devemos desativa-lo durante o processo de upgrade.
      
      .

      3.4 Altere o valor do parametro java_pool_size:

      
      SQL> alter system set java_pool_size = 70M scope=BOTH;
      
      .

      3.4 Ao realizar um upgrade em uma base de produção temos que verificar uma série de situações que podem comprometer o processo de upgrade, o note ID 837570.1 disponibiliza uma lista completa das verificações necessárias.
      4. Realizando o Upgrade da base
      4.1 Faça um backup do spfile e copie o arquivo de initlab1.ora do ORACLE_HOME/dbs (10g) para o ORACLE_HOME/dbs ( 11g);

      4.2 O parametro de inicialização DIAGNOSTIC_DEST substituiu os parametros USER_DUMP_DEST e BACKGROUND_DUMP_DEST que se tornaram obsoletos, altere o arquivo de inicialização ajustando os diretórios para o novo ORACLE_HOME (11g):
      [oracle@odbsrv02 dbs]$ cat initlab1.ora
      lab1.__db_cache_size=255852544
      lab1.__java_pool_size=75497472
      lab1.__large_pool_size=4194304
      lab1.__shared_pool_size=192937984
      lab1.__streams_pool_size=4194304
      *.aq_tm_processes=0
      *.audit_file_dest='/u01/app/oracle/product/11.2.0/lab1/diagnostics/adump'
      *.compatible='10.2.0.1.0'
      *.control_files='/u01/app/oracle/product/10.2.0/oradata/db_1/lab1/control01.ctl',
      '/u01/app/oracle/product/10.2.0/oradata/db_1/lab1/control02.ctl',
      '/u01/app/oracle/product/10.2.0/oradata/db_1/lab1/control03.ctl'
      *.core_dump_dest='/u01/app/oracle/product/11.2.0/lab1/diagnostics/cdump'
      *.db_block_size=8192
      *.db_domain=''
      *.db_name='lab1'
      *.dispatchers='(PROTOCOL=TCP) (SERVICE=lab1XDB)'
      *.java_pool_size=75497472
      *.job_queue_processes=0
      *.nls_length_semantics='BYTE'
      *.open_cursors=300
      *.pga_aggregate_target=25165824
      *.processes=150
      *.remote_login_passwordfile='EXCLUSIVE'
      *.resource_manager_plan=''
      *.sga_max_size=536870912
      *.sga_target=536870912
      *.undo_management='AUTO'
      *.undo_retention=900
      *.undo_tablespace='UNDOTBS1'
      *.utl_file_dir='/u01/app/oracle/product/10.2.0/flash_recovery_area/db_1/LAB1/archivelog'
      *.diagnostic_dest='/u01/app/oracle/product/11.2.0/lab1/diagnostics'
      4.3 Desative a geração de archive para a realização do upgrade, isto permitirá que o upgrade seja realizado num intervalo de tempo menor;
      4.4 Desative o EM DBConsole se estiver ativo;

      4.5 Desative o banco: shutdown immediate;

      4.6 Desative o Listener;

      4.7 Faça um backup full da base antes do upgrade;

      4.8 Copie o arquivo de password do diretório $ORACLE_HOME/dbs do ORACLE_HOME 10g para o ORACLE_HOME 11g;

      4.9 Configure as variáveis de ambiente para a base 11g:
      [oracle@odbsrv02 dbs]$ export ORACLE_BASE=/u01/app/oracle
      [oracle@odbsrv02 dbs]$ export ORACLE_HOME=/u01/app/oracle/product/11.2.0/lab1
      [oracle@odbsrv02 dbs]$ export PATH=/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin:/home/oracle/bin:/u01/app/oracle/product/11.2.0/lab1/bin
      4.10 Altere o arquivo /etc/oratab para o ORACLE_HOME (11G):
      EXEMPLO /etc/oratab
      #lab1:/u01/app/oracle/product/10.2.0/db_1:N
      lab1:/u01/app/oracle/product/11.2.0/lab1:N

      4.11 Execute o script de upgrade da base:

      
      [oracle@odbsrv02 ~]$ cd $ORACLE_HOME/rdbms/admin
      [oracle@odbsrv02 admin]$ sqlplus / as sysdba
      
      SQL*Plus: Release 11.2.0.1.0 Production on Fri Jul 9 07:12:01 2010
      
      Copyright (c) 1982, 2009, Oracle.  All rights reserved.
      
      Connected to an idle instance.
      
      SQL> startup upgrade;
      ORACLE instance started.
      
      Total System Global Area  535662592 bytes
      Fixed Size                  1337720 bytes
      Variable Size             218105480 bytes
      Database Buffers          310378496 bytes
      Redo Buffers                5840896 bytes
      Database mounted.
      Database opened.
      SQL> @catupgrd;
      
      .

      5. Tarefas após o Upgrade da base;

      5.1 Após o upgrade a base é encerrada e torna-se inativa, vamos ativar a base e verificar a integridade dos objetos:

      
      [oracle@odbsrv02 admin]$ sqlplus / as sysdba
      
      SQL*Plus: Release 11.2.0.1.0 Production on Fri Jul 9 08:19:41 2010
      
      Copyright (c) 1982, 2009, Oracle.  All rights reserved.
      
      Connected to an idle instance.
      
      SQL> startup
      ORACLE instance started.
      
      Total System Global Area  535662592 bytes
      Fixed Size                  1337720 bytes
      Variable Size             218105480 bytes
      Database Buffers          310378496 bytes
      Redo Buffers                5840896 bytes
      Database mounted.
      Database opened.
      SQL> @utlrp.sql
      .
      .
      SQL> select count(*) from dba_objects where status <> 'VALID';
      
      COUNT(*)
      ----------
      0
      
      SQL>
      SQL> @utlu112s.sql
      .
      Oracle Database 11.2 Post-Upgrade Status Tool           08-05-2010 08:40:05
      .
      Component                                Status         Version  HH:MM:SS
      .
      Oracle Server
      .                                         VALID      11.2.0.1.0  00:19:46
      JServer JAVA Virtual Machine
      .                                         VALID      11.2.0.1.0  00:04:47
      Oracle Workspace Manager
      .                                         VALID      11.2.0.1.0  00:01:02
      OLAP Analytic Workspace
      .                                         VALID      11.2.0.1.0  00:00:28
      OLAP Catalog
      .                                         VALID      11.2.0.1.0  00:01:20
      Oracle OLAP API
      .                                         VALID      11.2.0.1.0  00:01:15
      Oracle Enterprise Manager
      .                                         VALID      11.2.0.1.0  00:12:49
      Oracle XDK
      .                                         VALID      11.2.0.1.0  00:03:40
      Oracle Text
      .                                         VALID      11.2.0.1.0  00:01:14
      Oracle XML Database
      .                                         VALID      11.2.0.1.0  00:05:51
      Oracle Database Java Packages
      .                                         VALID      11.2.0.1.0  00:01:06
      Oracle Multimedia
      .                                         VALID      11.2.0.1.0  00:07:51
      Spatial
      .                                         VALID      11.2.0.1.0  00:07:49
      Oracle Expression Filter
      .                                         VALID      11.2.0.1.0  00:00:32
      Oracle Rule Manager
      .                                         VALID      11.2.0.1.0  00:00:19
      Gathering Statistics
      .                                                                00:07:40
      Total Upgrade Time: 01:17:41
      
      PL/SQL procedure successfully completed.
      
      SQL>
      
      .

      5.2 Confirmado que a base esta integra podemos executar o script que realizará as tarefas finais com a base aberta em modo normal:

      
      SQL> spool /u01/app/oracle/upgrade/catuppst.log;
      SQL> @catuppst.sql
      SQL> @utlrp.sql
      SQL> select count(*) from dba_objects where status <> 'VALID';
      
      COUNT(*)
      ----------
      0
      
      SQL>
      
      .

      5.3 Copie o arquivo listener.ora do ORACLE_HOME 10g para o 11g, modifique o arquivo alterando o ORACLE_HOME para 11g e inicie o Listener:

      
      [oracle@odbsrv02 admin]$ cd /u01/app/oracle/product/10.2.0/db_1/network/admin/
      [oracle@odbsrv02 admin]$ cp listener.ora /u01/app/oracle/product/11.2.0/lab1/network/admin/
      [oracle@odbsrv02 admin]$ ll /u01/app/oracle/product/11.2.0/lab1/network/admin/
      total 12
      -rw-r--r--  1 oracle oinstall  516 Aug  5 08:49 listener.ora
      drwxr-xr-x  2 oracle oinstall 4096 Aug  5 05:52 samples
      -rw-r--r--  1 oracle oinstall  187 May  9  2007 shrept.lst
      [oracle@odbsrv02 admin]$ cd /u01/app/oracle/product/11.2.0/lab1/network/admin
      [oracle@odbsrv02 admin]$ vi listener.ora
      [oracle@odbsrv02 admin]$ cat listener.ora
      # listener.ora Network Configuration File: /u01/app/oracle/product/11.2.0/lab1/network/admin/listener.ora
      # Generated by Oracle configuration tools.
      
      SID_LIST_LISTENER =
      (SID_LIST =
      (SID_DESC =
      (SID_NAME = PLSExtProc)
      (ORACLE_HOME = /u01/app/oracle/product/11.2.0/lab1)
      (PROGRAM = extproc)
      )
      )
      
      LISTENER =
      (DESCRIPTION_LIST =
      (DESCRIPTION =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1))
      (ADDRESS = (PROTOCOL = TCP)(HOST = odbsrv02.localdomain)(PORT = 1521))
      )
      )
      
      [oracle@odbsrv02 admin]$
      [oracle@odbsrv02 admin]$ lsnrctl start
      
      LSNRCTL for Linux: Version 11.2.0.1.0 - Production on 05-AUG-2010 08:55:16
      
      Copyright (c) 1991, 2009, Oracle.  All rights reserved.
      
      Starting /u01/app/oracle/product/11.2.0/lab1/bin/tnslsnr: please wait...
      
      TNSLSNR for Linux: Version 11.2.0.1.0 - Production
      System parameter file is /u01/app/oracle/product/11.2.0/lab1/network/admin/listener.ora
      Log messages written to /u01/app/oracle/diag/tnslsnr/odbsrv02/listener/alert/log.xml
      Listening on: (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(KEY=EXTPROC1)))
      Listening on: (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=odbsrv02.localdomain)(PORT=1521)))
      
      Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1)))
      STATUS of the LISTENER
      ------------------------
      Alias                     LISTENER
      Version                   TNSLSNR for Linux: Version 11.2.0.1.0 - Production
      Start Date                05-AUG-2010 08:55:19
      Uptime                    0 days 0 hr. 0 min. 1 sec
      Trace Level               off
      Security                  ON: Local OS Authentication
      SNMP                      OFF
      Listener Parameter File   /u01/app/oracle/product/11.2.0/lab1/network/admin/listener.ora
      Listener Log File         /u01/app/oracle/diag/tnslsnr/odbsrv02/listener/alert/log.xml
      Listening Endpoints Summary...
      (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(KEY=EXTPROC1)))
      (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=odbsrv02.localdomain)(PORT=1521)))
      Services Summary...
      Service "PLSExtProc" has 1 instance(s).
      Instance "PLSExtProc", status UNKNOWN, has 1 handler(s) for this service...
      The command completed successfully
      [oracle@odbsrv02 admin]$
      
      .

      5.4 Atualize os arquivo “/etc/oratab” e “/home/oracle/.bash_profile” com o ORACLE_HOME 11g.

      segunda-feira, 12 de julho de 2010

      Copiando tabelas sem utilizar export/import

      Objetivo:


      Uma tarefa muito comum no dia a dia do DBA é copiar tabelas de uma base de produção para uma base de desenvolvimento ou Homologação. Essa tarefa na maioria das vezes é realizada utilizando o export/import,uma alternativa a esse procedimento seria utilizar o comando COPY que é um recurso disponível no SQL*Plus.

      Ambiente:


      SO: Linux 2.6.9-67.0.0.0.1.EL i686 i386 GNU/Linux
      Base: Oracle Database 9.2.0.4.0 e Oracle Database 10.2.0.5.0

      Restrições:

      1. O comando COPY suporta somente os seguintes datatypes: CHAR, DATE, LONG, NUMBER e VARCHAR2;

      2. A versão 9.2.0.1.0 do SQL*Plus possui um bug: 4350952


      Possíveis contornos para esse bug:

      a) Utilize um cliente SQL*Plus das versões 10g, 11g ou 9.0.1.4.0;
      b) Utilize a função TO_NUMBER para o campo NUMBER sem especificação
      das casas decimais.
      Ex:
      copy from Scott/Tiger@INST1 create NewTable
      using Select to_number(Non_Precision_Column) ALIAS,
      COLUMN2,
      COLUMN3
      from Scott.Tablename;
      c) Utilize um cliente SQL*Plus no ambiente Unix;

      Overview:


      Nessa demonstração temos duas bases (instância: lab1 9.2.0.4.0 servidor: odbsrv92) e outra base como mesmo nome de instância (instância: lab1 10.2.0.5 servidor: odbsrv02). Vamos conectar na base 10g e copiar a tabela TEST_TAB do esquema APPL01 para o esquema TESTE na base 9i. Vamos utilizar a versão 9.2.0.1 do SLQ*Plus e devido ao bug 4350952 temos que utilizar a função TO_NUMBER no comando SELECT.

      Tópicos:

      1. Verificar existência da tabela na base 9i;
      2. Copiando a tabela TEST_TAB;
      3. Verificando a tabela copiada;

      1. Verificar existência da tabela na base 9i



      SQL> select INSTANCE_NAME, HOST_NAME, VERSION from v$instance;

      INSTANCE_NAME |HOST_NAME |VERSION
      ----------------|-----------------------|-----------------
      lab1 |odbsrv92.localdomain |9.2.0.4.0

      1 linha selecionada.

      SQL> select table_name from dba_tables where owner = 'TESTE';

      não há linhas selecionadas

      SQL>

      .


      2. Copiando a tabela TEST_TAB;



      SQL> select INSTANCE_NAME, HOST_NAME, VERSION from v$instance;

      INSTANCE_NAME HOST_NAME VERSION
      ---------------- -------------------------- ------------
      lab1 odbsrv02.localdomain 10.2.0.5.0

      Decorrido: 00:00:01.04
      SQL> desc appl01.TEST_TAB;
      Nome Nulo? Tipo
      --------------- -------- ----------------
      REGID NUMBER
      NOME VARCHAR2(30)
      ENDERECO VARCHAR2(30)
      DATA DATE
      COMENTARIO VARCHAR2(100)

      SQL> set arraysize 1000
      SQL> set copyc 100
      SQL> copy to teste/oracle@lab92 CREATE test_copy
      using select to_number(REGID) REGID,
      NOME,
      ENDERECO,
      DATA,
      COMENTARIO
      from appl01.TEST_TAB;

      Tamanho do vetor busc./ligaç.é 1000. (tamanho do vetor é 1000)
      Validará após cada 100 ligações de vetor. (validaçãocópia é 100)
      Extensão de tam.máximo é 10000000. (extensão é 10000000)
      Tabela TEST_COPY criada.

      70004 linhas selecionadas da conexão DEFAULT HOST.
      70004 linhas inseridas em TEST_COPY.
      70004 linhas validadas em TEST_COPY no teste@lab92.

      SQL>

      .


      3. Verificando a tabela copiada;



      SQL*Plus: Release 9.2.0.1.0 - Production on Seg Jul 12 10:24:25 2010

      Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved.

      SQL> conn system/oracle@lab92;
      Conectado.
      SQL> select INSTANCE_NAME, HOST_NAME, VERSION from v$instance;

      INSTANCE_NAME HOST_NAME VERSION
      ---------------- ---------------------- ---------------
      lab1 odbsrv92.localdomain 9.2.0.4.0

      SQL>
      SQL> select table_name from dba_tables where owner = 'TESTE';

      TABLE_NAME
      ------------------------------
      TEST_COPY

      SQL> select count(*) from teste.TEST_COPY;

      COUNT(*)
      ----------
      70004

      SQL>

      quarta-feira, 7 de julho de 2010

      Recriando um DBLink sem conhecimento da password

      Objetivo:


      Precisamos recriar alguns DBLinks porem não temos as senhas dos usuários utilizados nesses DBLinks, para as versões 8i e 9i podemos utilizar SYS.LINK$, mas na versão 10g o campo de senha esta criptografado, nesse caso teremos que utilizar o DATAPUMP.



      Ambiente:

      SO: Linux 2.6.9-67.0.0.0.1.EL i686 i386 GNU/Linux
      Base: Oracle Database 9.2.0.4.0 e Oracle Database 10.2.0.5.0

      Tópicos: Base 8i/9i

      1. Setup;
      2. Listar o conteudo da tabela SYS.LINK$;
      3. Gerar o comando para criação do DBLink;
      4. Recriar o DBLink em outro esquema;

      1. Setup

      Vamos criar um DBLink numa base 9i para o usuário SCOTT que irá acessar tabelas do esquema HR:


      SQL> conn scott/oracle
      Connected.
      SQL> create database link HR_LINK connect to hr identified by oracle USING 'LAB1';

      Database link created.

      SQL> select count(*) from EMPLOYEES@HR_LINK;

      COUNT(*)
      ----------
      107

      SQL>

      .


      2. Listar o conteudo da tabela SYS.LINK$



      SQL> set lines 120 pages 66
      col name for a25
      col host for a10
      col userid for a10
      col password for a20
      SELECT NAME,HOST,USERID,PASSWORD FROM SYS.LINK$;

      NAME HOST USERID PASSWORD
      ------------------------- ---------- ---------- --------------------
      HR_LINK.US.ORACLE.COM LAB1 HR ORACLE

      SQL>

      .


      3. Gerar o comando para criação do DBLink



      SQL> SELECT 'create '||DECODE(U.NAME,'PUBLIC','public ')||'database link '||CHR(10)
      2 ||DECODE(U.NAME,'PUBLIC',Null, U.NAME||'.')|| L.NAME||chr(10)
      3 ||'connect to '|| L.USERID || ' identified by "'
      4 ||L.PASSWORD||'" using ''' || L.host || ''';' AS "CREATE DBLINKS"
      5 FROM sys.link$ L, sys.user$ U
      6 WHERE L.OWNER# = U.USER#;

      CREATE DBLINKS
      -------------------------------------------------------------------------------------
      create database link
      SCOTT.HR_LINK.US.ORACLE.COM
      connect to HR identified by "ORACLE" using 'LAB1';
      SQL>

      .


      4. Recriar o DBLink em outro esquema



      SQL> conn teste/oracle
      Connected.
      SQL> create database link
      2 HR_LINK.US.ORACLE.COM
      3 connect to HR identified by "ORACLE" using 'LAB1';

      Database link created.

      SQL> select count(*) from EMPLOYEES@HR_LINK;

      COUNT(*)
      ----------
      107

      SQL>

      .


      Tópicos: Base 10g

      1. Setup;
      2. Listar o conteudo da tabela SYS.LINK$;
      3. Export do DBLink com o DATAPUMP;
      4. Import do DBLink com o DATAPUMP;
      5. Verificar se novo DBLINK esta funcionando;

      1. Setup

      Vamos criar um DBLink numa base 10g para o usuário SCOTT que irá acessar tabelas do esquema HR:



      SQL> conn sys/oracle as sysdba;
      Connected.
      SQL> grant create database link to scott;

      Grant succeeded.

      SQL> conn scott/oracle
      Connected.
      SQL> create database link HR_LINK connect to hr identified by oracle USING 'LAB1';

      Database link created.

      SQL> select count(*) from EMPLOYEES@HR_LINK;

      COUNT(*)
      ----------
      107

      SQL>

      .


      2. Listar o conteudo da tabela SYS.LINK$

      Quando listamos a tabela SYS.LINK$ , verificamos que a password não aparece no formato caracter:



      SQL> set lines 120 pages 66
      col name for a40
      col host for a10
      col userid for a10
      col password for a20
      SELECT NAME,HOST,USERID,PASSWORD FROM SYS.LINK$;

      NAME HOST USERID PASSWORD
      ---------------------------------------- ---------- ---------- --------------------
      HR_LINK.REGRESS.RDBMS.DEV.US.ORACLE.COM LAB1 HR

      SQL>


      .


      3. Export do DBLink com o DATAPUMP

      Para recriar o DBLink em outro esquema podemos utilizar o DATAPUMP com a opção INCLUDE para selecionar somente DBLinks:



      [oracle@odbsrv02 ~]$ expdp system/oracle SCHEMAS=scott INCLUDE=DB_LINK DUMPFILE=scott_dblink.dmp DIRECTORY=DATA_PUMP_DIR

      Export: Release 10.2.0.5.0 - Production on Wednesday, 07 July, 2010 10:18:48

      Copyright (c) 2003, 2007, Oracle. All rights reserved.

      Connected to: Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - Production
      With the Partitioning, OLAP, Data Mining and Real Application Testing options
      FLASHBACK automatically enabled to preserve database integrity.
      Starting "SYSTEM"."SYS_EXPORT_SCHEMA_01": system/******** SCHEMAS=scott INCLUDE=DB_LINK DUMPFILE=scott_dblink.dmp DIRECTORY=DATA_PUMP_DIR
      Estimate in progress using BLOCKS method...
      Processing object type SCHEMA_EXPORT/TABLE/TABLE_DATA
      Total estimation using BLOCKS method: 0 KB
      Processing object type SCHEMA_EXPORT/DB_LINK
      Master table "SYSTEM"."SYS_EXPORT_SCHEMA_01" successfully loaded/unloaded
      ******************************************************************************
      Dump file set for SYSTEM.SYS_EXPORT_SCHEMA_01 is:
      /u01/app/oracle/product/10.2.0/db_1/admin/lab1/dpdump/scott_dblink.dmp
      Job "SYSTEM"."SYS_EXPORT_SCHEMA_01" successfully completed at 10:19:01

      [oracle@odbsrv02 ~]$

      .


      4. Import do DBLink com o DATAPUMP

      No import podemos utilizar a opção REMAP_SCHEMA para indicar o esquema onde queremos que o DBLink seja criado:



      [oracle@odbsrv02 ~]$ impdp system/oracle REMAP_SCHEMA=scott:tstuser INCLUDE=DB_LINK DUMPFILE=scott_dblink.dmp DIRECTORY=DATA_PUMP_DIR

      Import: Release 10.2.0.5.0 - Production on Wednesday, 07 July, 2010 10:21:11

      Copyright (c) 2003, 2007, Oracle. All rights reserved.

      Connected to: Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - Production
      With the Partitioning, OLAP, Data Mining and Real Application Testing options
      Master table "SYSTEM"."SYS_IMPORT_FULL_01" successfully loaded/unloaded
      Starting "SYSTEM"."SYS_IMPORT_FULL_01": system/******** REMAP_SCHEMA=scott:tstuser INCLUDE=DB_LINK DUMPFILE=scott_dblink.dmp DIRECTORY=DATA_PUMP_DIR
      Processing object type SCHEMA_EXPORT/DB_LINK
      Job "SYSTEM"."SYS_IMPORT_FULL_01" successfully completed at 10:21:15
      [oracle@odbsrv02 ~]$

      .


      5. Verificar se novo DBLINK esta funcionando



      SQL> conn tstuser/oracle
      Connected.
      SQL> select count(*) from EMPLOYEES@HR_LINK;

      COUNT(*)
      ----------
      107

      SQL>

      terça-feira, 29 de junho de 2010

      Otimizando uma consulta sem alterar o código fonte

      Objetivo:


      Estamos realizando um trabalho para melhorar o desempenho de uma aplicação e identificamos que existe uma consulta que é a maior responsável pelo baixo desempenho desta, analisando a consulta verificamos que é possivel melhorar a performace, mas para isso precisamos alterar o código da aplicação. Essa aplicação é um pacote de um fornecedor e não temos acesso ao código fonte, uma possível solução para esse impasse seria a utilização do pacote “DBMS_ADVANCED_REWRITE” que permite a alteração de uma consulta sem alteração do código fonte da aplicação.


      Ambiente:


      SO: Linux 2.6.9-67.0.0.0.1.EL i686 i386 GNU/Linux
      Base: Oracle Database 10.2.0.5.0 com archive log habilitado


      Overview:


      O pacote DBMS_ADVANCED_REWRITE permite interceptar instruções SQL específicas e substituí-las com instruções SQL alternativa. Este recurso pode ser muito útil quando precisamos modificar uma instrução SQL visando melhoria de performace e não dispomos do código fonte da aplicação. Infelizmente este recurso tem algumas limitações e em alguns casos não podemos utilizá-lo:

      • Recurso disponível a partir da versão Oracle 10g;
      • Não funciona com instrução DML, somente com instrução SELECT;
      • Não funciona com “Bind Variables” (Metalink DOC ID: 392214.1);

      Tópicos:

      1. Previlégios necessários para o usuário;
      2. Criar uma tabela de teste;
      3. Plano de execução da consulta original;
      4. Plano de execução da consulta otimizada;
      5. Utilizar o pacote para estabelecer a equivalência;
      6. Verificar se equivalência esta funcionando;


      1. Previlégios necessários para o usuário

      SQL>
      SQL> conn sys/oracle@lab1 as sysdba;
      Conectado.
      SQL> GRANT EXECUTE ON DBMS_ADVANCED_REWRITE TO appl02;

      Concessão bem-sucedida.

      SQL> GRANT CREATE MATERIALIZED VIEW TO appl02;

      Concessão bem-sucedida.

      SQL>


      2. Criar uma tabela de teste

      SQL>
      SQL> conn appl02/oracle@lab1;
      Conectado.
      SQL> create table db_objetos as select * from all_objects;

      Tabela criada.

      SQL> create index db_obj_idx on db_objetos(OBJECT_NAME);

      Índice criado.

      SQL>


      3. Plano de execução da consulta original

      Agora vamos verificar o plano de execução de uma consulta que supostamente estaria causando grande impacto de performace na base de dados:

      SQL>
      SQL> select OWNER, OBJECT_NAME, OBJECT_TYPE
      from db_objetos
      where upper(OBJECT_NAME) = upper('all_objects');

      OWNER OBJECT_NAME OBJECT_TYPE
      ------------------------------ ------------------------------ -----------------
      SYS ALL_OBJECTS VIEW
      PUBLIC ALL_OBJECTS SYNONYM

      SQL> Explain plan for
      2 select OWNER, OBJECT_NAME, OBJECT_TYPE
      3 from db_objetos
      4 where upper(OBJECT_NAME) = upper('all_objects');

      Explicado.

      SQL> SELECT * FROM TABLE(dbms_xplan.display);

      PLAN_TABLE_OUTPUT
      --------------------------------------------------------------------------------
      Plan hash value: 440180848

      --------------------------------------------------------------------------------
      | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
      --------------------------------------------------------------------------------
      | 0 | SELECT STATEMENT | | 6 | 270 | 133 (3)| 00:00:02 |
      |* 1 | TABLE ACCESS FULL| DB_OBJETOS | 6 | 270 | 133 (3)| 00:00:02 |
      --------------------------------------------------------------------------------

      Predicate Information (identified by operation id):
      ---------------------------------------------------

      1 - filter(UPPER("OBJECT_NAME")='ALL_OBJECTS')

      Note
      -----
      - dynamic sampling used for this statement

      17 linhas selecionadas.
      SQL>


      4. Plano de execução da consulta otimizada

      Vamos supor que após uma analise na tabela “DB_OBJETOS” verificamos que o campo “OBJECT_NAME” possui somente textos com caracteres maiusculos, neste caso a consulta abaixo forneceria o mesmo resultado e utilizaria o indice desse campo, melhorando a performace da consulta:

      SQL>
      SQL> select OWNER, OBJECT_NAME, OBJECT_TYPE
      from db_objetos
      where OBJECT_NAME = upper('all_objects');

      OWNER OBJECT_NAME OBJECT_TYPE
      ------------------------------ ------------------------------ -------------------
      SYS ALL_OBJECTS VIEW
      PUBLIC ALL_OBJECTS SYNONYM

      SQL> Explain plan for
      2 select OWNER, OBJECT_NAME, OBJECT_TYPE
      3 from db_objetos
      4 where OBJECT_NAME = upper('all_objects');

      Explicado.

      SQL> SELECT * FROM TABLE(dbms_xplan.display);

      PLAN_TABLE_OUTPUT
      ------------------------------------------------------------------------------------------
      Plan hash value: 1912010479

      ------------------------------------------------------------------------------------------
      | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
      ------------------------------------------------------------------------------------------
      | 0 | SELECT STATEMENT | | 2 | 90 | 2 (0)| 00:00:01 |
      | 1 | TABLE ACCESS BY INDEX ROWID| DB_OBJETOS | 2 | 90 | 2 (0)| 00:00:01 |
      |* 2 | INDEX RANGE SCAN | DB_OBJ_IDX | 2 | | 1 (0)| 00:00:01 |
      ------------------------------------------------------------------------------------------

      Predicate Information (identified by operation id):
      ---------------------------------------------------

      2 - access("OBJECT_NAME"='ALL_OBJECTS')

      Note
      -----
      - dynamic sampling used for this statement

      18 linhas selecionadas.
      SQL>


      5. Utilizar o pacote para estabelecer a equivalência

      Agora vamos utilizar o pacote DBMS_ADVANCED_REWRITE para estabelecer a equivalência de forma que sempre que a consulta original for acionada a base Oracle utilize a consulta otimizada para execução:

      SQL>
      SQL> ALTER SESSION SET QUERY_REWRITE_INTEGRITY = TRUSTED;

      Sessão alterada.

      SQL> BEGIN
      2 sys.dbms_advanced_rewrite.declare_rewrite_equivalence (
      3 name => 'test_rw1',
      4 source_stmt =>
      5 'select OWNER, OBJECT_NAME, OBJECT_TYPE
      6 from db_objetos
      7 where upper(OBJECT_NAME) = upper(''all_objects'')',
      8 destination_stmt =>
      9 'select OWNER, OBJECT_NAME, OBJECT_TYPE
      10 from db_objetos
      11 where OBJECT_NAME = upper(''all_objects'')',
      12 validate => false,
      13 rewrite_mode => 'text_match');
      14 END;
      15 /

      Procedimento PL/SQL concluído com sucesso.


      SQL>


      6. Verificar se equivalência esta funcionando

      Na execução abaixo podemos constatar que apesar de acionar-mos a consulta original o plano de execução utilizado pela base Oracle é da consulta otimizada:

      SQL>
      SQL> Explain plan for
      2 select OWNER, OBJECT_NAME, OBJECT_TYPE
      3 from db_objetos
      4 where upper(OBJECT_NAME) = upper('all_objects');

      Explicado.

      SQL> SELECT * FROM TABLE(dbms_xplan.display);

      PLAN_TABLE_OUTPUT
      ------------------------------------------------------------------------------------------
      Plan hash value: 1912010479

      ------------------------------------------------------------------------------------------
      | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
      ------------------------------------------------------------------------------------------
      | 0 | SELECT STATEMENT | | 2 | 90 | 2 (0)| 00:00:01 |
      | 1 | TABLE ACCESS BY INDEX ROWID| DB_OBJETOS | 2 | 90 | 2 (0)| 00:00:01 |
      |* 2 | INDEX RANGE SCAN | DB_OBJ_IDX | 2 | | 1 (0)| 00:00:01 |
      ------------------------------------------------------------------------------------------

      Predicate Information (identified by operation id):
      ---------------------------------------------------

      2 - access("OBJECT_NAME"='ALL_OBJECTS')

      Note
      -----
      - dynamic sampling used for this statement

      18 linhas selecionadas.
      SQL>

      sexta-feira, 25 de junho de 2010

      Criando uma base reduzida para desenvolvimento

      Objetivo:

      Precisamos criar uma base para área de desenvolvimento realizar testes de uma aplicação e não temos espaço suficiente para clonar a base de produção, neste caso podemos utilizar um recurso do DataPump que permite copiar um percentual de dados da base.


      Ambiente:

      SO: Linux 2.6.9-67.0.0.0.1.EL i686 i386 GNU/Linux
      Base: Oracle Database 10.2.0.5.0 com archive log habilitado


      Overview:

      Nessa simulação vamos utilizar um esquema para demonstrar como podemos criar uma base de teste menor que a base de produção. O esquema utilizado será o SH que é um esquema exemplo criado opcionamento durante a instalação do banco de dados.


      Vamos utilizar a mesma base para fazer export e o import o que não inviabiliza a demonstração uma vez que o objetivo é demonstrar que podemos copiar todos os objetos de um esquema reduzindo a quantidade de espaço utilizada por eles.


      Tópicos:
      1. Criar usuário de teste;
      2. Export esquema SH;
      3. Import esquema SH_TESTE;
      4. Comparar objetos dos esquemas;
      5. Comparar tamanhos dos esquemas;

      1. Criar usuário de teste



      SQL> create user sh_teste identified by oracle
      default tablespace appl02 temporary tablespace temp;

      Usuário criado.

      SQL> grant connect to sh_teste;

      Concessão bem-sucedida.

      SQL> grant unlimited tablespace to sh_teste;

      Concessão bem-sucedida.

      SQL> spool off;





      2. Export esquema SH



      Primeiro vamos executar um EXPORT do esquema SH usando o parâmetro "SAMPLE", este parâmetro especifica um percentual de registros a serem copiados da base, neste caso vamos usar 30%:




      [oracle@odbsrv02 ~]$ expdp \"/ as sysdba\" directory=DATA_PUMP_DIR sample=30
      schemas=SH dumpfile=SH_esquema.dmp logfile=SH_esquema.log

      Export: Release 10.2.0.5.0 - Production on Wednesday, 16 June, 2010 2:30:03

      Copyright (c) 2003, 2007, Oracle. All rights reserved.

      Connected to: Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - Production
      With the Partitioning, OLAP, Data Mining and Real Application Testing options
      FLASHBACK automatically enabled to preserve database integrity.
      Starting "SYS"."SYS_EXPORT_SCHEMA_01": "/******** AS SYSDBA" directory=DATA_PUMP_DIR
      sample=30 schemas=SH dumpfile=SH_esquema.dmp logfile=SH_esquema.log

      Estimate in progress using BLOCKS method...
      Processing object type SCHEMA_EXPORT/TABLE/TABLE_DATA
      Total estimation using BLOCKS method: 35.31 MB
      Processing object type SCHEMA_EXPORT/USER
      Processing object type SCHEMA_EXPORT/SYSTEM_GRANT
      Processing object type SCHEMA_EXPORT/ROLE_GRANT
      Processing object type SCHEMA_EXPORT/DEFAULT_ROLE
      Processing object type SCHEMA_EXPORT/PRE_SCHEMA/PROCACT_SCHEMA
      Processing object type SCHEMA_EXPORT/TABLE/TABLE
      Processing object type SCHEMA_EXPORT/TABLE/GRANT/OWNER_GRANT/OBJECT_GRANT
      Processing object type SCHEMA_EXPORT/TABLE/INDEX/INDEX
      Processing object type SCHEMA_EXPORT/TABLE/CONSTRAINT/CONSTRAINT
      Processing object type SCHEMA_EXPORT/TABLE/INDEX/STATISTICS/INDEX_STATISTICS
      Processing object type SCHEMA_EXPORT/TABLE/COMMENT
      Processing object type SCHEMA_EXPORT/VIEW/VIEW
      Processing object type SCHEMA_EXPORT/TABLE/CONSTRAINT/REF_CONSTRAINT
      Processing object type SCHEMA_EXPORT/TABLE/INDEX/FUNCTIONAL_AND_BITMAP/INDEX
      Processing object type SCHEMA_EXPORT/TABLE/INDEX/STATISTICS/FUNCTIONAL_AND_BITMAP/INDEX_STATISTICS
      Processing object type SCHEMA_EXPORT/TABLE/STATISTICS/TABLE_STATISTICS
      Processing object type SCHEMA_EXPORT/TABLE/INDEX/DOMAIN_INDEX/INDEX
      Processing object type SCHEMA_EXPORT/MATERIALIZED_VIEW
      Processing object type SCHEMA_EXPORT/DIMENSION
      . . exported "SH"."CUSTOMERS" 3.004 MB 16875 rows
      . . exported "SH"."SUPPLEMENTARY_DEMOGRAPHICS" 212.3 KB 1332 rows
      . . exported "SH"."SALES":"SALES_Q4_2001" 701.6 KB 21029 rows
      . . exported "SH"."SALES":"SALES_Q1_1999" 638.7 KB 19186 rows
      . . exported "SH"."SALES":"SALES_Q3_2001" 659.5 KB 19746 rows
      . . exported "SH"."SALES":"SALES_Q1_2000" 615.4 KB 18435 rows
      . . exported "SH"."SALES":"SALES_Q1_2001" 613.8 KB 18351 rows
      . . exported "SH"."SALES":"SALES_Q2_2001" 636.1 KB 19029 rows
      . . exported "SH"."SALES":"SALES_Q3_1999" 672.3 KB 20208 rows
      . . exported "SH"."SALES":"SALES_Q4_1999" 621.0 KB 18637 rows
      . . exported "SH"."SALES":"SALES_Q2_2000" 557.8 KB 16645 rows
      . . exported "SH"."SALES":"SALES_Q3_2000" 589.0 KB 17617 rows
      . . exported "SH"."SALES":"SALES_Q4_1998" 482.4 KB 14421 rows
      . . exported "SH"."SALES":"SALES_Q4_2000" 560.1 KB 16745 rows
      . . exported "SH"."SALES":"SALES_Q2_1999" 546.6 KB 16363 rows
      . . exported "SH"."SALES":"SALES_Q1_1998" 442.2 KB 13218 rows
      . . exported "SH"."SALES":"SALES_Q3_1998" 512.7 KB 15349 rows
      . . exported "SH"."SALES":"SALES_Q2_1998" 359.0 KB 10669 rows
      . . exported "SH"."FWEEK_PSCAT_SALES_MV" 131.1 KB 3406 rows
      . . exported "SH"."PROMOTIONS" 24.66 KB 167 rows
      . . exported "SH"."TIMES" 130.2 KB 574 rows
      . . exported "SH"."COSTS":"COSTS_Q4_2001" 87.75 KB 2697 rows
      . . exported "SH"."COSTS":"COSTS_Q1_1999" 59.41 KB 1762 rows
      . . exported "SH"."COSTS":"COSTS_Q1_2001" 72.94 KB 2203 rows
      . . exported "SH"."COSTS":"COSTS_Q2_2001" 60.59 KB 1793 rows
      . . exported "SH"."COSTS":"COSTS_Q3_2001" 74.60 KB 2259 rows
      . . exported "SH"."COSTS":"COSTS_Q1_1998" 47.25 KB 1356 rows
      . . exported "SH"."COSTS":"COSTS_Q1_2000" 41.74 KB 1169 rows
      . . exported "SH"."COSTS":"COSTS_Q2_1998" 27.42 KB 692 rows
      . . exported "SH"."COSTS":"COSTS_Q2_1999" 44.67 KB 1269 rows
      . . exported "SH"."COSTS":"COSTS_Q2_2000" 39.98 KB 1110 rows
      . . exported "SH"."COSTS":"COSTS_Q3_1998" 44.03 KB 1250 rows
      . . exported "SH"."COSTS":"COSTS_Q3_1999" 47.19 KB 1353 rows
      . . exported "SH"."COSTS":"COSTS_Q3_2000" 48.67 KB 1399 rows
      . . exported "SH"."COSTS":"COSTS_Q4_1998" 47.65 KB 1369 rows
      . . exported "SH"."COSTS":"COSTS_Q4_1999" 53.85 KB 1576 rows
      . . exported "SH"."COSTS":"COSTS_Q4_2000" 52.44 KB 1525 rows
      . . exported "SH"."CAL_MONTH_SALES_MV" 5.476 KB 13 rows
      . . exported "SH"."CHANNELS" 6.515 KB 1 rows
      . . exported "SH"."COUNTRIES" 8.226 KB 7 rows
      . . exported "SH"."PRODUCTS" 15.93 KB 24 rows
      . . exported "SH"."COSTS":"COSTS_1995" 0 KB 0 rows
      . . exported "SH"."COSTS":"COSTS_1996" 0 KB 0 rows
      . . exported "SH"."COSTS":"COSTS_H1_1997" 0 KB 0 rows
      . . exported "SH"."COSTS":"COSTS_H2_1997" 0 KB 0 rows
      . . exported "SH"."COSTS":"COSTS_Q1_2002" 0 KB 0 rows
      . . exported "SH"."COSTS":"COSTS_Q1_2003" 0 KB 0 rows
      . . exported "SH"."COSTS":"COSTS_Q2_2002" 0 KB 0 rows
      . . exported "SH"."COSTS":"COSTS_Q2_2003" 0 KB 0 rows
      . . exported "SH"."COSTS":"COSTS_Q3_2002" 0 KB 0 rows
      . . exported "SH"."COSTS":"COSTS_Q3_2003" 0 KB 0 rows
      . . exported "SH"."COSTS":"COSTS_Q4_2002" 0 KB 0 rows
      . . exported "SH"."COSTS":"COSTS_Q4_2003" 0 KB 0 rows
      . . exported "SH"."MVIEW$_EXCEPTIONS" 0 KB 0 rows
      . . exported "SH"."SALES":"SALES_1995" 0 KB 0 rows
      . . exported "SH"."SALES":"SALES_1996" 0 KB 0 rows
      . . exported "SH"."SALES":"SALES_H1_1997" 0 KB 0 rows
      . . exported "SH"."SALES":"SALES_H2_1997" 0 KB 0 rows
      . . exported "SH"."SALES":"SALES_Q1_2002" 0 KB 0 rows
      . . exported "SH"."SALES":"SALES_Q1_2003" 0 KB 0 rows
      . . exported "SH"."SALES":"SALES_Q2_2002" 0 KB 0 rows
      . . exported "SH"."SALES":"SALES_Q2_2003" 0 KB 0 rows
      . . exported "SH"."SALES":"SALES_Q3_2002" 0 KB 0 rows
      . . exported "SH"."SALES":"SALES_Q3_2003" 0 KB 0 rows
      . . exported "SH"."SALES":"SALES_Q4_2002" 0 KB 0 rows
      . . exported "SH"."SALES":"SALES_Q4_2003" 0 KB 0 rows
      Master table "SYS"."SYS_EXPORT_SCHEMA_01" successfully loaded/unloaded
      ******************************************************************************
      Dump file set for SYS.SYS_EXPORT_SCHEMA_01 is:
      /u01/app/oracle/product/10.2.0/db_1/admin/lab1/dpdump/SH_esquema.dmp
      Job "SYS"."SYS_EXPORT_SCHEMA_01" successfully completed at 02:32:02

      [oracle@odbsrv02 ~]$




      3. Import esquema SH_TESTE
      Em seguida vamos importar os objetos do esquema SH no esquema SH_TESTE dizendo ao Data Pump para reduzir o tamanho das extensões para 30%:





      [oracle@odbsrv02 ~]$ impdp \"/ as sysdba\" transform=pctspace:30 remap_schema=SH:SH_TESTE
      directory=DATA_PUMP_DIR dumpfile=SH_esquema.dmp logfile=imp_SH_TESTE_esquema.log

      Import: Release 10.2.0.5.0 - Production on Wednesday, 16 June, 2010 2:47:58

      Copyright (c) 2003, 2007, Oracle. All rights reserved.

      Connected to: Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - Production
      With the Partitioning, OLAP, Data Mining and Real Application Testing options
      Master table "SYS"."SYS_IMPORT_FULL_01" successfully loaded/unloaded
      Starting "SYS"."SYS_IMPORT_FULL_01": "/******** AS SYSDBA" transform=pctspace:70 remap_schema=SH:SH_TESTE
      directory=DATA_PUMP_DIR dumpfile=SH_esquema.dmp logfile=imp_SH_TESTE_esquema.log
      Processing object type SCHEMA_EXPORT/USER
      ORA-31684: Object type USER:"SH_TESTE" already exists
      Processing object type SCHEMA_EXPORT/SYSTEM_GRANT
      Processing object type SCHEMA_EXPORT/ROLE_GRANT
      Processing object type SCHEMA_EXPORT/DEFAULT_ROLE
      Processing object type SCHEMA_EXPORT/PRE_SCHEMA/PROCACT_SCHEMA
      Processing object type SCHEMA_EXPORT/TABLE/TABLE
      Processing object type SCHEMA_EXPORT/TABLE/TABLE_DATA
      . . imported "SH_TESTE"."CUSTOMERS" 3.004 MB 16875 rows
      . . imported "SH_TESTE"."SUPPLEMENTARY_DEMOGRAPHICS" 212.3 KB 1332 rows
      . . imported "SH_TESTE"."SALES":"SALES_Q4_2001" 701.6 KB 21029 rows
      . . imported "SH_TESTE"."SALES":"SALES_Q1_1999" 638.7 KB 19186 rows
      . . imported "SH_TESTE"."SALES":"SALES_Q3_2001" 659.5 KB 19746 rows
      . . imported "SH_TESTE"."SALES":"SALES_Q1_2000" 615.4 KB 18435 rows
      . . imported "SH_TESTE"."SALES":"SALES_Q1_2001" 613.8 KB 18351 rows
      . . imported "SH_TESTE"."SALES":"SALES_Q2_2001" 636.1 KB 19029 rows
      . . imported "SH_TESTE"."SALES":"SALES_Q3_1999" 672.3 KB 20208 rows
      . . imported "SH_TESTE"."SALES":"SALES_Q4_1999" 621.0 KB 18637 rows
      . . imported "SH_TESTE"."SALES":"SALES_Q2_2000" 557.8 KB 16645 rows
      . . imported "SH_TESTE"."SALES":"SALES_Q3_2000" 589.0 KB 17617 rows
      . . imported "SH_TESTE"."SALES":"SALES_Q4_1998" 482.4 KB 14421 rows
      . . imported "SH_TESTE"."SALES":"SALES_Q4_2000" 560.1 KB 16745 rows
      . . imported "SH_TESTE"."SALES":"SALES_Q2_1999" 546.6 KB 16363 rows
      . . imported "SH_TESTE"."SALES":"SALES_Q1_1998" 442.2 KB 13218 rows
      . . imported "SH_TESTE"."SALES":"SALES_Q3_1998" 512.7 KB 15349 rows
      . . imported "SH_TESTE"."SALES":"SALES_Q2_1998" 359.0 KB 10669 rows
      . . imported "SH_TESTE"."FWEEK_PSCAT_SALES_MV" 131.1 KB 3406 rows
      . . imported "SH_TESTE"."PROMOTIONS" 24.66 KB 167 rows
      . . imported "SH_TESTE"."TIMES" 130.2 KB 574 rows
      . . imported "SH_TESTE"."COSTS":"COSTS_Q4_2001" 87.75 KB 2697 rows
      . . imported "SH_TESTE"."COSTS":"COSTS_Q1_1999" 59.41 KB 1762 rows
      . . imported "SH_TESTE"."COSTS":"COSTS_Q1_2001" 72.94 KB 2203 rows
      . . imported "SH_TESTE"."COSTS":"COSTS_Q2_2001" 60.59 KB 1793 rows
      . . imported "SH_TESTE"."COSTS":"COSTS_Q3_2001" 74.60 KB 2259 rows
      . . imported "SH_TESTE"."COSTS":"COSTS_Q1_1998" 47.25 KB 1356 rows
      . . imported "SH_TESTE"."COSTS":"COSTS_Q1_2000" 41.74 KB 1169 rows
      . . imported "SH_TESTE"."COSTS":"COSTS_Q2_1998" 27.42 KB 692 rows
      . . imported "SH_TESTE"."COSTS":"COSTS_Q2_1999" 44.67 KB 1269 rows
      . . imported "SH_TESTE"."COSTS":"COSTS_Q2_2000" 39.98 KB 1110 rows
      . . imported "SH_TESTE"."COSTS":"COSTS_Q3_1998" 44.03 KB 1250 rows
      . . imported "SH_TESTE"."COSTS":"COSTS_Q3_1999" 47.19 KB 1353 rows
      . . imported "SH_TESTE"."COSTS":"COSTS_Q3_2000" 48.67 KB 1399 rows
      . . imported "SH_TESTE"."COSTS":"COSTS_Q4_1998" 47.65 KB 1369 rows
      . . imported "SH_TESTE"."COSTS":"COSTS_Q4_1999" 53.85 KB 1576 rows
      . . imported "SH_TESTE"."COSTS":"COSTS_Q4_2000" 52.44 KB 1525 rows
      . . imported "SH_TESTE"."CAL_MONTH_SALES_MV" 5.476 KB 13 rows
      . . imported "SH_TESTE"."CHANNELS" 6.515 KB 1 rows
      . . imported "SH_TESTE"."COUNTRIES" 8.226 KB 7 rows
      . . imported "SH_TESTE"."PRODUCTS" 15.93 KB 24 rows
      . . imported "SH_TESTE"."COSTS":"COSTS_1995" 0 KB 0 rows
      . . imported "SH_TESTE"."COSTS":"COSTS_1996" 0 KB 0 rows
      . . imported "SH_TESTE"."COSTS":"COSTS_H1_1997" 0 KB 0 rows
      . . imported "SH_TESTE"."COSTS":"COSTS_H2_1997" 0 KB 0 rows
      . . imported "SH_TESTE"."COSTS":"COSTS_Q1_2002" 0 KB 0 rows
      . . imported "SH_TESTE"."COSTS":"COSTS_Q1_2003" 0 KB 0 rows
      . . imported "SH_TESTE"."COSTS":"COSTS_Q2_2002" 0 KB 0 rows
      . . imported "SH_TESTE"."COSTS":"COSTS_Q2_2003" 0 KB 0 rows
      . . imported "SH_TESTE"."COSTS":"COSTS_Q3_2002" 0 KB 0 rows
      . . imported "SH_TESTE"."COSTS":"COSTS_Q3_2003" 0 KB 0 rows
      . . imported "SH_TESTE"."COSTS":"COSTS_Q4_2002" 0 KB 0 rows
      . . imported "SH_TESTE"."COSTS":"COSTS_Q4_2003" 0 KB 0 rows
      . . imported "SH_TESTE"."MVIEW$_EXCEPTIONS" 0 KB 0 rows
      . . imported "SH_TESTE"."SALES":"SALES_1995" 0 KB 0 rows
      . . imported "SH_TESTE"."SALES":"SALES_1996" 0 KB 0 rows
      . . imported "SH_TESTE"."SALES":"SALES_H1_1997" 0 KB 0 rows
      . . imported "SH_TESTE"."SALES":"SALES_H2_1997" 0 KB 0 rows
      . . imported "SH_TESTE"."SALES":"SALES_Q1_2002" 0 KB 0 rows
      . . imported "SH_TESTE"."SALES":"SALES_Q1_2003" 0 KB 0 rows
      . . imported "SH_TESTE"."SALES":"SALES_Q2_2002" 0 KB 0 rows
      . . imported "SH_TESTE"."SALES":"SALES_Q2_2003" 0 KB 0 rows
      . . imported "SH_TESTE"."SALES":"SALES_Q3_2002" 0 KB 0 rows
      . . imported "SH_TESTE"."SALES":"SALES_Q3_2003" 0 KB 0 rows
      . . imported "SH_TESTE"."SALES":"SALES_Q4_2002" 0 KB 0 rows
      . . imported "SH_TESTE"."SALES":"SALES_Q4_2003" 0 KB 0 rows
      Processing object type SCHEMA_EXPORT/TABLE/GRANT/OWNER_GRANT/OBJECT_GRANT
      Processing object type SCHEMA_EXPORT/TABLE/INDEX/INDEX
      Processing object type SCHEMA_EXPORT/TABLE/CONSTRAINT/CONSTRAINT
      Processing object type SCHEMA_EXPORT/TABLE/INDEX/STATISTICS/INDEX_STATISTICS
      Processing object type SCHEMA_EXPORT/TABLE/COMMENT
      Processing object type SCHEMA_EXPORT/VIEW/VIEW
      Processing object type SCHEMA_EXPORT/TABLE/CONSTRAINT/REF_CONSTRAINT
      Processing object type SCHEMA_EXPORT/TABLE/INDEX/FUNCTIONAL_AND_BITMAP/INDEX
      Processing object type SCHEMA_EXPORT/TABLE/INDEX/STATISTICS/FUNCTIONAL_AND_BITMAP/INDEX_STATISTICS
      Processing object type SCHEMA_EXPORT/TABLE/STATISTICS/TABLE_STATISTICS
      Processing object type SCHEMA_EXPORT/TABLE/INDEX/DOMAIN_INDEX/INDEX
      Processing object type SCHEMA_EXPORT/MATERIALIZED_VIEW
      Processing object type SCHEMA_EXPORT/DIMENSION
      Job "SYS"."SYS_IMPORT_FULL_01" completed with 1 error(s) at 02:49:15

      [oracle@odbsrv02 ~]$




      4. Comparar objetos dos esquemas

      Concluida a copia precisamos verificar se todos os objetos foram copiados:


      SQL> select owner, object_type, count(1) Qtde
      2 from dba_objects
      3 where owner in ('SH','SH_TESTE')
      4 group by owner, object_type
      5 order by 2;

      OWNER OBJECT_TYPE QTDE
      ------------------------------ ------------------- ----------
      SH DIMENSION 5
      SH_TESTE DIMENSION 5
      SH_TESTE INDEX 28
      SH INDEX 28
      SH_TESTE INDEX PARTITION 168
      SH INDEX PARTITION 168
      SH_TESTE LOB 2
      SH LOB 2
      SH MATERIALIZED VIEW 2
      SH_TESTE MATERIALIZED VIEW 2
      SH_TESTE TABLE 17
      SH TABLE 17
      SH_TESTE TABLE PARTITION 56
      SH TABLE PARTITION 56
      SH VIEW 1
      SH_TESTE VIEW 1

      16 linhas selecionadas.

      SQL>






      5. Comparar tamanhos dos esquemas

      Agora vamos verificar se o DataPump fez o trabalho dele corretamente, vamos comparar a quantidade de espaço utilizada pelo esquema SH e SH_TESTE:




      SQL> select owner, sum(bytes)/1024 "Tamanho KB"
      2 from dba_segments
      3 where owner in ('SH','SH_TESTE')
      4 group by owner;

      OWNER Tamanho KB
      ------------------------------ ----------
      SH_TESTE 35712
      SH 81984

      SQL>





      Obs: A redução do espaço utilizado pelo esquema não é um calculo exato devido
      a forma como o Oracle trabalha com segmentos de dados e extensões.

      quarta-feira, 23 de junho de 2010

      Reorganizando uma tabela sem parar as atividades dos usuários

      Objetivo:



      Precisamos reorganizar uma tabela que é acessada durante 24 horas por dia e sete dias na semana, nessa situação uma alternativa seria utilizar a package Online Redefinition (DBMS_REDEFINITION).

      Ambiente:

      SO: Linux 2.6.9-67.0.0.0.1.EL i686 i386 GNU/Linux
      Base: Oracle Database 10.2.0.5.0 com archive log habilitado


      Overview:

      Oracle Online Redefinition permite alterações na estrutura das tabelas enquanto os usuários estão lendo e gravando nessas tabelas. Assegurando assim a continuidade do serviço sem impacto nas atividades dos usuários finais, não há restrição quanto tempo necessário para reorganização da tabela. Quando a reorganização estiver concluída, a mudança para a nova tabela reorganizada é automática e completamente transparente para os usuários da aplicação.


      Tópicos:
      1. Setup;
      2. Verificar se a tabela pode ser reorganizada online;
      3. Verificar tamanho da tabela;
      4. Criar a tabela provisória;
      5. Iniciar a reorganização;
      6. Simular uma modificação do usuário;
      7. Copiar objetos dependentes da tabela;
      8. Simular commit da transação do usuário;
      9. Sincronizar tabela provisória com a original;
      10. Disponibilizar a tabela provisória como original;
      11. Verificar se a tabela foi reorganizada;


      1. Setup




      SQL> create tablespace appl01 datafile '/u01/app/oracle/product/10.2.0/oradata/db_1/lab1/appl01.dbf' size 100 M;

      Tablespace criado.

      SQL> create user appl01 identified by oracle default tablespace appl01 temporary tablespace temp;

      Usuário criado.

      SQL> grant connect to appl01;

      Concessão bem-sucedida.

      SQL> grant unlimited tablespace to appl01;

      Concessão bem-sucedida.

      SQL> grant select any dictionary to appl01;

      Concessão bem-sucedida.

      SQL> grant resource to appl01;

      Concessão bem-sucedida.

      SQL> conn appl01/oracle@lab1;
      Conectado.

      SQL>
      SQL> drop table TEST_REORG CASCADE CONSTRAINTS PURGE;

      Tabela eliminada.

      SQL> create table test_reorg
      2 ( regid number not null
      3 ,nome varchar2(30) not null
      4 ,endereco varchar2(30) not null
      5 ,data date not null
      6 ,comentario varchar2(100)
      7 ,constraint test_reorg_pk primary key (regid)
      8 );

      Tabela criada.

      SQL>
      SQL>
      SQL> create index test_reorg_idx on test_reorg(nome);

      Índice criado.

      SQL> select object_name, object_type from dba_objects where owner = 'APPL01';

      OBJECT_NAME OBJECT_TYPE
      -------------------- -------------------
      DB_DICT TABLE
      TEST_REORG TABLE
      TEST_REORG_PK INDEX
      TEST_REORG_IDX INDEX
      DB_OBJETOS TABLE

      SQL> declare
      2 id number;
      3 x varchar2(30);
      4 y varchar2(30);
      5 c varchar2(100);
      6 begin
      7 x := '123456789+123456789+1234567890';
      8 y := 'Abcde fghi jklmn opqrs tuvxz99';
      9 id := 1;
      10 c := 'black Abcde fghi jklmn opqrs tuvxz99 123456789+123456789+1234567890 black Abcde fghi jklmn opqrs';
      11
      12 for i in 1..100000 loop
      13
      14 insert into test_reorg values (id, x, y, sysdate, c);
      15 id := id + 1;
      16
      17 end loop;
      18 end;
      19 /

      Procedimento PL/SQL concluído com sucesso.

      SQL>
      SQL> commit;

      Validação completa.

      SQL>
      SQL>
      SQL> delete from test_reorg where regid > 5000 and regid <> commit;

      Validação completa.

      SQL> delete from test_reorg where regid > 25000 and regid <> commit;

      Validação completa.

      SQL> delete from test_reorg where regid > 45000 and regid <> commit;

      Validação completa.

      SQL> delete from test_reorg where regid > 75000 and regid <> commit;

      Validação completa.

      SQL>
      SQL>





      2. Verificar se a tabela pode ser reorganizada online

      Para reorganizar uma tabela, precisamos verificar se a mesma é candidata a uma redefinição online:


      SQL> conn system/oracle@lab1;
      Conectado.
      SQL> BEGIN
      2 DBMS_REDEFINITION.CAN_REDEF_TABLE('APPL01',' TEST_REORG',dbms_redefinition.cons_use_pk);
      3 END;
      4 /

      Procedimento PL/SQL concluído com sucesso.

      SQL>
      SQL>


      3. Verificar tamanho da tabela

      Vamos verificar o tamanho da tabela antes da reorganização para comparar com o tamanho após a reorganização:



      SQL> select segment_name, owner, bytes/1024 "Tam. KB" from dba_segments where segment_name = 'TEST_REORG';

      SEGMENT_NAME OWNER Tam. KB
      -------------------- ------------ ----------
      TEST_REORG APPL01 20480

      SQL>


      4. Criar a tabela provisória




      SQL> conn appl01/oracle@lab1;
      Conectado.
      SQL> create table test_reorg_prov
      2 ( regid number
      3 ,nome varchar2(30)
      4 ,endereco varchar2(30)
      5 ,data date
      6 ,comentario varchar2(100)
      7 );

      Tabela criada.

      SQL>


      5. Iniciar a reorganização

      Agora vamos iniciar o processo de reorganização e definir os mapeamentos de coluna para as colunas antigas e novas:


      SQL> conn system/oracle@lab1;

      Conectado.

      SQL> BEGIN

      2 DBMS_REDEFINITION.START_REDEF_TABLE('APPL01', 'TEST_REORG','TEST_REORG_PROV',
      3 'regid regid, nome nome, endereco endereco, data data, comentario comentario' ,
      4 dbms_redefinition.cons_use_pk);
      5 END;
      6 /

      Procedimento PL/SQL concluído com sucesso.

      SQL>



      6. Simular uma modificação do usuário

      Enquanto a reorganização está executando vamos iniciar outra sessão onde faremos alterações na tabela TEST_REORG:




      SQL> conn appl01/oracle@lab1;
      Conectado.
      SQL> UPDATE TEST_REORG set endereco = 'valteraquino.blogspot.com' where regid=20000;

      1 linha atualizada.

      SQL>


      Obs: Não execute o commit nesse momento.

      7. Copiar objetos dependentes da tabela

      Em seguida retornando para a primeira sessão, vamos criar automaticamente todos os triggers, índices e constraints na tabela provisória:






      SQL> set serveroutput on
      SQL> DECLARE
      2 num_erros int;
      3 BEGIN
      4 DBMS_REDEFINITION.COPY_TABLE_DEPENDENTS
      5 ('APPL01', 'TEST_REORG','TEST_REORG_PROV',1, TRUE, TRUE, TRUE, FALSE, num_erros);
      6 DBMS_OUTPUT.put_line ('Numero de erros durante a copia do obj.dependentes: ' num_erros );
      7 END;
      8 /
      Numero de erros durante a copia do obj.dependentes: 0

      Procedimento PL/SQL concluído com sucesso.

      SQL>


      8. Simular commit da transação do usuário

      Agora vamos retornar para a sessão onde executamos o UPDATE na tabela e vamos confirmar a mudança de endereço e fechar a sessão:





      SQL> commit;

      Validação completa.

      SQL> exit



      9. Sincronizar tabela provisória com a original

      Agora podemos sincronizar a tabela provisória para que ela inclua a alteração no endereço que fizemos:




      SQL> BEGIN
      2 DBMS_REDEFINITION.SYNC_INTERIM_TABLE('APPL01', 'TEST_REORG', 'TEST_REORG_PROV');
      3 END;
      4 /

      Procedimento PL/SQL concluído com sucesso.

      SQL>


      10. Disponibilizar a tabela provisória como original

      Agora vamos encerrar a reorganização e as tabelas serão invertidas automaticamente:



      SQL> BEGIN
      2 DBMS_REDEFINITION.FINISH_REDEF_TABLE('APPL01', 'TEST_REORG', 'TEST_REORG_PROV');
      3 END;
      4 /

      Procedimento PL/SQL concluído com sucesso.

      SQL> DROP TABLE APPL01.TEST_REORG_PROV CASCADE CONSTRAINTS PURGE;

      Tabela eliminada.

      SQL>



      11. Verificar se a tabela foi reorganizada

      Vamos verificar o tamanho atual da tabela 'TEST_REORG' e comparar com o tamanho antes do processo de reorganização:



      SQL> select segment_name, owner, bytes/1024 "Tam. KB" from dba_segments where segment_name = 'TEST_REORG';

      SEGMENT_NAME OWNER Tam. KB
      -------------------- ------------ ----------
      TEST_REORG APPL01 14336

      SQL>
      SQL> select endereco from APPL01.TEST_REORG where regid in (19999,20000,20001);

      ENDERECO
      ------------------------------
      Abcde fghi jklmn opqrs tuvxz99
      valteraquino.blogspot.com
      Abcde fghi jklmn opqrs tuvxz99

      SQL>
      SQL> select object_name, object_type from dba_objects where owner = 'APPL01';

      OBJECT_NAME OBJECT_TYPE
      -------------------- -------------------
      DB_DICT TABLE
      DB_OBJETOS TABLE
      TEST_REORG_PK INDEX
      TEST_REORG_IDX INDEX
      TEST_REORG TABLE

      SQL>