Pages

Tuesday, July 4, 2017

SQL*Loader is failing with error: ORA-01653: unable to extend table by 128 in tablespace

===============================
General
===============================
SQL*Loader is failing with error: ORA-01653: unable to extend table 
CUSTOMER_REPORTS.CUSTOMER_USAGE_DAILY by 128 in tablespace DWH_TABLE

This is strange, because when checking used space inside tablespace DWH_TABLE, there is plenty of space. 
What could be wrong?

===============================
Evidence from SQL*Loader
===============================

Table CUSTOMER_USAGE_DAILY, loaded from every logical record.
Insert option in effect for this table: APPEND
TRAILING NULLCOLS option in effect

   Column Name                  Position   Len  Term Encl Datatype
------------------------------ ---------- ----- ---- ---- ---------------------
KEY1                                FIRST     *   ,       CHARACTER            
DATE_OF_RECORD                       NEXT     *   ,       CHARACTER            
NETWORK_ID                           NEXT     *   ,       CHARACTER            
IMSI                                 NEXT     *   ,       CHARACTER            
VOICE_MO                             NEXT     *   ,       CHARACTER            
VOICE_MT                             NEXT     *   ,       CHARACTER            
DATA                                 NEXT     *   ,       CHARACTER            
SMS_MO                               NEXT     *   ,       CHARACTER            
TS_LAST_MODIFIED                                          SYSDATE

ORA-01653: unable to extend table CUSTOMER_REPORTS.CUSTOMER_USAGE_DAILY by 128 in tablespace DWH_TABLE

===============================
Checking current status
===============================

Checking usage in DBA_DATA_FILES

SET LINESIZE 140
SET PAGESIZE 200
COL tablespace_name FOR A30
COL file_name FOR A60
COL Mb FOR 9999999999999
COL MAX_MB FOR 9999999999999

SELECT tablespace_name, 
       file_name, 
       ROUND(bytes/1024/1024) AS Mb, ROUND(maxbytes/1024/1024) AS MAX_MB
  FROM DBA_DATA_FILES
ORDER BY tablespace_name, file_name;  

TABLESPACE_NAME FILE_NAME                                         MB     MAX_MB
--------------- -------------------------------------------- ------- ----------
DWH_INDEX       /oracle_db/db1/db_igt/ora_dwh_index_01.dbf      2200       6000
DWH_TABLE       /oracle_db/db1/db_igt/ora_dwh_table_01.dbf     12000      12000
GIN             /oracle_db/db1/db_igt/ora_gin_01.dbf             500       6000
GININDEX        /oracle_db/db1/db_igt/ora_ginindex_01.dbf        200       3000
IGT_INDEX       /oracle_db/db1/db_igt/ora_igt_index_01.dbf      2900      30000
IGT_TABLE       /oracle_db/db1/db_igt/ora_igt_table_01.dbf      2300      30000
IGT_TABLE       /oracle_db/db1/db_igt/ora_igt_table_02.dbf       600      30000
IGT_TABLE       /oracle_db/db1/db_igt/ora_igt_table_03.dbf       400      30000
SYSAUX          /oracle_db/db1/db_igt/ora_sysaux_01.dbf          900       2000
SYSTEM          /oracle_db/db1/db_igt/ora_system_01.dbf          500       2000
UNDOTBS         /oracle_db/db1/db_igt/ora_undotbs_01.dbf        6000       6000
WORKAREA        /oracle_db/db1/db_igt/ora_workarea_01.dbf        300       3000



SET LINESIZE 120
SET PAGESIZE 200

SELECT TABLESPACE_NAME, 
       (MAX(MAX_SPACE)-MAX(USED_SPACE)) AS DBA_FREE_SPACE_MB,
       MAX(USED_SPACE) AS USED_SPACE_MB, 
       MAX(MAX_SPACE) AS MAX_SPACE_MB, 
       ROUND(((MAX(MAX_SPACE)-MAX(USED_SPACE))/MAX(MAX_SPACE))*100) as FREE_PCT, 
       CASE WHEN (ROUND(( (MAX(MAX_SPACE)-MAX(USED_SPACE)  ) /MAX(MAX_SPACE) ) *100)<15)  THEN 'Y' ELSE 'N' END AS ADD_MORE_SPACE 
       FROM ( 
          SELECT tablespace_name,  
         ROUND(SUM(bytes)/1024/2014) AS FREE_SPACE, 
               0 AS MAX_SPACE, 
            0 AS USED_SPACE   
            FROM DBA_FREE_SPACE
           WHERE 1=1
                 --AND tablespace_name LIKE '%IGT%' OR tablespace_name LIKE '%DWH%' OR tablespace_name LIKE '%REPORTS%' OR tablespace_name = 'SYSTEM'  OR tablespace_name = 'SYSAUX' 
           GROUP BY tablespace_name  
           UNION ALL 
          SELECT tablespace_name, 
         0 AS FREE_SPACE, 
           ROUND( SUM(CASE WHEN (bytes>maxbytes)  THEN bytes ELSE maxbytes END)/1024/1024) AS MAX_SPACE, 
                 0 AS USED_SPACE 
            FROM DBA_DATA_FILES
           WHERE 1=1
                 --AND tablespace_name LIKE '%IGT%' OR tablespace_name LIKE '%DWH%' OR tablespace_name LIKE '%REPORTS%' OR tablespace_name = 'SYSTEM'  OR tablespace_name = 'SYSAUX' 
           GROUP BY tablespace_name 
           UNION ALL 
           SELECT tablespace_name, 
                  0 AS FREE_SPACE, 
                  0 AS MAX_SPACE, 
                  ROUND(SUM(bytes/1024/1024)) AS USED_SPACE 
             FROM DBA_SEGMENTS
            WHERE 1=1
            --AND tablespace_name LIKE '%IGT%' OR tablespace_name LIKE '%DWH%' OR                     tablespace_name LIKE '%REPORTS%' OR tablespace_name = 'SYSTEM'                     OR tablespace_name = 'SYSAUX' 
            GROUP BY tablespace_name 
       ) 
