My blog has moved!

You should be automatically redirected in 5 seconds. If not, visit
http://www.oraexplorer.com
and update your bookmarks.

Tuesday, February 12, 2008

What is the current status of Data Guard?

While working in one of Data Guard projects, I was asked about the current sync status of standby. I started talking about gap, SCN, or applied and received archive log numbers, and so on, which obviously did not make sense to business users. The only thing they'd like to know is whether or not data at standby is up-to-date with that of primary, or if not, what date/time of standby data it is at right now.

All existing scripts we do have in house are just checking the received or applied SCNs or thread# of archive logs. In order to make sense out of these numbers for business users or managers, I will need to convert them into date and time. Fortunately, I recalled the "scn_to_timestamp" function which allows me to convert the SCN number to its corresponding timestamp.

I can get the current_scn from v$database of the standby. However, in the case of physical standby, when database is being mounted (recovery mode), this function does not work. It should work fine with the logical standby which is opened all the time.

SQL> select scn_to_timestamp(current_scn) from v$database;
select scn_to_timestamp(current_scn) from v$database
*
ERROR at line 1:
ORA-00604: error occurred at recursive SQL level 1
ORA-01219: database not open: queries allowed on fixed tables/views only
To resolve this, once getting the current_scn on standby, I can log on to the primary and get the time stamp corresponding to the SCN number.

Sample below is the KSH script to obtain the date/time based on a SCN. Note that the syntax to check the gap is added as well. The account connecting to primary just needs SELECT_CATALOG_ROLE.

# Get SCN number from DR
DRSCN=/tmp/drscn$$.log
${SQLPLUS} -s /nolog <<EOF
connect / as sysdba
set heading off
set feedback off
col current_scn format 999999999999999999999999
spool ${DRSCN}
select current_scn from v\$database;
spool off
exit
EOF
DR_SCN=`cat ${DRSCN}`

rm ${DRSCN}

# Get Timestamp from Primary
TSDR=/tmp/tsdr$$.log
TSSTAT=/tmp/tsstat$$.log
${SQLPLUS} -s /nolog &lt&ltEOF
connect user/password@PRIMARY
set heading off
set feedback off
spool ${TSDR}
select
to_char(scn_to_timestamp(${DR_SCN}),'MM/DD/YYYY HH24:MI')
from dual;
spool off
spool ${TSSTAT}
select
case
when
scn_to_timestamp(${DR_SCN}) > systimestamp - interval '1' hour
then 'OK'
when
scn_to_timestamp(${DR_SCN}) > systimestamp - interval '2' hour
then 'WARNING'
else 'CRITICAL'
end "STATUS"
from dual;
spool off
exit
EOF

rm ${TSDR}
rm ${TSSTAT}

Thursday, January 3, 2008

Unconventional way to create an Oracle database

This is so funny. It probably takes longer for the guy to create a database if he has a cold or flu.

http://www.youtube.com/watch?v=CHzV4LZnvHc

BTW, I like the name of database, "nosejob".

Friday, December 28, 2007

Select-only-privileged user can lock table

This is an interesting post by Tanel Poder on "Your read only accounts aren't that read only". Basically a read-only account with the select privilege only on a table can issue the lock on that table even though it does not have any DML privileges. This means that it could prevent any further DMLs (causing denial of service) to other valid sessions. This behavior is not new. But explanation, examples and work-around/semi-solution by Tanel are clear. Good Job!!!

Tuesday, December 4, 2007

SQL Plus Copy

The SQL*Plus COPY command can copy data between two databases via SQL*Net.

Syntax:

USER1 @srcdb> copy
usage: COPY FROM [db] TO [db] [opt] [table] { ([cols]) } USING [sel]
[db] : database string, e.g., hr/your_password@d:chicago-mktg
[opt] : ONE of the keywords: APPEND, CREATE, INSERT or REPLACE
[table]: name of the destination table
[cols] : a comma-separated list of destination column aliases
[sel] : any valid SQL SELECT statement
A missing FROM or TO clause uses the current SQL*Plus connection.
Sample:
@Target database, the table initially does not exist.
USER1 @targetdb> select * from rep_tab;
select * from rep_tab
*
ERROR at line 1:
ORA-00942: table or view does not exist
@Source database, run copy command within SQL Plus.
USER1 @srcdb> copy from user1/user1@srcdb -
> to user1/user1@target_host:1521/target_sid -
> create rep_tab -
> using -
> select * from rep_tab;

