Understanding Utl_file - sql

So I am changing the procedure of this parse_file 'clean_files_up procedure'. I have coded the changes but after testing I realized
I am actually having a hard time understanding what is going on. I have never worked with parsing a file or utl_file so I don't entirely
undrestand the concept.
So in summary, we need it to look for a file called Files20130807.xxx with the current sysdate from a directory called NEWFILE_DIRECTORY.
IF there is no file meaning that it can not find a file matching the current sysdate it needs to run the orignial file which is located
in a different directory called ORIGINALFILE_DIRECTORY and then go the the end of the procedure. If there is a file that matches the
current sysdate then it needs to continue through the procedure. When it gets to actually opening up the file it will open the file that
matches the current sysdate from NEWFILE_DIRECTORY and then will parse the file, otherwise if the current file from NEWFILE_DIRECTORY
is open then it will need to open the original file located in ORIGNIALFILE_DIRECTORY and then will parse that file instead.
PROCEDURE clean_files_up IS
v_fileName VARCHAR2(20) := Files || to_char(sysdate, 'YYYYMMDD') || '.xxx';
v_inFile utl_file.file_type;
v_outFile utl_file.file_type;
v_line VARCHAR2(2000);
v_newLine VARCHAR2(2000);
v_count NUMBER := 1;
BEGIN
--No Files found for current date
IF (substr(v_fileName, 6, 8)) <> to_char(sysdate, 'YYYYMMDD') THEN
v_inFile := utl_file.fopen('ORIGINALFILE_DIRECTORY', 'OriginalFile.xxx', 'r');
RETURN; --go to end of procedure
END IF;
v_inFile := utl_file.fopen ('NEWFILE_DIRECTORY', 'v_fileName', 'r');
IF utl_file.is_open(v_inFile) THEN
v_outFile := utl_file.fopen('ORIGINALFILE_DIRECTORY',
'OriginalFile.xxx',
'W');
LOOP
BEGIN
utl_file.get_line(v_inFile, v_line);
IF v_line IS NULL THEN
EXIT;
END IF;
IF v_count > 1 THEN
get_new_csv_line(v_line, v_newLine);
utl_file.put_line(v_outFile, v_newLine);
utl_file.fflush(v_outFile);
END IF;
v_count := v_count + 1;
EXCEPTION
WHEN no_data_found THEN
EXIT;
END;
END LOOP;
utl_file.fclose(v_outFile);
END IF;
EXCEPTION
WHEN OTHERS THEN
Condition;
END clean_files_up;
Questions:
So I need to create a new directory called NEWFILE_DIRECTORY located in some file path /xxx/xxx/xxx that has the list of files
like ; Files20130804.xxx, Files20130805.xxx, Files20130806.xxx, Files20130807 locted in it. I don't know
where inside of this procedure I would have the new directory being created or even if I can create it within the procedure
CREATE OR REPLACE DIRECTORY newfile_directory in as '/xxx/xxx/xxx'
2.. I need to read in these files to make sure that it matches the sysdate otherwise it needs to run the original file and
then go to the end of the proceudre. This part is the IF statement right after the BEGIN. I am just confussed in how it knows
to look in the NEWFILE_DIRECTORY to find the matching file name Files20130807.xxx to see if it is a match or not.
3.. This is a similiar question to #2 but how does (after the first End IF;) it know where the file path for NEWFILE_DIRECOTRY
and ORIGINALFILE_DIRECTORY is located without giving or defining a path ?
4.. Lastly when testing the code I noticed that after it reads in the v_inFile := utl_file.fopen ('NEWFILE_DIRECTORY', 'v_fileName', 'r');
(right after the first End IF;) it goes down to the exception without continuing through the if and to the loop.
I would really appreciate it someone could answer theses questions are at least help to understand what is going on. Also
if I need to clearfiy and of the questions (1-4) I can do that.