GROUP BY tablespace_name;

TABLESPACE_NAME DBA_FREE_SPACE_MB USED_SPACE_MB MAX_SPACE_MB   FREE_PCT ADD_SPACE
--------------- ----------------- ------------- ------------ ---------- ---------
DWH_INDEX                    3935          2065         6000         66 N
SYSAUX                       1462           538         2000         73 N
IGT_TABLE                   86981          3019        90000         97 N
GININDEX                     3000             0         3000        100 N
UNDOTBS                      5834           166         6000         97 N
SYSTEM                       1593           407         2000         80 N
WORKAREA                     3000             0         3000        100 N
GIN                          6000             0         6000        100 N
IGT_INDEX                   27319          2681        30000         91 N
DWH_TABLE                   10234          1766        12000         85 N


Checking DBA_TABLESPACE_USAGE_METRICS

SELECT name, value from  V$PARAMETER WHERE name = 'db_block_size';

NAME              VALUE
----------------  ----------
db_block_size     8192

SELECT tablespace_name, 
       ROUND(used_space*8192/1024/1024) AS USED_MB,
       ROUND(tablespace_size*8192/1024/1024) AS MAX_MB, 
       ROUND(used_percent) AS USED_PCT , 
       100-ROUND(used_percent) AS FREE_PCT
 FROM  DBA_TABLESPACE_USAGE_METRICS
ORDER BY tablespace_name;


TABLESPACE_NAME                   USED_MB         MAX_MB   USED_PCT   FREE_PCT
------------------------------ ---------- -------------- ---------- ----------
DWH_INDEX                            2066           6000         34         66
DWH_TABLE                            1767          12000         15         85
GIN                                     1           6000          0        100
GININDEX                                1           3000          0        100
IGT_INDEX                            2682          30000          9         91
IGT_TABLE                            3022          90000          3         97
SYSAUX                                539           2000         27         73
SYSTEM                                408           2000         20         80
TEMPORARY                               0          12000          0        100
UNDOTBS                                78           6000          1         99
WORKAREA                                1           3000          0        100

Checking top DBA_SEGMENTS on DWH_TABLE tablespace, CUSTOMER_USAGE_DAILY is not one of the top heavy segments. 

OWNER            TABLESPACE_NAME SEGMENT_NAME                USED_MB
---------------- --------------- -------------------------- --------
CUSTOMER_REPORTS DWH_TABLE       FACT_ROAMER_CAMPAIGNS          699
CUSTOMER_REPORTS DWH_TABLE       AGG_ROAMING_PROF_1M            524
CUSTOMER_REPORTS DWH_TABLE       FACT_ROAMER_SCENARIO           146
CUSTOMER_REPORTS DWH_TABLE       FACT_ROAMER_USAGE               45
CUSTOMER_REPORTS DWH_TABLE       AGG_ROAMING_PROF_12M            32
CUSTOMER_REPORTS DWH_TABLE       AGG_ROAMING_PROF_YTD            31
CUSTOMER_REPORTS DWH_TABLE       AGG_CAMPAIGN_SENT_DAILY         29
CUSTOMER_REPORTS DWH_TABLE       AUDIT_TRACE                     26
CUSTOMER_REPORTS DWH_TABLE       AGG_SCENARIO_6M                 23
CUSTOMER_REPORTS DWH_TABLE       AGG_SCENARIO_CN_18M             23



SELECT COUNT(*) FROM DBA_EXTENTS WHERE TABLESPACE_NAME = 'DWH_TABLE';

  COUNT(*)
----------
     13753

Checking for pct_increase value, there is no fixed value set. 
So Oracle is using it internal defaults.

SELECT table_name, PCT_INCREASE FROM DBA_TABLES WHERE table_name = 'CUSTOMER_USAGE_DAILY';

TABLE_NAME                     PCT_INCREASE
------------------------------ ------------
SFI_CUSTOMER_USAGE_DAILY


SELECT TABLESPACE_NAME, PCT_INCREASE FROM DBA_TABLESPACES WHERE TABLESPACE_NAME = 'DWH_TABLE';

TABLESPACE_NAME PCT_INCREASE
--------------- ------------
DWH_TABLE


Checking CUSTOMER_USAGE_DAILY extents.

SELECT OWNER, SEGMENT_NAME, TABLESPACE_NAME AS TBS_NAME, EXTENT_ID, BLOCK_ID , BYTES 
  FROM DBA_EXTENTS 
 WHERE SEGMENT_NAME = 'CUSTOMER_USAGE_DAILY';