Array fetch/bind size is 15. (arraysize is 15)
Will commit when done. (copycommit is 0)
Maximum long size is 80. (long is 80)
Table REP_TAB created.

1 rows selected from user1@SRCDB.
1 rows inserted into REP_TAB.
1 rows committed into REP_TAB at user1@host1:1521/targetsid.

@Target database, now table is copied here.
USER1 @targetdb> select * from rep_tab;

A
----------
1

This is a quick and easy way to copy data between two databases especially on where the usage of database link is restricted. It only requires SQL*Net service name (or host/port/service) and proper privileges.

Friday, November 30, 2007

APEX to upload a text file and write into a table

One of the web development projects using Oracle APEX I’m working on is to upload the content of a text file in csv format into database. By default, all files using the “File Browse..” element will be uploaded to the “wwv_flow_files” table which has structure as follows -


SQL> desc wwv_flow_files
Name Type Nullable Default Comments
------------ -------------- -------- ------- --------
ID NUMBER
FLOW_ID NUMBER
NAME VARCHAR2(90)
FILENAME VARCHAR2(400) Y
TITLE VARCHAR2(255) Y
MIME_TYPE VARCHAR2(48) Y
DOC_SIZE NUMBER Y
DAD_CHARSET VARCHAR2(128) Y
CREATED_BY VARCHAR2(255) Y
CREATED_ON DATE Y
UPDATED_BY VARCHAR2(255) Y
UPDATED_ON DATE Y
LAST_UPDATED DATE Y
CONTENT_TYPE VARCHAR2(128) Y
BLOB_CONTENT BLOB Y
LANGUAGE VARCHAR2(30) Y
DESCRIPTION VARCHAR2(4000) Y
FILE_TYPE VARCHAR2(255) Y
FILE_CHARSET VARCHAR2(128) Y

Even though the text file contains character data, the uploaded file content will be stored in the “binary format” in a BLOB column named BLOB_CONTENT. Due to nature of BLOB, to read character out, the conversion using “chr” function is required. Please see a good article about this concept and conversion by Natalka Roshak on the orafaq at http://www.orafaq.com/node/895.

I modified the sample script provided in above article to suite my need – reading each line of the text file and insert into a target table.

DECLARE
v_blob_data BLOB;
v_blob_len NUMBER;
v_position NUMBER;
v_raw_chunk RAW(10000);
v_char CHAR(1);
c_chunk_len number := 1;
v_line VARCHAR2 (32767) := NULL;
v_data_array wwv_flow_global.vc_arr2;
BEGIN
-- Read data from wwv_flow_files
select blob_content into v_blob_data
from wwv_flow_files where name = 'F29800/Data_CSV.csv';

v_blob_len := dbms_lob.getlength(v_blob_data);
v_position := 1;

-- Read and convert binary to char
WHILE ( v_position <= v_blob_len ) LOOP
v_raw_chunk := dbms_lob.substr(v_blob_data,c_chunk_len,v_position);
v_char := chr(hex_to_decimal(rawtohex(v_raw_chunk)));
v_line := v_line || v_char;
v_position := v_position + c_chunk_len;
-- When a whole line is retrieved
IF v_char = CHR(10) THEN
-- Convert comma to : to use wwv_flow_utilities
v_line := REPLACE (v_line, ',', ':');
-- Convert each column separated by : into array of data
v_data_array := wwv_flow_utilities.string_to_table (v_line);
-- Insert data into target table
EXECUTE IMMEDIATE 'insert into TABLE_X (v1, v2, v3, v4)
values (:1,:2,:3,:4)'
USING
v_data_array(1),
v_data_array(2),
v_data_array(3),
v_data_array(4);
-- Clear out
v_line := NULL;
END IF;
END LOOP;
END;
/