Answers on your questions:
1) Following code creates link from Oracle internally defined directory (can see them by selecting data from DBA_DIRECTORIES) to file system directory.
CREATE OR REPLACE DIRECTORY NEWFILE_DIRECTORY AS '/xxx/xxx/xxx'
If path '/xxx/xxx/xxx' already exists in file system, then this will be correct way.
2) If I understand you correctly, then you must check that in NEWFILE_DIRECTORY exists file with current date in it's name. It can be done with following function:
FUNCTION check_if_file_exists
(p_file_name IN VARCHAR2
,p_file_dir IN VARCHAR2)
RETURN BOOLEAN
IS
v_file utl_file.file_type;
BEGIN
v_file := utl_file.fopen(p_file_dir, p_file_name, 'R');
IF utl_file.is_open(v_file) THEN
RETURN TRUE;
ELSE
RETURN FALSE;
END IF;
EXCEPTION
WHEN UTL_FILE.invalid_path THEN
RETURN FALSE;
WHEN utl_file.invalid_operation THEN
RETURN FALSE;
END check_if_file_exists;
And your first if will be:
IF check_if_file_exists(v_fileName, 'NEWFILE_DIRECTORY') THEN
3) You can create DB directories (mapping for DB to find file system path) by "CREATE OR REPLACE DIRECTORY" (see #1)
4) You pass parameter as string value 'v_fileName' not variable v_fileName. Correct code would be:
v_inFile := utl_file.fopen ('NEWFILE_DIRECTORY', v_fileName, 'r');

Janis Baiza thank you for the answer it really helped me to understand what was going on.
I actually found that this will check to see if the file exists in the current directory as well and if it does then outputs that it exists and if it doesn't then out put it doesn't exist and run the original file then return to end of procedure.
utl_file.fgetattr ('NEWFILE_DIRECTORY', v_fileName, v_check_fileEX, v_fLength, v_Bsize );
IF v_check_fileEX THEN
dbms_output.put_line('file exists');
END IF;
IF NOT v_check_fileEX THEN
dbms_output.put_line('file does not exist');
v_inFile := utl_file.fopen('ORIGINALFILE_DIRECTORY', 'OriginalFile.xxx', 'r');
RETURN;
END IF;

Related

Not downloading correctly files from APEX

I have a little problem. I'm trying to download files from APEX application. The file downloads correctly but the browser doesn't recognize the file as a PDF. The code below works perfectly but lacks the recognition of the filetype.
create or replace PROCEDURE DOWNLOAD_LIST
(p_id_list in VARCHAR2) AS
v_mime VARCHAR2(2000);
v_length NUMBER;
v_file_name VARCHAR2(2000);
Lob_loc BLOB;
BEGIN
SELECT MIME_TYPE, BLOB_CONTENT, CODI ,DBMS_LOB.GETLENGTH(blob_content)
INTO v_mime,lob_loc,v_file_name,v_length
FROM table
WHERE ID_LIST = p_id_list;
-- set up HTTP header
-- use an NVL around the mime type and
-- if it is a null set it to application/octect
-- application/octect may launch a download window from windows
-- I've tried to put either pdf or octet. The database file has 'application/pdf' as mime_type
owa_util.mime_header( nvl(v_mime,'application/pdf'), FALSE );
-- set the size so the browser knows how much to download
htp.p('Content-length: ' || v_length);
-- the filename will be used by the browser if the users does a save as
--htp.p('Content-Disposition: attatchment; filename="'||replace(replace(substr(v_file_name,instr(v_file_name,'/')+1),chr(10),null),chr(13),null)|| '"');
htp.p('Content-Disposition: attatchment; filename="'||v_file_name||'.pdf'||'"');
-- close the headers
owa_util.http_header_close;
-- download the BLOB
wpg_docload.download_file( Lob_loc );
end DOWNLOAD_LIST;
Any help?
I think there is a slight issue with your content-length:
This is code I have in production and it does show a .pdf file properly using the browser built-in viewer:
PROCEDURE PR_SHOW_REPORT(io_blReport IN OUT BLOB,
i_vcContentDisposition IN VARCHAR2 DEFAULT 'inline',
i_vcFilename IN VARCHAR2 DEFAULT 'reportresult.pdf') IS
l_mime VARCHAR2 (255);
l_length NUMBER;
l_file_name VARCHAR2 (2000);
lob_loc BLOB;
BEGIN
OWA_UTIL.mime_header ('application/pdf', FALSE);
HTP.p ('Content-Length: ' || DBMS_LOB.GETLENGTH(io_blReport));
HTP.p ('Content-Disposition: ' || i_vcContentDisposition ||'; filename="' || i_vcFilename || '"');
OWA_UTIL.http_header_close;
WPG_DOCLOAD.download_file(io_blReport);
END;
It is not that simple; requires you to take some additional steps, as described in Creating PDF Reports with Oracle Application Express 5.0 and Oracle REST Data Services. Have a look, that tutorial takes 20 minutes to complete.