OWNER            SEGMENT_NAME         TBS_NAME  EXTENT_ID   BLOCK_ID      BYTES
---------------- -------------------- --------- ---------- ---------- ----------
CUSTOMER_REPORTS CUSTOMER_USAGE_DAILY DWH_TABLE          0       3384      65536
CUSTOMER_REPORTS CUSTOMER_USAGE_DAILY DWH_TABLE          1    1523848      65536
CUSTOMER_REPORTS CUSTOMER_USAGE_DAILY DWH_TABLE          2    1523856      65536
CUSTOMER_REPORTS CUSTOMER_USAGE_DAILY DWH_TABLE          3    1523864      65536
CUSTOMER_REPORTS CUSTOMER_USAGE_DAILY DWH_TABLE          4    1523872      65536
CUSTOMER_REPORTS CUSTOMER_USAGE_DAILY DWH_TABLE          5    1523880      65536
CUSTOMER_REPORTS CUSTOMER_USAGE_DAILY DWH_TABLE          6    1523888      65536
CUSTOMER_REPORTS CUSTOMER_USAGE_DAILY DWH_TABLE          7    1523896      65536
CUSTOMER_REPORTS CUSTOMER_USAGE_DAILY DWH_TABLE          8    1523904      65536
CUSTOMER_REPORTS CUSTOMER_USAGE_DAILY DWH_TABLE          9    1523912      65536
CUSTOMER_REPORTS CUSTOMER_USAGE_DAILY DWH_TABLE         10    1523920      65536
CUSTOMER_REPORTS CUSTOMER_USAGE_DAILY DWH_TABLE         11    1523928      65536
CUSTOMER_REPORTS CUSTOMER_USAGE_DAILY DWH_TABLE         12    1523936      65536
CUSTOMER_REPORTS CUSTOMER_USAGE_DAILY DWH_TABLE         13    1523944      65536
CUSTOMER_REPORTS CUSTOMER_USAGE_DAILY DWH_TABLE         14    1523952      65536
CUSTOMER_REPORTS CUSTOMER_USAGE_DAILY DWH_TABLE         15    1523960      65536
CUSTOMER_REPORTS CUSTOMER_USAGE_DAILY DWH_TABLE         16     217088    1048576
CUSTOMER_REPORTS CUSTOMER_USAGE_DAILY DWH_TABLE         17     217216    1048576
CUSTOMER_REPORTS CUSTOMER_USAGE_DAILY DWH_TABLE         18    1536000    1048576


Checking DBA_RECYCLEBIN contents.
SELECT COUNT(*) FROM DBA_RECYCLEBIN;
COUNT(*)
----------
0
===============================
Oracle Metalink
===============================

Per Oracle Metalink 
SQL*Loader Fils on Load with ORA-1653 (Doc ID 205296.1)
Fact(s)
~~~~~~~~
Oracle RDBMS Server
Oracle SQL*Loader


Symptom(s)
~~~~~~~~~~
SQL*Loader fails on small load with 
  ORA-1653: unable to extend table <schema>.<table_name> by <size> in tablespace <tbs>

Loads on other tables work without problem. There is sufficient space within the
tablespace to accomodate the load.


Change(s)
~~~~~~~~~~
N/A


Cause
~~~~~~~
NEXT extent requested by the table is larger than the largest available extent
within the tablespace.

It is possible that PCTINCREASE is set to some non-zero value and each request
for extents getslarger and larger.


Fix
~~~~
Possible resolutions include:

1. Coalesce the tablespace:

ALTER TABLESPACE <TBS> COALESCE;

2. Add a datafile to the tablespace:

ALTER TABLESPACE <TBS> ADD DATAFILE 'PATH/NAME' SIZE <SIZE>;

3. Alter the NEXT attribute for the table that you are trying to load into
   to a value smaller than the largest available free extent in the tablespace:

ALTER TABLE <TABLE_NAME> STORAGE (NEXT <SIZE M/K>);
   where M/K = Megabytes or Kilobytes.

   To get the Next extent that will be requested by the table do:
   
SELECT TO_CHAR (NEXT_EXTENT,'999G999G999G999D00')||' MB' AS "NEXT"
  FROM   USER_TABLES 
 WHERE  TABLE_NAME = '<TABLE_NAME>';


   To get the largest free extent available in the tablespace run:
   
SELECT TABLESPACE_NAME,
       TO_CHAR (MAX(BYTES),'999G999G999G999D00')||' MB' AS "LARGEST FREE EXTENT"
  FROM   DBA_FREE_SPACE
 WHERE  TABLESPACE_NAME = '<TBS>'
 GROUP  BY TABLESPACE_NAME;



===============================
Add more space, to fix the error
===============================
D. In order to resolve the issue, additional 2Gb of space were allocated to /oracle_db/db1/db_igt/ora_dwh_table_01.dbf datafile.

ALTER DATABASE DATAFILE '/oracle_db/db1/db_igt/ora_dwh_table_01.dbf' AUTOEXTEND OF MAXSIZE 14000M;

Now when running the SQL*Load, the process completes without error.

Checking usage in DBA_DATA_FILES, the above datafile has increase by 200M, although there is plenty of free space!!

DBA_DATA_FILES
TABLESPACE_NAME FILE_NAME                                         MB     MAX_MB
--------------- -------------------------------------------- ------- ----------
DWH_INDEX       /oracle_db/db1/db_igt/ora_dwh_index_01.dbf      2200       6000
DWH_TABLE       /oracle_db/db1/db_igt/ora_dwh_table_01.dbf     12200      14000
GIN             /oracle_db/db1/db_igt/ora_gin_01.dbf             500       6000
GININDEX        /oracle_db/db1/db_igt/ora_ginindex_01.dbf        200       3000
IGT_INDEX       /oracle_db/db1/db_igt/ora_igt_index_01.dbf      2900      30000
IGT_TABLE       /oracle_db/db1/db_igt/ora_igt_table_01.dbf      2300      30000
IGT_TABLE       /oracle_db/db1/db_igt/ora_igt_table_02.dbf       600      30000
IGT_TABLE       /oracle_db/db1/db_igt/ora_igt_table_03.dbf       400      30000
SYSAUX          /oracle_db/db1/db_igt/ora_sysaux_01.dbf          900       2000
SYSTEM          /oracle_db/db1/db_igt/ora_system_01.dbf          500       2000
UNDOTBS         /oracle_db/db1/db_igt/ora_undotbs_01.dbf        6000       6000
WORKAREA        /oracle_db/db1/db_igt/ora_workarea_01.dbf        300       3000


