Friday 26 August 2011

The DIRECTORY Object Handy for BFILEs and UTL_FILE

Question:
What is the purpose of the DIRECTORY object in Oracle?
Answer:
Deepak, this answer assumes that you were asking about the DIRECTORY object, rather than the Oracle Internet Directory.
The DIRECTORY object in Oracle is useful for working with BFILEs via the DBMS_LOB package and, in Oracle9i Database Release 2, with UTL_FILE to read and write files.
The following statements demonstrate how to grant privileges to allow definition of a directory:
CONNECT SYS/ AS SYSDBA

GRANT CREATE ANY DIRECTORY TO scott
/
Developers will usually not have the privilege to create a directory; that capability should be tightly controlled by the database administrator, to avoid gaping security holes in one's database.
With the privilege granted, however, I can create a directory that is owned by SYS but can be used by SCOTT:
CONNECT SCOTT /TIGER

CREATE OR REPLACE DIRECTORY images_dir AS 'c:\temp'
/
When the directory is defined, you can also grant read and write privileges on a directory.
With this directory in place, I can now use it to load an image from a file (BFILE) into a LOB stored in a table:
DROP TABLE images
/

CREATE TABLE images ( ID INTEGER , image BLOB )
/

DECLARE
l_file BFILE := BFILENAME ( 'IMAGES_DIR' , 'steven.gif' );
l_blob_loc BLOB ;
BEGIN
-- Get a lob locator.
INSERT INTO images VALUES ( 1 , EMPTY_BLOB ())
RETURNING image INTO l_blob_loc ;

-- Now load the file into that lob locator
DBMS_LOB .fileopen ( l_file , DBMS_LOB .file_readonly );
DBMS_LOB .loadfromfile ( dest_lob => l_blob_loc
, src_lob => l_file
, amount => DBMS_LOB .getlength ( l_file )
);
DBMS_LOB .fileclose ( l_file );
COMMIT;
END;
/
And here is an example of using a database directory with UTL_FILE:
CREATE OR REPLACE DIRECTORY prod_dir AS 'P:\order_entry\data'
/

CREATE OR REPLACE DIRECTORY prod_dir AS 'P:\backup\order_entry\data'
/

BEGIN
-- Copy the first six lines of a file to another file.
-- using the UTL_FILE.FCOPY program that was added in
-- in Oracle Database 9i Release 2.
UTL_FILE .fcopy (
src_location => 'PROD_DIR',
src_filename => 'names.txt',
dest_location => 'BACKUP_DIR' ,
dest_filename => 'prevnames.txt' ,
start_line => 1 ,
end_line => 6
);
END;
/
By the way, you can query the contents of ALL_DIRECTORIES to see the directories the current schema can use

No comments:

Post a Comment