Wednesday, November 14, 2007

Oracle APEX in 11g Installation

Today I installed Oracle 11g (11.1.0.6) on my machine. I did not realize that Oracle APEX is a part of the standard database components.



So after the 11g installation, I just follow simple steps (shown later below) for the post-installation. In order to access the APEX application, either the embedded PL/SQL gateway or Oracle HTTP server with mod_plsql is needed. For simplicity, I've decided to go with the former. By using the embedded PL/SQL gateway, it will run using the Oracle XML DB HTTP server which is already in Oracle database, so there is no need to install a separate HTTP server. The Oracle's document here explains about this as well as provides the detailed information on the post-installation.

To configure the embedded PL/SQL gateway:

1. Go to the $ORACLE_HOME/apex directory.

2. Use SQL/Plus to connect as SYS to 11g database where APEX is installed.


SYS AS SYSDBA@db11r1> @apxconf

PORT
----------
8080

Enter values below for the XDB HTTP listener port and the password for the Application Express ADMIN user.
Default values are in brackets [ ].
Press Enter to accept the default value.


Enter a password for the ADMIN user []admin_password
Enter a port for the XDB HTTP listener [ 8080]
...changing HTTP Port

PL/SQL procedure successfully completed.

PL/SQL procedure successfully completed.

Session altered.

...changing password for ADMIN

PL/SQL procedure successfully completed.

Commit complete.
3. Unlock the ANONYMOUS account.
SYS AS SYSDBA@db11r1> ALTER USER ANONYMOUS ACCOUNT UNLOCK;

User altered.
4. Enable Oracle XML DB HTTP server
SYS AS SYSDBA@db11r1> EXEC DBMS_XDB.SETHTTPPORT(8080);

PL/SQL procedure successfully completed.

SYS AS SYSDBA@db11r1> COMMIT;

Commit complete.
5. We're now ready to access APEX.

http://host:port/apex
http://host:port/apex/apex_admin -- for admin page

Port in this case is 8080 which is the default.






















Note that the format of URL is a little bit different from when using HTTP server with mod_plsql -

http://host:port/pls/apex
http://host:port/pls/apex/apex_admin -- for admin page


Also the SQL Developer 1.1.3 is included under "sqldeveloper" directory of ORACLE HOME. So just double-click at sqldeveloper.exe to launch application.


Saturday, November 3, 2007

RMAN Duplicate

Last week I had a chance to work on RMAN to duplicate the existing 3-node RAC database to another 2-node RAC database. In my case, the 2-node target already has running instances, the task here is to wipe out and copy data from production.

Here is my note. I tried to put some comments to cover in case of when duplicating from a scratch - meaning there is no target database before as well.

Source:
3-node Oracle 10.2.0.3 RAC on Solaris 10: hostA1, hostA2 and hostA3
Database: racA (instance racA1, racA2 and racA3)

Target:
2-node Oracle 10.2.0.3 RAC on Solaris 10: hostB1 and hostB2
Database: racB (instance racB1 and racB2)

1. On source host, backup on source using RMAN (either using catalog or control file to disk or tape). Sample here is shown using control file to disk.

$ORACLE_HOME/bin/rman

RMAN> connect target /
connected to target database: RACA (DBID=2748812654)

run {
allocate channel d1 type disk;
backup format '/u1/df_%t_%s_%p' database
include current controlfile
plus archivelog;
release channel d1;
}


2. Copy all backupset files to one of the target hosts to the same location of backup

$ scp /u1/df* hostB1:/u1/

If this is a new target database, copy the pfile or spfile from source host too.

Also create a password file using orapwd on the target hosts.

3. Modify the initialization parameters.

You can modify the existing spfile directly if the target database exists before. However, I prefer not to touch the original spfile. My suggestion is to create an init file and use that instead. Make sure this new init file will be used everything instance is restarted because during duplicate, database will be restarted by RMAN. To ensure that it will not use the existing spfile, I would recommend renaming it temporarily.

SQL> create pfile='$ORACLE_HOME/dbs/initracB.ora' from spfile;