DBA_TABLESPACES
TABLESPACE_NAME DBA_FREE_SPACE_MB USED_SPACE_MB MAX_SPACE_MB   FREE_PCT ADD_SPACE
--------------- ----------------- ------------- ------------ ---------- ---------
DWH_INDEX                    3935          2065         6000         66 N
SYSAUX                       1462           538         2000         73 N
IGT_TABLE                   86981          3019        90000         97 N
GININDEX                     3000             0         3000        100 N
UNDOTBS                      5834           166         6000         97 N
SYSTEM                       1593           407         2000         80 N
WORKAREA                     3000             0         3000        100 N
GIN                          6000             0         6000        100 N
IGT_INDEX                   27319          2681        30000         91 N
DWH_TABLE                   12234          1766        14000         87 N


===============================
Conclusion
===============================
When checking all the above information, two findings stand out.

A. There are 13753 extents in tablespace DWH_TRACE.
This Tablespace size is 12000 Mb.
That means that many of the extents are less than 1Mb.


B. Before addition of 2Gb, the data from DBA_DATA_FILES shows:
DWH_TABLE       /oracle_db/db1/db_igt/ora_dwh_table_01.dbf     12000      12000
So the DWH_TRACE was populated in the past with segments, which are now deleted.

C. The next extent of table CUSTOMER_USAGE_DAILY is 1048576 bytes.
   So when loading data via SQL*Loader, the next allocated extent should be of size 1Mb.

D. If extent of size 1Mb cannot be allocated, an error ORA-01653: unable to extend table by 128 in tablespace would be thrown.

E. After adding additional space to datafile, the DBA_DATA_FILES.bytes value has increased from 12000M to 12200MB.

This is surprising!

Tablespace DWH_TABLE is only 13% used, but still the datafile has increased by 200M.

SQL*Loader is using Direct Access method data load.

It seems that the SQL*Loader process cannot re-use existing free extents withing the tablespace, and is allocating new space.

===============================
Solution
===============================
The long term solution would be to move table CUSTOMER_USAGE_DAILY table to a dedicated tablespace.
That way, this tablespace can be maintained without affecting other tables in the application.
ALTER TABLE CUSTOMER_USAGE_DAILY MOVE TABLESPACE NEW_TABLESPACE;



View Indexes Fragmentation.
Collect Statistics for Index Fragmentation:
as sys
GRANT SELECT ON index_stats to COL_CLARO_SPXQQ

as user
CREATE TABLE frag_stats_all AS SELECT * FROM index_stats WHERE 1=2;

DECLARE
    cursor ind_cur IS
       select owner , index_name
       from   dba_indexes where tablespace_name='IGT_INDEX' AND owner = 'COL_CLARO_SPXQQ'
       order by owner , index_name; 
    l_sql_text         varchar2(1000);
BEGIN    
    for ind_rec in ind_cur LOOP
  l_sql_text := 'analyze index '||ind_rec.owner||'.'||ind_rec.index_name||' validate structure';
  execute immediate l_sql_text;
      l_sql_text := 'insert into frag_stats_all select * from index_stats';
      execute immediate l_sql_text;
    end loop;
    commit;
END;
/

To See results: 
SELECT name,height,lf_rows,lf_blks,lf_rows_len,lf_blk_len,del_lf_rows,distinct_keys,used_space/1024/1024 used_space
FROM INDEX_STATS
SELECT * FROM dba_indexes
SELECT USER FROM DUAL

Wednesday, June 28, 2017

"ORA-00900: invalid SQL statement" and "ORA-02064 Distributed operation not supported" Errors When calling to Remote PL/SQL Procedure

================================
General
================================
A. When calling to a remote PL/SQL procedure from sqlplus - all works fine,
But when calling to the same remote PL/SQL procedure from PL/SQL code, an ORA-00900: invalid SQL statement error is thrown.

B. When calling a PL/SQL directly, all works fine, but when calling same procedure vi db link, it fails with ORA-02064 Distributed operation not supported

Why is that?

================================
ORA-00900 Example
================================
In this example, a DB_LINK named KUKU is created to the remote database.

CREATE DATABASE LINK KUKU CONNECT TO REMOTE_USER IDENTIFIED BY REMOTE_PASSWORD USING 'REMOTE_HOST_NAME';

In the remote database, a getDate Procedure in Package PKG_TEST should be activated.

In sqlplus
From sqlplus, any of these versions work:
EXEC PKG_TEST.getDate@KUKU;
EXEC REMOTE_USER.PKG_TEST.getDate@KUKU;

When creating a Synonym, it can be also used, to simplify code.

CREATE SYNONYM REMOTE_PKG FOR REMOTE_USER.PKG_TEST@KUKU

SELECT * FROM USER_SYNONYMS WHERE synonym_name = 'KUKU'

SYNONYM_NAME        TABLE_OWNER      TABLE_NAME      DB_LINK
------------------- ---------------- --------------- ---------------
REMOTE_PKG          REMOTE_USER      PKG_TEST        KUKU

So in sqlplus, it would be:
EXEC REMOTE_PKG.getDate;

In PL/SQL
When activating the same code in PL/SQL it MUST be inside a BEGIN END block.
Any other syntax, such as EXECUTE IMMEDIATE <sql_string> would fail with "ORA-00900: invalid SQL statement".

This is the correct code:

BEGIN
  PKG_TEST.getDate;
  EXCEPTION
    WHEN OTHERS THEN
      WRITE_LOG(v_module_name,'Error Running: '||v_sql_str||' '||SQLERRM);
      RAISE;
