UTL_FILE package
1. Purpose
The UTL_FILE package reads and writes text files on the server from PL/iSQL. It also provides procedures to inspect, copy, remove, and rename files. FOPEN returns a sys.ORA_UTL_FILE_FILE_TYPE handle for subsequent read, write, and close operations.
2. Feature Description
2.1. Security prerequisites
UTL_FILE uses the sys.utl_file_directory table to restrict access to directories. Register a directory in this table before using file operations.
CREATE TABLE sys.utl_file_directory(
dirname name PRIMARY KEY,
dir TEXT
);
-
Unprivileged users have
SELECTonsys.utl_file_directoryonly; adding or deleting registered directories requires superuser privileges. This corresponds to Oracle’sCREATE DIRECTORYprivilege, which is granted only toSYSandSYSTEMby default. -
Register a directory before use, then reference it by its
dirname:
-- register the data directory as a directory object named 'data_directory'
INSERT INTO sys.utl_file_directory(dirname, dir)
VALUES ('data_directory', current_setting('data_directory'));
-
The
locationparameter may be either a registereddirnameor a raw path. Raw paths are canonicalized and must fall under one of the registered directories (prefix match); otherwise the operation fails withINVALID_PATH. -
As in Oracle, a subdirectory of an accessible directory is not automatically accessible; it must be registered with a complete path of its own.
-
File permission mask: files created by
FOPENare subject to theutl_file.umaskparameter (default0077). Only superusers can change it, and the value must be 3–4 octal digits:
SET utl_file.umask = '0022';
SHOW utl_file.umask;
2.2. Functions and procedures
| Call | Return type | Description |
|---|---|---|
|
|
Open a file for input or output. |
|
|
Open a file in Unicode mode for input or output; the file is read and written in UTF-8 instead of the database character set. Same parameters as |
|
|
Determine whether the file handle refers to a file that has been opened but not yet closed |
|
— |
Close an open file identified by a file handle |
|
— |
Close all open file handles for the session; an emergency cleanup procedure, e.g. when a PL/iSQL program exits on an exception |
|
— |
Physically write all pending output to the file; useful when the file must be read while it is still open (e.g. debug messages) |
|
|
Return the current relative offset position within the file, in bytes; |
|
— |
Adjust the file pointer forward or backward within the file by the number of bytes specified. |
|
— |
Read text up to, but not including, the line terminator, the end of file, or |
|
— |
Read text in Unicode from a file opened by |
|
— |
Write one or more operating system-specific line terminators (default 1). Separate from |
|
— |
Write the string in |
|
— |
A |
|
— |
Write the line to the file and append the platform-specific line terminator; |
|
— |
Write a Unicode line to a file opened by |
|
— |
Write a |
|
— |
Copy a contiguous portion of a file to a newly created file. By default the whole file is copied; |
|
— |
Delete a disk file, assuming sufficient privileges; the operating system verifies file and directory permissions |
|
— |
Rename a file to a new name, similar to the UNIX |
|
— |
Read and return the attributes of a disk file: existence, length in bytes ( |
Not yet implemented compared with Oracle: GET_RAW, PUT_NCHAR, PUTF_NCHAR, and the byte (rb/wb/ab) open modes.
The file handle type corresponds field-by-field to Oracle’s private FILE_TYPE record; its contents should not be referenced or changed by the user:
CREATE TYPE sys.ORA_UTL_FILE_FILE_TYPE AS(id INTEGER, datatype INTEGER, byte_mode BOOLEAN);
2.3. Syntax
UTL_FILE subprograms are typically called from PL/iSQL anonymous blocks:
DECLARE
f sys.ora_utl_file_file_type;
line TEXT;
BEGIN
f := UTL_FILE.FOPEN('data_directory', 'regress.txt', 'W');
UTL_FILE.PUT_LINE(f, 'abc');
UTL_FILE.PUT_LINE(f, '-----');
UTL_FILE.FCLOSE(f);
f := UTL_FILE.FOPEN('data_directory', 'regress.txt', 'R');
UTL_FILE.GET_LINE(f, line);
WHILE line IS NOT NULL LOOP
RAISE NOTICE '>>%<<', line;
UTL_FILE.GET_LINE(f, line);
END LOOP;
UTL_FILE.FCLOSE(f);
END;
/
In Oracle compatibility mode (ivorysql.compatible_mode = oracle) the package can be used directly. As in Oracle, the file location and file name are supplied as separate strings so the location can be checked against the registry; together they must represent a legal filename on the system.
2.4. Open modes
Following Oracle’s FOPEN definition:
| Mode | Description | Notes |
|---|---|---|
|
Read text |
The file must exist |
|
Write text, truncating |
Creates the file if it does not exist, otherwise empties it |
|
Append text |
Writes are added at the end of the file; a missing file is created, which matches Oracle’s note that append mode creates the file in write mode |
The mode is case-insensitive ('r', 'w', 'a' are accepted); any other value raises INVALID_MODE. Oracle additionally supports the byte modes rb, wb, and ab; these are not yet supported by IvorySQL.
2.5. Operational notes
The following rules are inherited from Oracle’s Operational Notes and Rules and Limits for UTL_FILE:
-
Bytes returned by GET_LINE are the lesser of: the
GET_LINElenparameter, the number of bytes until the next line terminator, and themax_linesizespecified byFOPEN. The line terminator itself is not read into the buffer, so reading blank lines returns empty strings. -
max_linesize must be in the range 1–32767; if unspecified, a default value of 1024 is supplied. The
GET_LINElenparameter follows the same range; whenmax_linesizeandlendiffer, the lesser value takes precedence. -
Character sets: files opened by
FOPENare expected to be encoded in the database character set, files opened byFOPEN_NCHARin UTF-8. Reading a file in an unexpected character set gives indeterminate results. -
Sequential
PUToutput should not exceed the line limit between flushes; exceedingmax_linesizeraisesVALUE_ERROR("buffer is too short"). -
Open-file limit: a session can have at most 50 files open simultaneously (same as Oracle). Beyond that,
FOPENfails with a "program limit exceeded" error. -
Operating system-specific parameters (e.g. environment variables) cannot be used in the file location or file name parameters.
3. Syntax Examples
Writing and reading a file line by line:
DECLARE
f sys.ora_utl_file_file_type;
line TEXT;
i INTEGER;
BEGIN
f := UTL_FILE.FOPEN('data_directory', 'regress.txt', 'W');
UTL_FILE.PUT_LINE(f, 'abc');
UTL_FILE.PUT_LINE(f, '123'::numeric);
UTL_FILE.NEW_LINE(f, 2);
UTL_FILE.PUT(f, 'a');
UTL_FILE.PUT(f, 'b');
UTL_FILE.NEW_LINE(f);
UTL_FILE.PUTF(f, '[1=%s, 2=%s]', 'one', 'two');
UTL_FILE.NEW_LINE(f);
UTL_FILE.FCLOSE(f);
f := UTL_FILE.FOPEN('data_directory', 'regress.txt', 'R');
i := 1;
UTL_FILE.GET_LINE(f, line);
WHILE line IS NOT NULL LOOP
RAISE NOTICE '[%] >>%<<', i, line;
UTL_FILE.GET_LINE(f, line);
i := i + 1;
END LOOP;
UTL_FILE.FCLOSE(f);
EXCEPTION
WHEN OTHERS THEN
RAISE NOTICE 'exception: %', sqlerrm;
UTL_FILE.FCLOSE_ALL();
END;
/
Output:
NOTICE: [1] >>abc<<
NOTICE: [2] >>123<<
NOTICE: [3] >><<
NOTICE: [4] >>ab<<
NOTICE: [5] >>[1=one, 2=two]<<
The classic PUTF example from the Oracle documentation writes Hello, world!\nI come from Zork with greetings for all earthlings.:
DECLARE
my_world VARCHAR2 := 'Zork';
f sys.ora_utl_file_file_type;
BEGIN
f := UTL_FILE.FOPEN('data_directory', 'zork.txt', 'W');
UTL_FILE.PUTF(f, 'Hello, world!\nI come from %s with %s.\n',
my_world,
'greetings for all earthlings');
UTL_FILE.FCLOSE(f);
END;
/
File attributes, copy, remove, and rename:
DECLARE
fexists BOOLEAN;
file_length NUMBER;
block_size INTEGER;
BEGIN
UTL_FILE.FCOPY('data_directory', 'regress.txt', 'data_directory', 'regress2.txt');
UTL_FILE.FGETATTR('data_directory', 'regress2.txt', fexists, file_length, block_size);
RAISE NOTICE 'fexists = %, file_length = %, block_size = %', fexists, file_length, block_size;
UTL_FILE.FREMOVE('data_directory', 'regress2.txt');
UTL_FILE.FGETATTR('data_directory', 'regress2.txt', fexists, file_length, block_size);
RAISE NOTICE 'fexists = %', fexists;
UTL_FILE.FRENAME('data_directory', 'regress.txt', 'data_directory', 'regress2.txt', TRUE);
END;
/
Output:
NOTICE: fexists = t, file_length = 24, block_size = 4096
NOTICE: fexists = f
The max_linesize/len precedence example from the Oracle documentation — GET_LINE’s `len request exceeds FOPEN’s `max_linesize, so the number of bytes returned is bounded by the smaller value:
DECLARE
v1 TEXT;
f1 sys.ora_utl_file_file_type;
BEGIN
-- MAX_LINESIZE (256) is less than GET_LINE's length request (32767),
-- so the number of bytes returned will be 256 or less if a line terminator is seen.
f1 := UTL_FILE.FOPEN('data_directory', 'u12345.tmp', 'R', 256);
UTL_FILE.GET_LINE(f1, v1, 32767);
UTL_FILE.FCLOSE(f1);
-- FOPEN's MAX_LINESIZE defaults to 1024,
-- so the number of bytes returned will be 1024 or less if a line terminator is seen.
f1 := UTL_FILE.FOPEN('data_directory', 'u12345.tmp', 'R');
UTL_FILE.GET_LINE(f1, v1, 32767);
UTL_FILE.FCLOSE(f1);
-- GET_LINE doesn't specify a number of bytes, so it defaults to
-- FOPEN's MAX_LINESIZE, which in turn defaults to 1024.
f1 := UTL_FILE.FOPEN('data_directory', 'u12345.tmp', 'R');
UTL_FILE.GET_LINE(f1, v1);
UTL_FILE.FCLOSE(f1);
END;
/
FFLUSH, FSEEK, and FGETPOS work together for write-then-reread scenarios: writes become visible to other handles only after FFLUSH, and FSEEK can jump to a saved offset:
DECLARE
f sys.ora_utl_file_file_type;
f1 sys.ora_utl_file_file_type;
line TEXT;
line2_pos INTEGER;
BEGIN
f := UTL_FILE.FOPEN('data_directory', 'regressflush.txt', 'W');
f1 := UTL_FILE.FOPEN('data_directory', 'regressflush.txt', 'R');
FOR i IN 1..5 LOOP
UTL_FILE.PUT_LINE(f, 'line ' || i::text);
END LOOP;
UTL_FILE.FFLUSH(f); -- make buffered writes visible
UTL_FILE.FSEEK(f1); -- reset read position to 0
UTL_FILE.GET_LINE(f1, line);
line2_pos := UTL_FILE.FGETPOS(f1); -- remember the offset of line 2
WHILE line IS NOT NULL LOOP
RAISE NOTICE '>>%<<', line;
UTL_FILE.GET_LINE(f1, line);
END LOOP;
UTL_FILE.FSEEK(f1, line2_pos, NULL); -- jump back to line 2 (absolute)
UTL_FILE.GET_LINE(f1, line);
RAISE NOTICE '>>%<<', line;
UTL_FILE.FSEEK(f1, NULL, -7); -- move back one record (relative)
UTL_FILE.GET_LINE(f1, line);
RAISE NOTICE '>>%<<', line;
UTL_FILE.FCLOSE_ALL();
END;
/
FSEEK makes it possible to read previous lines without first closing and reopening the file — you must know the number of bytes by which to navigate. If the beginning of the file is reached before the requested number of bytes, the file pointer is placed at the beginning of the file; if the end of the file is reached first, INVALID_OFFSET is raised.
4. Exceptions
UTL_FILE raises Oracle-style exceptions, which can be caught with WHEN OTHERS and inspected via SQLERRM. The exception set follows Oracle’s UTL_FILE Exceptions table:
| Exception | Description |
|---|---|
|
File location is invalid |
|
The |
|
File handle is invalid |
|
File could not be opened or operated on as requested, e.g. reading from a handle opened in |
|
Destination buffer too small, or an operating system error occurred during the read operation |
|
An operating system error occurred during the write operation; also raised when |
|
Unspecified PL/iSQL error |
|
A file is opened using |
|
The requested operation failed because the file is open |
|
The |
|
The |
|
Permission to access the file location is denied |
|
|
|
The requested file delete operation failed |
|
The requested file rename operation failed |
|
Predefined exception; see the note on end-of-file behavior below |
|
Predefined exception; raised when written data exceeds |
Procedures in UTL_FILE can also raise other predefined PL/iSQL exceptions.
End-of-file behavior: when GET_LINE reads past the end of the file, Oracle raises NO_DATA_FOUND. IvorySQL instead logs the condition at LOG level (no data found) and returns NULL, so the WHILE line IS NOT NULL loop pattern works naturally:
DECLARE
f sys.ora_utl_file_file_type;
line TEXT;
BEGIN
f := UTL_FILE.FOPEN('data_directory', 'regress.txt', 'R');
UTL_FILE.GET_LINE(f, line);
WHILE line IS NOT NULL LOOP
RAISE NOTICE '>>%<<', line;
UTL_FILE.GET_LINE(f, line);
END LOOP;
UTL_FILE.FCLOSE(f);
END;
/
Error handling example:
DECLARE
f sys.ora_utl_file_file_type;
BEGIN
-- 'wrong_directory' is not registered, raises INVALID_PATH
f := UTL_FILE.FOPEN('wrong_directory', 'regress.txt', 'A', 1024);
END;
/
ERROR: INVALID_PATH
DETAIL: File location is invalid.
HINT: locality is not found in sys.utl_file_directory table
5. Differences from Oracle
The API is aligned with Oracle, with the following known differences:
| Area | IvorySQL behavior |
|---|---|
Directory objects |
Uses the |
End of file |
|
Byte modes |
|
Missing subprograms |
|
|
Resets the file position to 0; Oracle raises |
|
|
|
After |
Exception set |
Exceptions not specifically detected by the implementation ( |
File ownership |
On UNIX, files created by |
6. Transaction and session lifecycle
File handles survive COMMIT but are automatically closed when the transaction rolls back or the session terminates, so buffered data is not silently lost:
BEGIN
f := UTL_FILE.FOPEN('data_directory','regress.txt','A',1024);
RAISE NOTICE 'is_open = %', UTL_FILE.IS_OPEN(f); -- t
COMMIT;
RAISE NOTICE 'is_open = %', UTL_FILE.IS_OPEN(f); -- t
ROLLBACK;
RAISE NOTICE 'is_open = %', UTL_FILE.IS_OPEN(f); -- f
END;
/
7. Implementation notes
For the security model, handle management, and internal design, see UTL_FILE implementation design.