$> mv spfileRACDB.ora spfileRACDB_temp.ora

In initracB.ora
Change
*.cluster_database=false

add convert if names or paths are different
*.db_file_name_convert = ('/u1/racA','/u1/racB')
*.log_file_name_convert= ('/u2/racA','/u1/racB')

Due to a bug in note:334899.1, add this
_no_recovery_through_resetlogs=TRUE

4. On target host, create a TNSNAME alias pointing to the source database.

racA =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = hostA1)(PORT = 1521))
(ADDRESS = (PROTOCOL = TCP)(HOST = hostA2)(PORT = 1521))
(ADDRESS = (PROTOCOL = TCP)(HOST = hostA3)(PORT = 1521))
)
(CONNECT_DATA =
(SERVICE_NAME = racA)
(FAILOVER_MODE =
(TYPE = SELECT)
)
)
)

5. Shutdown all instance if up and startup "nomount" only one instance. Leave other instances on other nodes down. The RMAN duplicate will recreate a database instance for one node only.

6. Start RMAN duplicate

$ORACLE_HOME/bin/rman

RMAN> connect target sys/syspassword@racA
connected to target database: RACA (DBID=2748812654)

RMAN> connect auxiliary /
connected to auxiliary database: RACB (DBID=215163916, not open)

RMAN> run {
allocate channel D1 device type disk;
allocate auxiliary channel D2 device type disk;
DUPLICATE TARGET DATABASE TO RACB;
}

You can use “SKIP” option to not duplicate some tablespaces if needed.

If you encountered missing archive files, copy them from source to target on the same path, and re-run RMAN duplicate.

7. Once completed, restart instance to use the original spfile or the one after reverting additional parameters in step #3.

If you try to restart the 2nd instance, it will fail with an error that there is no log thread.

8. Recreate redo logs of thread 2.

ALTER DATABASE ADD LOGFILE THREAD 2
GROUP 4 (‘u01/racB/redo/redo4a’,
‘u02/racB/redo/redo4a’) size 100M,
GROUP 5 (‘u01/racB/redo/redo5a’,
‘u02/racB/redo/redo5a’) size 100M,
GROUP 6 (‘u01/racB/redo/redo6a’,
‘u02/racB/redo/redo6a’) size 100M ;

Then
alter database enable public thread 2;

You now should be able to start the second instance.

9. Add a new temporary file into the temporary tablespace

SQL> alter tablespace temp add tempfile '/u1/racB/oradata/temp2.dbf' size 1024m reuse;

That’s it!!!

Monday, October 29, 2007

Change column width of show parameter in SQL Plus

You can change the width of the NAME, TYPE and VALUE of "show parameter" in SQL/Plus.


SQL> show parameter sga

NAME TYPE
------------------------------ ------------------------------
VALUE
------------------------------
lock_sga boolean
FALSE
pre_page_sga boolean
FALSE
sga_max_size big integer
300M
sga_target big integer
0

SQL> column NAME_COL_PLUS_SHOW_PARAM format A20
SQL> column TYPE format A20
SQL> column VALUE_COL_PLUS_SHOW_PARAM format A20

SQL> show parameter sga

NAME TYPE VALUE
-------------------- -------------------- --------------------
lock_sga boolean FALSE
pre_page_sga boolean FALSE
sga_max_size big integer 300M
sga_target big integer 0

Saturday, October 27, 2007

Read XML data from URL and insert into Oracle

There are lot of articles (example) talking about how to read a physical XML file and insert into Oracle database. Here is a little bit different. This shows you how to read XML directly from web's URL then insert into a database table without involving a physical XML file.

To manage the list of URLs, I create a table containing list of URLs. There will be only one URL in this example. But you can use this table to manage multiple URLs if needed.

CREATE TABLE url_tab
(
URL_NAME VARCHAR2(100),

URL SYS.URIType
);

Insert the URL into this table. Note that URL will go to where column type is SYS.URIType.

