Minisha
Minisha

Reputation: 2237

Is there a FILE_READ equivalent in oracle?

I was trying to load data in to db on application startup.

With H2 I was using the below query and it worked perfectly. With Oracle it doesn't work. Can someone point me the right direction? I went through oracle documentation but didn't manage to find an equivalent.

INSERT INTO TEMPLATES(ID,NAME,BODY) VALUES('2b04469f31c445ca82c354322845b52b', 'Records', FILE_READ('/opt/bin/Records.txt'));

Upvotes: 1

Views: 598

Answers (1)

APC
APC

Reputation: 146239

Oracle SQL has no equivalent of a file_read() function. However, it is possible to write your own.

However, before we start you need to known that Oracle is much more locked down when it comes to database interoperability with the OS. Many things are not enabled by default, and consequently you may require assistance from a friendly DBA to get this working.

For instance, we cannot use OS filepaths directly (at least in more recent versions) so we need to create a DIRECTORY object. Normally the privilege to do this is restricted to DBAs.

create directory opt_bin as '/opt/bin';
grant read on directory opt_bin to <<your_user>>;

Note that /opt/bin must be a directory to which the database has access. On a *nix environment that means the oracle OS user has at least read on the directory.

With that infrastructure in place we can create a function which loads an OS file into a blob. It uses the directory and file name to instantiate a BFILE then applies DBMS_LOB capability to load that BFILE into a BLOB.

create or replace file_to_blob 
    (p_dir in varchar2, p_file in varchar2)
    return blob
is
    bf bfile;
    tmp_blob blob := empty_blob();
    l_dest_offset pls_integer := 1;
    l_src_offset pls_integer := 1;
begin
    bf := bfilename(p_dir, b_file);
    dbms_lob.createtemporary(tmp_blob, true);
    dbms_open(bf, dbms_lob.file_readonly);
    dbms_lob.loadblobfromfile(tmp_blob, bf, dbms_lob.lobmaxsize, l_dest_offset, l_src_offset);
    dbms_lob.close(bf);
    return tmp_blob;
end;
/

You can use this function in your insert statement like this:

INSERT INTO TEMPLATES(ID,NAME,BODY) 
VALUES
('2b04469f31c445ca82c354322845b52b', 'Records', file_to_blob('opt_bin', 'Records.txt'));

Upvotes: 1

Related Questions