END;


================================
ORA-02064 Example
================================
In this example, same DB_LINK named KUKU is created to the remote database.
The procedure now is a DML Procedre, performing an update, and a commit.

The remote procedure has these API:

PKG_TEST.setDate(v_date    IN DATE,

                v_result  OUT NUMBER);

When calling the remote procedure in PL/SQL, it would be:


DECLARE
  v_date   DATE;
  v_result NUMBER;
BEGIN
  v_date := SYSDATE;
  PKG_TEST.setDate(v_date,v_result);
  EXCEPTION
    WHEN OTHERS THEN
      WRITE_LOG(v_module_name,'Error Running: '||v_sql_str||' '||SQLERRM);
      RAISE;


END;


The returned error is:

ORA-02064: distributed operation not supported
ORA-06512: at "REMOTE_USER.PKG_TEST", line 491

Per Oracle documentation, 

Error Cause:
One of the following unsupported operations was attempted:

1. array execute of a remote update with a subquery that references a dblink, or

2. an update of a long column with bind variable and an update of a second column with a subquery that both references a dblink and a bind variable, or

3. a commit is issued in a coordinated session from an RPC procedure call with OUT parameters or function call.

Action:
Simplify remote update statement.

Per Oracle Metalink CALLING REMOTE PACKAGE RECEIVES ORA-2064 (Doc ID 1026597.6):
"This is Not A Bug. 
In the documentation for ORA-2064, it states that one of  the disallowed actions is "A commit is issued in a coordinated session from an RPC with OUT parameters." 
It happens that the return value of a function call counts as an OUT parameter for purposes of this rule. 

As a workaround for some cases Pragma AUTONOMOUS_TRANSACTION can be used in the called function or procedure in the remote site package."


So, a work around this problem would be to change the remote Procedure to be Autonomous Transaction.

PKG_TEST.setDate(v_date    IN DATE,
                v_result  OUT NUMBER) IS
PRAGMA AUTONOMOUS_TRANSACTION;


Tuesday, June 27, 2017

DBMS_STATS.GATHER_FIXED_OBJECTS_STATS, DBMS_STATS.GATHER_DICTIONARY_STATS and DBMS_STATS.GATHER_SYSTEM_STATS

======================================
General 

======================================
DBMS_STATS.GATHER_FIXED_OBJECTS_STATS
DBMS_STATS.GATHER_DICTIONARY_STATS
DBMS_STATS.GATHER_SYSTEM_STATS

======================================
DBMS_STATS.GATHER_FIXED_OBJECTS_STATS
======================================
This would collect statistics about Fixed objects. 
These are the X$ and K$ tables and their indexes. 
The V$ views in Oracle are defined in top of X$ tables (for example V$SQL and V$SQL_PLAN).

How to identify when DBMS_STATS.GATHER_FIXED_OBJECTS_STATS was executed in the database ?

SELECT v.name, ts.analyzetime 
FROM V$FIXED_TABLE v, SYS.TAB_STATS$ ts 
WHERE v.object_id = ts.obj#; 

no rows returned

SELECT COUNT(*) FROM sys.tab_stats$
count(*) was 0.

EXEC DBMS_STATS.GATHER_FIXED_OBJECTS_STATS(NULL);
This takes few minutes.

SELECT COUNT(*) FROM sys.tab_stats$
returns 761

======================================
DBMS_STATS.GATHER_DICTIONARY_STATS
======================================
This procedure gathers statistics for dictionary schemas 'SYS', 'SYSTEM'.

When was it last run?
Check the the last_analyzed column for tables owned by SYS.
SELECT MAX(LAST_ANALYZED) FROM DBA_TABLES WHERE owner = 'SYSTEM';

MAX(LAST_ANALYZED)
------------------
27-JUN-17

SELECT MAX(LAST_ANALYZED) FROM DBA_TABLES WHERE owner = 'SYS';

MAX(LAST_ANALYZED)
------------------
27-JUN-17

======================================
DBMS_STATS.GATHER_SYSTEM_STATS
======================================
This procedure gathers system statistics.

The actual gathered statistics would depend upon system being under workload, or not.

DBMS_STATS.GATHER_SYSTEM_STATS procedure gathers statistics relating to the performance of your systems I/O and CPU. 
Giving the optimizer this information makes its choice of execution plan more accurate, since it is able to weigh the relative costs of operations using both the CPU and I/O profiles of the system.


When was DBMS_STATS.GATHER_SYSTEM_STATS last run?
The output from DBMS_STATS.GATHER_SYSTEM_STATS is stored in the AUX_STATS$ table.

SELECT * FROM SYS.AUX_STATS$;

NAME                 PNAME                     PVAL1 PVAL2
-------------------- -------------------- ---------- --------------------
SYSSTATS_INFO        STATUS                          COMPLETED
SYSSTATS_INFO        DSTART                          10-26-2008 13:08
SYSSTATS_INFO        DSTOP                           10-26-2008 13:08
SYSSTATS_INFO        FLAGS                         1
SYSSTATS_MAIN        CPUSPEEDNW           1108.95499
SYSSTATS_MAIN        IOSEEKTIM                    10
SYSSTATS_MAIN        IOTFRSPEED                 4096
SYSSTATS_MAIN        SREADTIM
SYSSTATS_MAIN        MREADTIM
SYSSTATS_MAIN        CPUSPEED
SYSSTATS_MAIN        MBRC
SYSSTATS_MAIN        MAXTHR
SYSSTATS_MAIN        SLAVETHR

How to execute DBMS_STATS.GATHER_SYSTEM_STATS?