SQL> INSERT INTO url_tab VALUES
(’This is a test URL’,
sys.UriFactory.getUri(’http://www.domain.com/test.xml’)
);

SQL> commit;

This is the sample of the test.xml file.








The XML_DATA_TAB is a target table containing a XMLTYPE column where data will be loaded into.

SQL> CREATE TABLE xml_data_tab ( xml_data xmltype );

Table created.

If there are multiple URLs, obviously you have to loop through all in the list to load data one URL at the time. But in this case, there is only one URL, so here is how to read XML data from an URL and then convert into XMLType data.

insert into xml_data_tab
select sys.xmltype.createXML(u.url.getClob()) from url_tab u;

* Note that if you're running on the 11g database, you might run into an error on ACL. Please consult Metalink note 453786.1. Watch out for "&nbs" keyword in step #5 box #2. Remove this typo before execution.

SQL> insert into xml_data_tab
select sys.xmltype.createXML(u.url.getClob()) from url_tab u;

select sys.xmltype.createXML(u.url.getClob()) from url_tab u
*
ERROR at line 2:
ORA-29273: HTTP request failed
ORA-06512: at "SYS.UTL_HTTP", line 1674
ORA-24247: network access denied by access control list (ACL)
ORA-06512: at "SYS.HTTPURITYPE", line 34

After the fix -

SQL> insert into xml_data_tab
select sys.xmltype.createXML(u.url.getClob()) from url_tab u;

1 row created.


SQL> commit;

Commit complete.

Note that there is no mechanism for any error checking. You can add yourself if needed. So it is assumed that XML is well-formed.

These are sample queries to extract data from xml_data column.

Retrieve value of attribute -

SQL> select
extractvalue(xml_data, '/crm_data/@product') product_name
from xml_data_tab;


PRODUCT_NAME
-----------------------------------
electronics

Retrieve value of element -

SQL> select
extractvalue(xml_data, '/crm_data/customer/first_name') first_name,
extractvalue(xml_data, '/crm_data/customer/last_name') last_name,
extractvalue(xml_data, '/crm_data/customer/address') address
from xml_data_tab;

FIRST_NAME LAST_NAME ADDRESS
-------------------- -------------------- --------------------
John Doe 12345 Lala lane

Oracle Sample Schemas

Well, I believe most of DBAs including myself do not want to create Oracle sample schemas when creating a database. Why bother because we thought we would never use those sample schemas anyway. However, recently I’m running into an issue when trying to use tutorials on Oracle Data Mining (ODM). It requires the Sale History (SH) schema. Since database is already created, when I run “dbca” again on that database and select “Configure Database Options”, the “Sample Schemas” option is grayed out.

In order to install these sample schemas manually on the existing Oracle 10g home, a script called “mksample.sql” located at @?/demo/schema is needed. By default, the Enterprise Edition version does not include this script when binaries are installed.

D:\oracle\product\10.2.0\db_1\demo\schema> ls
bus_intelligence
mk_dir.sql.ouibak sales_history

human_resources
mk_dir.sql.sbs
sted_mkplug.sql.dbl

log mkplug.sql
mk_dir.sql
order_entry

You will need to download the 10g Companion CD, run “Setup.exe”, select to install the “Oracle Database 10g Productions” (2nd option) then specify the existing Oracle Home. The installation takes about 10 minutes. After the installation, now mksample.sql is there.

D:\oracle\product\10.2.0\db_1\demo\schema>ls
README.txt
mk_dir.sql.ouibak
mkverify.sql

bus_intelligence
mk_dir.sql.ouibak.1
order_entry

human_resources
mkplug.sql
product_media

info_exchange
mksample.sql

sales_historylog

mksample.sql.sbs
shippingmk_dir.sql
mkunplug.sql

sted_mkplug.sql.dbl

To install the sample schemas, just simply run the following at the SQL prompt -

> sqlplus /nolog
SQL>@mksample systempwd syspwd hrpwd oepwd pmpwd ixpwd shpwd bipwd default_tablespace temporary_tablespace log_file_directory


Example:
@mksample manager change_on_install hr oe pm ix sh bi example temp $ORACLE_HOME/demo/schema/log/

The process takes about 20 minutes.

Please note that this same script can be used if there is a need to reset data of these sample schemas.