location of FND_FILE log file

I create a log file in my procedure:
v_log_file VARCHAR2 (250) := FND_FILE.LOG;
and during my procedure I write in this file :
FND_FILE.PUT_LINE (
v_log_file,
'### start');
How can I see my log file to check if it's written correctly? Where can I find my log file?
You can use DBMS_OUTPUT.PUT_LINE instead to view it in SQL developer. Use the below code before compiling your anonymous block.
SET SERVEROUTPUT ON;

PL/SQL Oracle Directory

I am using util_file.fopen to import a .txt file into a database. However, I do not want hardcode the directory. Is there a way save the current directory to a variable or log the path? That way I can create an oracle directory that is the current directory, and util_file.fopen will always open the .txt file that is in the directory that I am running my pl/sql from
I know that "HOST CD" will show me my current directory, but I have not been able to save it to a variable or log it
Thanks
Create multiple directory objects:
CREATE DIRECTORY DIRECTORY_1 AS '/some/path';
CREATE DIRECTORY DIRECTORY_2 AS '/some/other/path';
CREATE DIRECTORY DIRECTORY_3 AS '/yet/another/path';
Assign the name of the directory to a variable:
strDirectory_to_use := 'DIRECTORY_1';
Use the variable when opening a file:
-- References /some/path/filename.txt
aFile := UTL_FILE.FOPEN(strDirectory_to_use, 'filename.txt', 'r');
Change the variable to contain the name of a different directory object:
strDirectory_to_use := 'DIRECTORY_2';
Now when you use the variable in a call to UTL_FILE.FOPEN it will look at the directory pointed to by directory object DIRECTORY_2:
-- References /some/other/path/filename.txt
aFile := UTL_FILE.FOPEN(strDirectory_to_use, 'filename.txt', 'r');
Best of luck.
If you want to use current working directory you can create that directory dinamically. Problem is when multiple processes try to access your procedure.
If you can ensure that only one process is using procedure at same time you can do:
create or replace procedure (mypath varchar2) as
begin
execute immediate 'CREATE OR REPLACE DIRECTORY DIRECTORY_1 AS ' || mypath;
aFile := UTL_FILE.FOPEN(DIRECTORY_1, 'filename.txt', 'r');
end;
/
If you can't ensure that only one thread will call procedure at same time it gets tricky. You can try to lookup directory.
create or replace procedure (mypath varchar2) as
dirname varchar2;
begin
select DIRECTORY_NAME into dirname from dba_directories where DIRECTORY_PATH = mypath;
if (dirname is null) then
dirname := substr(replace(replace(replace(replace(dirname,'\',''),':',''),'/',''),'.',''),1,30);
execute immediate 'CREATE OR REPLACE ' || dirname || ' AS ' || mypath;
end if;
aFile := UTL_FILE.FOPEN(dirname, 'filename.txt', 'r');
end;
/

/usr/tmp, default path in UTL_FILE

When i am searching for directories registered to UTL_DIR i am getting the following :
select value from v$parameter where name='utl_file_dir';
/usr/tmp, /usr/tmp, /oradata/hrtst/db/tech_st/11.2.0/appsutil/outbound/HRTS, /usr/tmp
Does this mean /usr/tmp is the directory for UTL_DIR ?
also i cannot search for /oradata/hrtst/db/tech_st/11.2.0/appsutil/outbound/HRTS through winscp or putty.
Also i created a directory like
create or replace directory MY_DIR as '/usr/tmp';
and then i tried to write in this folder :
DECLARE
fileHandler UTL_FILE.FILE_TYPE;
begin
fileHandler := UTL_FILE.FOPEN('MY_DIR', 'test_file.txt', 'W');
UTL_FILE.PUTF(fileHandler, 'Writing TO a file\n');
UTL_FILE.FCLOSE(fileHandler);
EXCEPTION
WHEN others THEN
raise_application_error(-20000, 'ERROR: Invalid PATH FOR file.');
END;
anonymous block completed
though this block got executed succesfuly but no file got created in the directory when i checked.

Cancel SQL *PLUS Execution without raising an error

i have a tricky SQL Problem:
We have a huge SQL Script which installs our application on the DB server.
We want to skip the database installation if the latest update didn't change anything in the DB.
I have implemented following check, which is executed before the other SQL commands:
check_current_version_delta.sql:
DECLARE
v_deploy_version VARCHAR2(30) := '&db_deploy_version';
v_check BOOLEAN := FALSE;
BEGIN
DBMS_OUTPUT.PUT_LINE( '--------------------------------------------------------------------------------');
DBMS_OUTPUT.PUT_LINE( 'Check if we have a new DB version');
DBMS_OUTPUT.PUT_LINE( '--------------------------------------------------------------------------------');
FOR cu_version IN (SELECT version FROM &DB_CURRENT_USER..db_deployment WHERE version = v_deploy_version AND ROWNUM = 1) LOOP
v_check := TRUE;
END LOOP;
IF v_check THEN
RAISE_APPLICATION_ERROR( -20001, 'DB Version: '||v_deploy_version||' is already installed');
END IF;
END;
/
This is working very well but our installation team complains about the ORA-XXXXX Error in the log, because they have automated error checks this installation is marked as FAIL (though there was no actual error)
So now the actual problem:
I need to cancel the execution of the SQL without any errors in the LOG. Is this even possible?
Alternative would be to make the rest of the installation dependent on the outcome of the script above. But i'm not sure how to accomplish that.
Have you some suggestions on how to handle it the good way?
One possible way is to create three scripts: The first checks for the condition and either calls the second or the third. The second does the real job. The third is an empty dummy, to avoid the error message cause by calling a non-existent script
In code, it looks like this:
col SCRIPT1_COL new_val SCRIPT1
SELECT case
when version = '&db_deploy_version' then 'dummy.sql'
else 'upgrade_db.sql'
end as SCRIPT1_COL
FROM &DB_CURRENT_USER..db_deployment;
#&SCRIPT1
Alternatively, you could use the method shown above to load either a script "dummy.sql" that does nothing or a script "exit.sql" that just contains the exit command, and execute it before doing the real job.
Presumably you're already using whenever sqlerror so make it terminate when you raise that exception, and you're redirecting the output to your log file. If so you can just hide the text of the exception with set termout off:
whenever sqlerror exit success
set termout off
DECLARE
...
BEGIN
...
IF v_check THEN
RAISE_APPLICATION_ERROR( -20001,
'DB Version: '||v_deploy_version||' is already installed');
END IF;
END;
/
set termout on
whenever sqlerror exit failure
... the rest of your script
The script will stop if the exception is raised but produce no output. The success means anything that runs this won't decide it has errored independently of the log; the exit code from sqlplus will be zero.
You may be spooling to output instead; in which case just don't start the spool until after your check. Or if you have things before this that you do have to spool, turn the spool off and then on again afterwards with append.