Option A. - noworkload
All databases come bundled with a default set of noworkload statistics, but they can be replaced with more accurate information. 
When gathering noworkload stats, the database issues a series of random I/Os and tests the speed of the CPU. 
As you can imagine, this puts a load on your system during the gathering phase.

EXEC DBMS_STATS.GATHER_SYSTEM_STATS;

Option B. - Workload
When initiated using the start/stop or interval parameters, the database uses counters to keep track of all system operations, giving it an accurate idea of the performance of the system. 
If workload statistics are present, they will be used in preference to noworkload statistics.

EXEC DBMS_STATS.GATHER_SYSTEM_STATS('START');
-- Wait some time, say 120 minutes, during workload hours
EXEC DBMS_STATS.GATHER_SYSTEM_STATS('STOP');
or
EXEC DBMS_STATS.GATHER_SYSTEM_STATS('interval', interval => 120); 

======================================
When to run these procedures?
======================================

DBMS_STATS.GATHER_FIXED_OBJECTS_STATS
- When there was a change to init.ora Instance parameters

DBMS_STATS.GATHER_DICTIONARY_STATS
- When there was a change to dictionary structure - new schema, etc.

DBMS_STATS.GATHER_SYSTEM_STATS
- When there was a major change to the host hardware.

======================================
Get Execution Plan
======================================
SET LINESIZE 200
SET PAGESIZE 0
SELECT sql_text, sql_id from V$SQL WHERE SQL_TEXT LIKE '%XXXX%';
SELECT * FROM table (DBMS_XPLAN.DISPLAY_CURSOR('1ddfkrjxhvpt8'));

Monday, June 19, 2017

delete_old_trace_files.sh. Linux script to delete Oracle log files

===========================
General
===========================
This a script that cleans up log file for Oracle listener and server.

===========================
Code
===========================

crontab entry
0 6 * * * /software/oracle/oracle/scripts/delete_old_trace_files.sh

delete_old_trace_files.sh


#!/bin/bash
ORA_INST=igt
DAYS_TO_KEEP=14
DAYS_TO_KEEP_LIST=7
LIST_SERVER=`hostname`

LISTENER_ROOT=/software/oracle/diag/tnslsnr/${LIST_SERVER}/lsnr_igt/trace
LISTENER_ROOT_ALERT=/software/oracle/diag/tnslsnr/${LIST_SERVER}/lsnr_igt/alert

find /software/oracle/diag/rdbms/${ORA_INST}/${ORA_INST}/trace -type f -name "*.trc" -mtime +${DAYS_TO_KEEP} -exec rm {} \;
find /software/oracle/diag/rdbms/${ORA_INST}/${ORA_INST}/trace -type f -name "*.trm" -mtime +${DAYS_TO_KEEP} -exec rm {} \;
find /software/oracle/diag/rdbms/${ORA_INST}/${ORA_INST}/trace -type f -size +1000M -exec rm {} \;

find $LISTENER_ROOT  -type f -mtime +${DAYS_TO_KEEP} -exec rm {} \;
find $LISTENER_ROOT_ALERT  -type f -mtime +${DAYS_TO_KEEP_LIST} -exec rm {} \;

mv -f  ${LISTENER_ROOT}/lsnr_igt.log_6  ${LISTENER_ROOT}/lsnr_igt.log_7
mv -f  ${LISTENER_ROOT}/lsnr_igt.log_5  ${LISTENER_ROOT}/lsnr_igt.log_6
mv -f  ${LISTENER_ROOT}/lsnr_igt.log_4  ${LISTENER_ROOT}/lsnr_igt.log_5
mv -f  ${LISTENER_ROOT}/lsnr_igt.log_3  ${LISTENER_ROOT}/lsnr_igt.log_4
mv -f  ${LISTENER_ROOT}/lsnr_igt.log_2  ${LISTENER_ROOT}/lsnr_igt.log_3
mv -f  ${LISTENER_ROOT}/lsnr_igt.log_1  ${LISTENER_ROOT}/lsnr_igt.log_2
mv -f  ${LISTENER_ROOT}/lsnr_igt.log    ${LISTENER_ROOT}/lsnr_igt.log_1


===========================
Evaluate the current status
===========================
Find biggest files
find /some/path -type f -printf '%s %p\n'|sort -nr | head -10 

Find biggest folder
du  -sh * |sort -nr | head -10

Thursday, June 8, 2017

Compare Regular Cursor vs Bulk Collect

=====================================
General
=====================================
Overview: 
There is a table, which is source table.
The records from this table should be processed, and inserted into a target table.
Once done, records from source table are deleted.

This Package handles same task in two ways:
convertSdr2CdrCursor
convertSdr2CdrBulk

convertSdr2CdrCursor
The records are selected via regular cursor, and processed one by one.

convertSdr2CdrBulk
The records are selected via BULK COLLECT, and processed one by one.

Since the processing is done one by one, there is no real advantage for using BULK COLLECT.

=====================================
The time to execute in both options
=====================================
convertSdr2CdrCursorDelete 50000 records using regular cursor
Time to Execute: 999(sec), rows deleted: 50000
50000/999=50 rows/sec

convertSdr2CdrBulk
Delete 50000 records using BULK COLLECT
Time to Execute: 1249(sec), rows deleted: 60762

60762/1249 = 48 rows/sec

Both options were far superior to not using bind variables.
Without using bind variables, the time was 6 rows/sec.

=====================================
Code
=====================================
CREATE OR REPLACE PACKAGE BODY SDR_2_CDR_CONVERT_ALEC AS

PROCEDURE write_to_log(p_data in varchar2) is
  pragma autonomous_transaction;

