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 SELECT on sys.utl_file_directory only; adding or deleting registered directories requires superuser privileges. This corresponds to Oracle’s CREATE DIRECTORY privilege, which is granted only to SYS and SYSTEM by 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 location parameter may be either a registered dirname or a raw path. Raw paths are canonicalized and must fall under one of the registered directories (prefix match); otherwise the operation fails with INVALID_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 FOPEN are subject to the utl_file.umask parameter (default 0077). 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

FOPEN(location, filename, open_mode [, max_linesize])

ORA_UTL_FILE_FILE_TYPE

Open a file for input or output. open_mode is one character: R (read), W (write, truncate), A (append). max_linesize defaults to 1024, range 1–32767

FOPEN_NCHAR(location, filename, open_mode [, max_linesize])

ORA_UTL_FILE_FILE_TYPE

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 FOPEN

IS_OPEN(file)

BOOLEAN

Determine whether the file handle refers to a file that has been opened but not yet closed

FCLOSE(file)

—

Close an open file identified by a file handle

FCLOSE_ALL

—

Close all open file handles for the session; an emergency cleanup procedure, e.g. when a PL/iSQL program exits on an exception

FFLUSH(file)

—

Physically write all pending output to the file; useful when the file must be read while it is still open (e.g. debug messages)

FGETPOS(file)

INTEGER

Return the current relative offset position within the file, in bytes; 0 means the beginning of the file

FSEEK(file [, absolute_offset [, relative_offset]])

—

Adjust the file pointer forward or backward within the file by the number of bytes specified. absolute_offset is a byte position counted from the beginning of the file; relative_offset seeks forward (positive) or backward (negative) from the current position; with both omitted IvorySQL resets the position to 0

GET_LINE(file, buffer OUT, [len])

—

Read text up to, but not including, the line terminator, the end of file, or len bytes — whichever comes first — into buffer. len defaults to max_linesize; if both are given the lesser value takes precedence. Returns NULL at end of file

GET_LINE_NCHAR(file, buffer OUT, [len])

—

Read text in Unicode from a file opened by FOPEN_NCHAR

NEW_LINE(file [, lines])

—

Write one or more operating system-specific line terminators (default 1). Separate from PUT because the line terminator is a platform-specific character sequence

PUT(file, buffer)

—

Write the string in buffer to the file without appending a line terminator; use NEW_LINE or PUT_LINE to terminate the line

PUTF(file, format [, arg1..arg5])

—

A PUT with formatting, like a limited printf(). %s in format is replaced by arg1–arg5 in order, \n by the platform line terminator, %% by a literal % (IvorySQL extension). If there are more %s formatters than arguments, an empty string is substituted

PUT_LINE(file, buffer [, autoflush])

—

Write the line to the file and append the platform-specific line terminator; autoflush = TRUE flushes the buffer to disk after the write

PUT_LINE_NCHAR(file, buffer)

—

Write a Unicode line to a file opened by FOPEN_NCHAR; appends the line terminator

PUT_RAW(file, buffer [, autoflush])

—

Write a BYTEA value (the counterpart of Oracle RAW) to the file without appending a line terminator; autoflush = TRUE flushes after writing

FCOPY(src_location, src_filename, dest_location, dest_file [, start_line [, end_line]])

—

Copy a contiguous portion of a file to a newly created file. By default the whole file is copied; start_line (default 1) and end_line (default: end of file) select a portion from the source file. The source is opened in read mode, the destination in write mode

FREMOVE(location, filename)

—

Delete a disk file, assuming sufficient privileges; the operating system verifies file and directory permissions

FRENAME(src_location, src_filename, dest_location, dest_filename [, overwrite])

—

Rename a file to a new name, similar to the UNIX mv function. overwrite defaults to FALSE; if the destination exists and overwrite is FALSE, WRITE_ERROR is raised

FGETATTR(location, filename, fexists OUT, file_length OUT, block_size OUT)

—

Read and return the attributes of a disk file: existence, length in bytes (NULL if the file does not exist), and file system block size (NULL if the file does not exist)

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

R

Read text

The file must exist

W

Write text, truncating

Creates the file if it does not exist, otherwise empties it

A

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_LINE len parameter, the number of bytes until the next line terminator, and the max_linesize specified by FOPEN. 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_LINE len parameter follows the same range; when max_linesize and len differ, the lesser value takes precedence.

  • Character sets: files opened by FOPEN are expected to be encoded in the database character set, files opened by FOPEN_NCHAR in UTF-8. Reading a file in an unexpected character set gives indeterminate results.

  • Sequential PUT output should not exceed the line limit between flushes; exceeding max_linesize raises VALUE_ERROR ("buffer is too short").

  • Open-file limit: a session can have at most 50 files open simultaneously (same as Oracle). Beyond that, FOPEN fails 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

INVALID_PATH

File location is invalid

INVALID_MODE

The open_mode parameter in FOPEN is invalid

INVALID_FILEHANDLE

File handle is invalid

INVALID_OPERATION

File could not be opened or operated on as requested, e.g. reading from a handle opened in W/A mode

READ_ERROR

Destination buffer too small, or an operating system error occurred during the read operation

WRITE_ERROR

An operating system error occurred during the write operation; also raised when FRENAME finds the destination file exists and overwrite is FALSE

INTERNAL_ERROR

Unspecified PL/iSQL error

CHARSETMISMATCH

A file is opened using FOPEN_NCHAR, but later I/O operations use nonchar functions such as PUTF or GET_LINE

FILE_OPEN

The requested operation failed because the file is open

INVALID_MAXLINESIZE

The max_linesize value for FOPEN() is invalid; it should be within the range 1 to 32767

INVALID_FILENAME

The filename parameter is invalid

ACCESS_DENIED

Permission to access the file location is denied

INVALID_OFFSET

absolute_offset < 0, or an offset causes a seek past the end of the file

DELETE_FAILED

The requested file delete operation failed

RENAME_FAILED

The requested file rename operation failed

NO_DATA_FOUND

Predefined exception; see the note on end-of-file behavior below

VALUE_ERROR

Predefined exception; raised when written data exceeds max_linesize

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 sys.utl_file_directory table instead of Oracle’s CREATE DIRECTORY/ALL_DIRECTORIES. A raw path under a registered directory is also accepted

End of file

GET_LINE returns NULL at EOF; Oracle raises NO_DATA_FOUND

Byte modes

rb/wb/ab open modes are not supported; INVALID_MODE is raised. The byte_mode field exists in the handle type for future use

Missing subprograms

GET_RAW, PUT_NCHAR, PUTF_NCHAR are not yet implemented

FSEEK with both offsets NULL

Resets the file position to 0; Oracle raises INVALID_OFFSET

PUTF format strings

%% is supported as a literal % (an IvorySQL extension); unmatched %s formatters are replaced by an empty string, same as Oracle

FCLOSE_ALL and IS_OPEN

After FCLOSE_ALL, IS_OPEN returns FALSE in IvorySQL; Oracle keeps reporting TRUE for the untouched handle

Exception set

Exceptions not specifically detected by the implementation (ACCESS_DENIED, DELETE_FAILED, RENAME_FAILED, FILE_OPEN, CHARSETMISMATCH, INVALID_FILENAME, INTERNAL_ERROR) surface as the closest Oracle exception, typically INVALID_PATH/INVALID_OPERATION/READ_ERROR/WRITE_ERROR with the operating system error text as DETAIL

File ownership

On UNIX, files created by FOPEN are owned by the user running the database server, as in Oracle; their permissions are masked by utl_file.umask

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.