begin
  insert into SGA_W_LOG (procedure_name, data, ts_last_modified) values ('ConvertSdr2Cdr', p_data, sysdate);
  commit;

end;

-------------------------------------------------------
-- Process using Regular Cursor
-------------------------------------------------------

PROCEDURE convertSdr2CdrCursor (pProductName in varchar2) is

  cursor SdrCrs(pProductName in varchar2) is
   SELECT  cdr_id,
           outgoing_call_direction
     from DEBUG_GEN_W_NEW_SDR_ALEC
     where rownum < 50000
     and product_name = pProductName
     and ((pProductName = 'MOCO' and event_name = 'IDP') OR (pProductName <> 'MOCO'))
     for update;

  Vsql         VARCHAR2(5000);
  v_sql_type1  VARCHAR2(5000);
  v_sql_type2  VARCHAR2(5000);
  
  v_start_date DATE;
  v_end_date   DATE;
  v_seconds    NUMBER;
  
BEGIN
  v_start_date := SYSDATE;
  write_to_log('start running convertSdr2CdrCursor procedure at '||TO_CHAR(v_start_date,'YYYYMMDD hh24:mi:ss') );
  
  v_sql_type1 := GenerateCdr(1);
  v_sql_type2 := GenerateCdr(2);

  -- for each SDR create the mapped CDRs
  for SdrRec in SdrCrs(pProductName) loop

    begin

    Vsql := v_sql_type1;

-- create the insert statement and execute it
    Vsql := 'insert into CDR_ALEC select ' || Vsql || ' from DEBUG_GEN_W_NEW_SDR_ALEC where cdr_id = :b1';
    EXECUTE IMMEDIATE Vsql USING SdrRec.cdr_id;


    -- Generate CDR for Leg2
    if SdrRec.outgoing_call_direction is not null then
       Vsql :=v_sql_type2;
       Vsql := 'insert into CDR_ALEC select ' || Vsql || ' from DEBUG_GEN_W_NEW_SDR_ALEC where cdr_id = :b1';
       EXECUTE IMMEDIATE Vsql USING SdrRec.cdr_id;
    end if;

    delete DEBUG_GEN_W_NEW_SDR_ALEC WHERE CURRENT OF SdrCrs;

    EXCEPTION
      WHEN OTHERS THEN
            write_to_log('Error for CDR_ID: '|| SdrRec.Cdr_Id || ' - ' ||sqlerrm);
            UPDATE DEBUG_GEN_W_NEW_SDR_ALEC
              SET ROAMING_TYPE ='9'
            WHERE CURRENT OF SdrCrs;
    END;
  END LOOP;

  COMMIT;
  
  v_end_date := SYSDATE;
  write_to_log('convertSdr2CdrCursor procedure completed at '||TO_CHAR(v_end_date,'YYYYMMDD hh24:mi:ss'));
  v_seconds := ROUND((v_end_date - v_start_date)*1440*60);
  write_to_log('Time to Execute: '||v_seconds||'(sec)');
  
end convertSdr2CdrCursor;


-------------------------------------------------------
-- Process using BULK COLLECT
-------------------------------------------------------
PROCEDURE convertSdr2CdrBulk(p_product_name IN VARCHAR2) IS

  TYPE sdr_record IS RECORD (
      sdr_rowid               ROWID,
      cdr_id                  DEBUG_GEN_W_NEW_SDR_ALEC.cdr_id%TYPE,
      outgoing_call_direction DEBUG_GEN_W_NEW_SDR_ALEC.outgoing_call_direction%TYPE
  );

  TYPE sdr_record_tab IS TABLE OF sdr_record;
  v_sdr_records   sdr_record_tab;

  CURSOR sdr_cur IS
  SELECT  ROWID, cdr_id, outgoing_call_direction
    FROM DEBUG_GEN_W_NEW_SDR_ALEC
   WHERE 1=1
     AND product_name = p_product_name
     AND ((p_product_name = 'MOCO' and event_name = 'IDP') OR (p_product_name <> 'MOCO'));
   
  v_sql                        VARCHAR2(5000);
  v_insert_sql                 VARCHAR2(5000);
  v_sql_type1                  VARCHAR2(5000);
  v_sql_type2                  VARCHAR2(5000);
  v_outgoingCallDirection      SDR_2_CDR_MAPPING_NEW.sdr_column_name%TYPE;

  v_start_date                DATE;
  v_end_date                  DATE;
  v_seconds                   NUMBER;
  v_cdr_id                    DEBUG_GEN_W_NEW_SDR_ALEC.cdr_id%TYPE;
  c_limit                     NUMBER := 50000;
  
BEGIN
  
  v_start_date := SYSDATE;
  write_to_log('Start running ConvertSdr2CdrBulk procedure at '||TO_CHAR(v_start_date,'YYYYMMDD hh24:mi:ss') );
  
  v_sql_type1 := GenerateCdr(1);
  v_sql_type2 := GenerateCdr(2);

  SELECT sdr_column_name INTO v_outgoingCallDirection
    FROM SDR_2_CDR_MAPPING_NEW
   WHERE leg_id = 2
    AND cdr_column_name = 'CALL_DIRECTION';

  write_to_log('Before Opening Cursor');
  
   OPEN sdr_cur;
   --Loop on Cursor
   LOOP
     BEGIN   
       FETCH sdr_cur 
         BULK COLLECT INTO v_sdr_records LIMIT c_limit;

         IF sdr_cur%NOTFOUND THEN
             write_to_log('No More Data to Fetch from DB');
         END IF;  
        
         write_to_log('v_sdr_records.COUNT : '||v_sdr_records.COUNT );
         write_to_log('Processing Data');
         --Loop on the Bulk records
         FOR indx IN 1 .. v_sdr_records.COUNT LOOP
          
           BEGIN
             -- create the insert statement and execute it
             v_sql := v_sql_type1;           
             v_insert_sql := 'INSERT INTO CDR_ALEC SELECT ' || v_sql || ' FROM DEBUG_GEN_W_NEW_SDR_ALEC WHERE cdr_id = :b1';
             v_cdr_id :=  v_sdr_records(indx).cdr_id;
             EXECUTE IMMEDIATE v_insert_sql USING v_cdr_id;

             --check whether to create 2nd CDR for outgoing leg
             IF v_sdr_records(indx).outgoing_call_direction IS NOT NULL THEN
               v_sql := v_sql_type2;
               v_insert_sql := 'INSERT INTO CDR_ALEC SELECT ' || v_sql || ' FROM DEBUG_GEN_W_NEW_SDR_ALEC WHERE cdr_id = :b1';               
               EXECUTE IMMEDIATE v_insert_sql USING  v_sdr_records(indx).cdr_id;
             END IF; 

             DELETE DEBUG_GEN_W_NEW_SDR_ALEC WHERE DEBUG_GEN_W_NEW_SDR_ALEC.rowid = v_sdr_records(indx).sdr_rowid;
           EXCEPTION
             WHEN OTHERS THEN
               write_to_log('ConvertSdr2CdrBulk Error for CDR_ID: '|| v_sdr_records(indx).cdr_id || ' Error Details: ' ||SQLERRM);
               UPDATE DEBUG_GEN_W_NEW_SDR_ALEC
               SET ROAMING_TYPE ='9'
             WHERE cdr_id =  v_sdr_records(indx).cdr_id;
           END;   
                

        END LOOP;
        EXIT WHEN sdr_cur%NOTFOUND;

     EXCEPTION
       WHEN OTHERS THEN
         write_to_log('Unexpected Error in ConvertSdr2CdrBulk: '||SQLERRM);          
     END;
     
     END LOOP;
     CLOSE sdr_cur;
     COMMIT;
  v_end_date := SYSDATE;
  write_to_log('ConvertSdr2CdrBulk procedure completed at '||TO_CHAR(v_end_date,'YYYYMMDD hh24:mi:ss'));
  v_seconds := ROUND((v_end_date - v_start_date)*1440*60);
  write_to_log('Time to Execute: '||v_seconds||'(sec)');
  

END ConvertSdr2CdrBulk;

END SDR_2_CDR_CONVERT_ALEC;

Tuesday, May 16, 2017

Linux Code Example. Reading from file and then sed+awk+egrep.

==============================
General
==============================
Code example.

Reading from file
sed+awk+egrep
If result is wrong, report error.
For predefined time, skip check.

cat $GG_STATUS_FILE | while read;do printf '%s\n' ;egrep -i '(EXTRACT|REPLICAT)'|tr ":" " " | tr -s '[:space:]' | awk -v lc=$LC '{if
 ($2!="RUNNING" || $4>=01 || $5>=lc ||  ( "$7" ~ /^[0-9]+$/ && $7>=01 ) || $8>=lc ) {print " Problem with the "$1" "$3" : status is 
"$2" with lag of " $4"HR:"$5"MI and checkpoint of "$7"HR:"$8"MI " >> "/tmp/gg_test.out"} }' ;  done
        if [ -s "/tmp/gg_test.out" ]; then
      GG_STATUS=1
    fi

  # If no GoldenGate errors found
  if [ ${GG_STATUS} -eq 0 ]; then
    echo "`date +"%d-%m-%Y %H:%M:%S"`   GOLDENGATE STATUS OK. GoldenGate seems to be functioning properly" | tee -a ${LOG_FILE}
  else
  
    #--------------------------------------------
    #Skip restart from crontab
    #46 06 * * * /software/oracle/oracle/scripts/gg_restart_all_extracts.sh
    #--------------------------------------------
    SKIP_HOUR=6
    SKIP_MIN_START=45
    SKIP_MIN_END=59

    RUN_HOUR=`date | sed s/:/' '/g | awk '{print $4}'`
    RUN_MIN=`date | sed s/:/' '/g | awk '{print $5}'`
    SKIP_CHECK=0

    if [ $SKIP_HOUR -eq $RUN_HOUR ]; then
      if [ $SKIP_MIN_START -lt $RUN_MIN ] && [ $RUN_MIN -lt $SKIP_MIN_END ]; then
        SKIP_CHECK=1
      else
        SKIP_CHECK=0
      fi
    fi

    if [ $SKIP_CHECK -eq 1 ]; then
      echo "`date +"%d-%m-%Y %H:%M:%S"`   GOLDENGATE Restart Time, Skip GOLDENGATE STATUS Check." | tee -a ${LOG_FILE}
    else
      echo "`date +"%d-%m-%Y %H:%M:%S"`   GOLDENGATE STATUS MAJOR. Problem with GoldenGate Process(es)" | tee -a ${LOG_FILE}
      cat /tmp/gg_test.out | tee -a ${LOG_FILE}
      cat $GG_STATUS_FILE | tee -a ${LOG_FILE}
    fi
    #--------------------------------------------
    # echo "`date +"%d-%m-%Y %H:%M:%S"`   GOLDENGATE STATUS MAJOR. Problem with GoldenGate Process(es)" | tee -a ${LOG_FILE}
    # cat /tmp/gg_test.out | tee -a ${LOG_FILE}
    # cat $GG_STATUS_FILE | tee -a ${LOG_FILE} 
    #--------------------------------------------
  fi

  \rm -f /tmp/gg_test.out
  \rm -f /tmp/check_goldengate.*
  \rm -f /tmp/gg_status.*