UTL_FILE Package

1. Overview and Scope

UTL_FILE provides PL/iSQL operations on files on the database server, including text input and output, file positioning, attribute queries, copying, deletion, and renaming. Files are accessed by the database server process, and paths refer to the server’s file system rather than the client’s file system.

The examples use Linux, a UTF8 database, and the psql client supplied with IvorySQL, connected through the Oracle compatibility port. Oracle’s full set of interfaces, exceptions, and boundary behaviors must not be assumed to apply to this implementation.

2. Prerequisites

2.1. Directory Registration and Permissions

The sys.utl_file_directory table is created when ivorysql_ora is installed; applications do not need to create it again. Its two columns, dirname name PRIMARY KEY and dir text, store a directory alias and the corresponding directory path on the server.

By default, PUBLIC has SELECT permission on this table but no write permissions. Directories can be registered by the table owner, a superuser, or a role explicitly granted the necessary table permissions; modifying directory registrations is not restricted to superusers. Registering a directory neither creates the operating system directory nor changes its permissions.

Paths are resolved as follows:

  • location is first looked up as a directory alias in dirname. If no alias matches, it is treated as a path. Aliases are matched against their stored strings; all examples use lowercase aliases.

  • After the directory and filename are joined and the resulting path is normalized, the full file path is checked for a prefix consisting of a registered dir followed by a directory separator. Registering dir as a normalized absolute path is recommended.

  • This check permits access to subdirectories of a registered directory. Subdirectories must already exist but do not need separate registration; filename can also include subdirectory components. A sibling directory with a similar name does not gain access merely because its name shares a prefix.

  • After .. components are normalized, the final path must still fall within a registered directory. The implementation checks path strings without resolving symbolic links through realpath(), so the registration table must not be regarded as a file system sandbox that isolates symbolic link targets.

  • Environment variables and ~ are not expanded. Actual read and write access also depends on the file system permissions of the operating system user running the database.

The registration table does not provide a model for granting directory READ and WRITE permissions separately to each database user. Do not register the database data directory as a general application working directory; this document uses a separate example directory.

2.2. File Handles

In PL/iSQL, declare variables using the package type UTL_FILE.FILE_TYPE. Both FOPEN and FOPEN_NCHAR return this type. Do not create or reference sys.ORA_UTL_FILE_FILE_TYPE; that SQL type does not exist in the current installation.

The package record contains id INTEGER, datatype INTEGER, and byte_mode BOOLEAN. These fields are for internal use. Applications should pass the entire record as a handle and should not modify or persist its fields to reconstruct a handle. A handle is valid only in the database session that created it. Each session can hold at most 50 open file handles at a time.

IS_OPEN checks whether a handle is still present in the current session’s open file table. FCLOSE closes a single handle; FCLOSE_ALL() closes all file handles in the current session. After either operation, IS_OPEN returns FALSE. Reading, writing, or closing an already closed handle raises INVALID_FILEHANDLE.

2.3. Permissions for Newly Created Files

When creating a new file, FOPEN and FOPEN_NCHAR temporarily apply utl_file.umask, whose default value is '0077'. Under the ordinary Linux permission model, new files typically have mode 0600 and are owned by the operating system user running the database. File system ACLs and other factors can also affect the final permissions. Opening an existing file does not change its permissions.

The current setting validation requires superuser privileges and accepts one to four octal digits, such as '77', '077', and '0077'; values are not restricted to three or four digits. An explicit four-digit form is recommended. FCOPY creates its destination through a separate fopen() code path that does not temporarily apply utl_file.umask, so its file permissions must not be assumed to match those of a file created by FOPEN.

3. Interface Reference

The following are the package’s public interfaces. Entries with an explicit return type are functions; all other entries are procedures. String parameters use VARCHAR2, except that the output buffers of GET_LINE and GET_LINE_NCHAR and the input buffer of PUT_LINE_NCHAR use TEXT. All file handle parameters use UTL_FILE.FILE_TYPE.

3.1. Opening, Closing, Flushing, and Positioning

Interface Description

FOPEN(location, filename, open_mode, max_linesize DEFAULT 1024) RETURN UTL_FILE.FILE_TYPE

Reads and writes text in the database character set. max_linesize is an INTEGER in the range 1–32767. Omitting it uses 1024; explicitly passing NULL raises an error.

FOPEN_NCHAR(location, filename, open_mode, max_linesize DEFAULT 1024) RETURN UTL_FILE.FILE_TYPE

Uses UTF8 as the file encoding, converting to and from the database character set during input and output. All other parameter rules are the same as for FOPEN.

IS_OPEN(file) RETURN BOOLEAN

Checks whether the handle is still open.

FCLOSE(file IN OUT)

Closes the file and releases the handle slot. The package body does not clear the fields in the caller’s record, but the handle is no longer valid.

FCLOSE_ALL()

Closes all open files in the current session and releases all slots.

FFLUSH(file)

Calls the C standard library function fflush() to submit buffered writes from user space to the operating system. It does not call fsync() and does not guarantee that data has been persisted to physical storage.

FGETPOS(file) RETURN INTEGER

Returns the current byte offset from the beginning of the file, where the initial position is 0. The return type is a 32-bit INTEGER, so this interface is unsuitable for file offsets beyond its representable range.

FSEEK(file IN OUT, absolute_offset DEFAULT NULL, relative_offset DEFAULT NULL)

Both offset parameters are INTEGER. Absolute offsets are measured from the beginning of the file; relative offsets are measured from the current position. If both are non-null, the absolute offset takes precedence. If both are null, INVALID_OFFSET is raised.

Open modes accept a single character and are case-insensitive:

Mode Behavior

R / r

Read only; the file must already exist.

W / w

Write only; an existing file is immediately truncated, and a missing file is created.

A / a

Append; a missing file is created. Even after a seek, subsequent writes remain subject to the operating system’s append mode.

Modes such as rb, wb, ab, and r+ are not supported.

The valid target range for FSEEK is [0, file length], including the exact EOF position. A negative absolute offset, a relative move before the beginning of the file, or a move beyond EOF raises INVALID_OFFSET; the position is not automatically clamped to a file boundary. These out-of-range parameter errors leave the current position unchanged.

Before seeking, the implementation flushes the stream and measures the file length. A seek can therefore target content already written through the current handle even if it has not been explicitly flushed. To return to the beginning of the file, call FSEEK(f, 0); do not omit both offsets.

3.2. Text Input and Output and Raw Byte Output

Interface Description

GET_LINE(file, buffer OUT TEXT, len DEFAULT NULL)

Reads a text fragment and removes any line terminator encountered. len is an INTEGER and, when non-null, must be in the range 1–32767. If omitted or NULL, it uses the max_linesize specified when the file was opened. Raises NO_DATA_FOUND when EOF is reached without reading any characters.

GET_LINE_NCHAR(file, buffer OUT TEXT, len DEFAULT NULL)

Uses the same reading implementation as GET_LINE; the actual file encoding is taken from the encoding saved when the handle was opened.

PUT(file, buffer)

Writes text without appending a newline. The input length for this call is checked in bytes after conversion to the file encoding.

PUT_LINE(file, buffer, autoflush DEFAULT FALSE)

Writes text and appends one line terminator. autoflush is a BOOLEAN; TRUE triggers a flush, and an explicit NULL is treated as FALSE.

PUT_LINE_NCHAR(file, buffer TEXT)

Writes text, appends a line terminator, and flushes the stream. The package body always passes TRUE for autoflush; this interface has no third parameter.

NEW_LINE(file, lines DEFAULT 1)

Writes lines line terminators. lines is an INTEGER; omitting it or passing NULL writes one terminator, while zero or a negative value writes nothing.

PUTF(file, format, arg1 DEFAULT NULL, arg2 DEFAULT NULL, arg3 DEFAULT NULL, arg4 DEFAULT NULL, arg5 DEFAULT NULL)

Writes formatted text without automatically appending a newline. Supports %s, %%, and the two-character sequence consisting of a backslash followed by n in the format string, as described below.

PUT_RAW(file, buffer BYTEA, autoflush DEFAULT FALSE)

Writes BYTEA data directly, without character set conversion or an appended newline. Flushes when autoflush is TRUE. The current implementation does not check the length of this write against max_linesize.

3.2.1. Read Boundaries

Each GET_LINE call reads at most min(len, max_linesize) bytes in the file encoding. If len is null, the limit is max_linesize. Encountering LF, CRLF, or a standalone CR ends the read, and the terminator is excluded from the returned value.

  • Reading an empty line returns a zero-length TEXT value. In the environment verified for this document, that value is not NULL. End a reading loop by catching NO_DATA_FOUND, rather than relying on line IS NULL.

  • If the final text fragment has no terminating newline, that fragment is returned first; the next read raises NO_DATA_FOUND. An empty file raises this exception on the first read.

  • A long line does not raise READ_ERROR merely because it exceeds the current read limit; it is returned across multiple calls. If the byte limit is reached just before the newline is consumed, the next call consumes that newline and returns an empty string. A verified example of this boundary appears below.

  • Lengths are measured in bytes, not characters. If the limit splits a multibyte character, such as a UTF8 character, character set validation can raise an encoding error. Avoid choosing a len so small that it splits multibyte characters.

3.2.2. Write Lengths and Formatting

In the current implementation, max_linesize is not a limit on the cumulative length of a logical line across calls:

  • PUT, PUT_LINE, and PUT_LINE_NCHAR each check the encoded byte length of the text argument for that call. The newline automatically appended by PUT_LINE or PUT_LINE_NCHAR is excluded from this check.

  • Lengths are not accumulated across consecutive PUT calls, and flushing does not reset any accumulated length. Multiple valid calls can therefore produce a line longer than max_linesize.

  • PUTF checks the total number of bytes produced by one call, including substituted arguments and generated newlines. A newline does not reset the count. Exceeding the limit raises VALUE_ERROR, and any portion already written may remain in the file.

  • NEW_LINE does not perform this length check, and PUT_RAW is also exempt from it.

  • The buffer arguments of PUT, PUT_LINE, PUT_LINE_NCHAR, and PUT_RAW, and the format string of PUTF, must not be explicitly NULL.

Each %s in PUTF consumes the next of up to five arguments. An omitted or NULL argument produces no content; the sixth and subsequent %s directives also produce no content. %% writes one %. A backslash followed by n in the format string writes a newline; the same two characters inside a substituted argument are not interpreted again as a format directive. This is not a complete printf() implementation: %d, width, precision, and similar formats are not supported. The current implementation discards unknown two-character ASCII percent sequences such as %d, so applications should use only the explicitly supported directives.

Text output writes \n through a C text stream. Files in the Linux examples in this document use LF line endings. Although PUT_RAW writes bytes directly, it still uses the text stream opened by FOPEN; this does not imply support for portable binary open modes.

FOPEN_NCHAR selects UTF8 as the file encoding, but GET_LINE_NCHAR and PUT_LINE_NCHAR do not independently select an encoding. The package body does not check whether the handle’s datatype matches the NCHAR or ordinary interface, so mixing them does not specifically raise CHARSETMISMATCH. Applications should nevertheless use the corresponding interfaces consistently.

3.3. File Management

Interface Description

FCOPY(location, filename, dest_dir, dest_file, start_line DEFAULT 1, end_line DEFAULT 2147483647)

Copies text lines. Line numbers are INTEGER, start at 1, and include both endpoints. Omitted or explicitly NULL arguments use their respective defaults; nonpositive values raise an error. The destination is opened for writing, truncating any existing contents.

FREMOVE(location, filename)

Deletes the specified file using unlink(). Deleting a nonexistent file raises an error.

FRENAME(src_location, src_filename, dest_location, dest_filename, overwrite DEFAULT FALSE)

Renames or moves a file using rename(). overwrite is a BOOLEAN; an omitted or NULL value is treated as FALSE, in which case an existing destination raises WRITE_ERROR. TRUE permits replacing an existing destination, subject to operating system rules.

FGETATTR(location, filename, fexists OUT BOOLEAN, file_length OUT NUMBER, block_size OUT INTEGER)

Retrieves attributes using stat(). file_length is measured in bytes, and block_size is the st_blksize value returned by the system. Do not assume a fixed block size of 4096.

FCOPY recognizes LF as the line separator, preserves the copied text, and performs no character set conversion. It is not suitable for copying binary data containing NUL bytes. If start_line exceeds the number of lines in the file or is greater than end_line, the destination is still created or truncated, and the result is empty. Do not use the same file as both source and destination. Before copying a source that is still being written, flush or close its write handle.

Once the directory registration check passes, FGETATTR returns FALSE, NULL, NULL if stat() fails. This can mean either that the file does not exist or that its attributes cannot be retrieved because of permissions or another cause. Therefore, fexists = FALSE alone does not prove that the file is absent. Failure of the directory check still raises INVALID_PATH.

4. Runnable Examples

4.1. Preparing the Example Directory and Connection

Run the following examples in the order shown. On the server, create a separate directory as the operating system user running the database, then connect as a database user with write permission on the directory registration table. Port 1521 below is the Oracle compatibility port of the instance used for verification; adjust the port, database name, and user for other environments.

mkdir -p /tmp/ivorysql_utl_file_demo
/home/highgo/6.0/inst/bin/psql -X -h 127.0.0.1 -p 1521 -U highgo -d postgres

Run the subsequent code in this psql session. Use / on a line by itself to terminate a PL/iSQL anonymous block. When connecting through the PostgreSQL compatibility port, setting only the server’s ivorysql.compatible_mode does not ensure that the client correctly splits anonymous blocks; the psql parser must also be synchronized. These examples connect directly through the Oracle compatibility port.

\set ON_ERROR_STOP on
SET client_min_messages = notice;
SET standard_conforming_strings = on;
SHOW ivorysql.compatible_mode;
SHOW server_encoding;
SHOW utl_file.umask;

INSERT INTO sys.utl_file_directory(dirname, dir)
VALUES ('utl_file_demo', '/tmp/ivorysql_utl_file_demo');

The queried values in the verification environment were oracle, UTF8, and 0077, respectively. If a registration with the same name already exists, check its purpose first to avoid changing a directory used by another application.

Each functional example below creates and deletes its own files; the only shared prerequisite is the directory registration above. Expected output lists only NOTICE messages, omitting the psql line-number prefixes and command completion tags.

4.2. Writing, Appending, Formatting, and Reading Text Line by Line

DECLARE
    f UTL_FILE.FILE_TYPE;
    line TEXT;
    n INTEGER := 0;
BEGIN
    f := UTL_FILE.FOPEN('utl_file_demo', 'text.txt', 'W');
    UTL_FILE.PUT_LINE(f, 'abc');
    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, 'name=%s; ratio=100%%\n', 'IvorySQL');
    UTL_FILE.FCLOSE(f);

    f := UTL_FILE.FOPEN('utl_file_demo', 'text.txt', 'A');
    UTL_FILE.PUT_LINE(f, 'tail');
    UTL_FILE.FCLOSE(f);

    f := UTL_FILE.FOPEN('utl_file_demo', 'text.txt', 'R');
    LOOP
        BEGIN
            UTL_FILE.GET_LINE(f, line);
        EXCEPTION WHEN NO_DATA_FOUND THEN
            EXIT;
        END;
        n := n + 1;
        RAISE NOTICE '[%] >>%<<', n, line;
    END LOOP;
    UTL_FILE.FCLOSE(f);
    RAISE NOTICE 'is_open = %', UTL_FILE.IS_OPEN(f);
    UTL_FILE.FREMOVE('utl_file_demo', 'text.txt');
EXCEPTION WHEN OTHERS THEN
    UTL_FILE.FCLOSE_ALL();
    RAISE;
END;
/

The output includes two empty-line records:

NOTICE:  [1] >>abc<<
NOTICE:  [2] >><<
NOTICE:  [3] >><<
NOTICE:  [4] >>ab<<
NOTICE:  [5] >>name=IvorySQL; ratio=100%<<
NOTICE:  [6] >>tail<<
NOTICE:  is_open = f

4.3. Length Limits and the Newline Boundary

This example writes two consecutive three-byte strings, demonstrating that write lengths are not accumulated across PUT calls. Although the read specifies len = 32767, the handle’s max_linesize = 3 still limits each read to three bytes.

DECLARE
    f UTL_FILE.FILE_TYPE;
    line TEXT;
BEGIN
    f := UTL_FILE.FOPEN('utl_file_demo', 'length.txt', 'W', 3);
    UTL_FILE.PUT(f, 'abc');
    UTL_FILE.PUT(f, 'def');
    UTL_FILE.NEW_LINE(f);
    UTL_FILE.FCLOSE(f);

    f := UTL_FILE.FOPEN('utl_file_demo', 'length.txt', 'R', 3);
    FOR i IN 1..3 LOOP
        UTL_FILE.GET_LINE(f, line, 32767);
        RAISE NOTICE '[%] text=[%], bytes=%, pos=%',
            i, line, octet_length(line), UTL_FILE.FGETPOS(f);
    END LOOP;
    BEGIN
        UTL_FILE.GET_LINE(f, line);
    EXCEPTION WHEN NO_DATA_FOUND THEN
        RAISE NOTICE 'EOF: SQLSTATE=%, SQLERRM=%', SQLSTATE, SQLERRM;
    END;
    UTL_FILE.FCLOSE(f);
    UTL_FILE.FREMOVE('utl_file_demo', 'length.txt');
EXCEPTION WHEN OTHERS THEN
    UTL_FILE.FCLOSE_ALL();
    RAISE;
END;
/

Output on Linux:

NOTICE:  [1] text=[abc], bytes=3, pos=3
NOTICE:  [2] text=[def], bytes=3, pos=6
NOTICE:  [3] text=[], bytes=0, pos=7
NOTICE:  EOF: SQLSTATE=P0002, SQLERRM=no data found

4.4. Flushing and Seeking with Absolute and Relative Offsets

DECLARE
    writer UTL_FILE.FILE_TYPE;
    reader UTL_FILE.FILE_TYPE;
    line TEXT;
    second_pos INTEGER;
BEGIN
    writer := UTL_FILE.FOPEN('utl_file_demo', 'seek.txt', 'W');
    reader := UTL_FILE.FOPEN('utl_file_demo', 'seek.txt', 'R');
    UTL_FILE.PUT_LINE(writer, 'one');
    UTL_FILE.PUT_LINE(writer, 'two');
    UTL_FILE.FFLUSH(writer);

    UTL_FILE.FSEEK(reader, 0);
    UTL_FILE.GET_LINE(reader, line);
    second_pos := UTL_FILE.FGETPOS(reader);
    RAISE NOTICE 'first=%, second_pos=%', line, second_pos;

    UTL_FILE.FSEEK(reader, second_pos);
    UTL_FILE.GET_LINE(reader, line);
    RAISE NOTICE 'absolute=%', line;

    UTL_FILE.FSEEK(reader, NULL, -4);
    UTL_FILE.GET_LINE(reader, line);
    RAISE NOTICE 'relative=%', line;

    UTL_FILE.FCLOSE_ALL();
    RAISE NOTICE 'writer_open=%, reader_open=%',
        UTL_FILE.IS_OPEN(writer), UTL_FILE.IS_OPEN(reader);
    UTL_FILE.FREMOVE('utl_file_demo', 'seek.txt');
EXCEPTION WHEN OTHERS THEN
    UTL_FILE.FCLOSE_ALL();
    RAISE;
END;
/

Here, -4 corresponds to the four bytes occupied by two followed by one LF on Linux. Applications should seek using the actual byte length of a record, not its character count.

NOTICE:  first=one, second_pos=4
NOTICE:  absolute=two
NOTICE:  relative=two
NOTICE:  writer_open=f, reader_open=f

4.5. Querying Attributes, Copying Lines, Renaming, and Deleting

DECLARE
    f UTL_FILE.FILE_TYPE;
    ex BOOLEAN;
    sz NUMBER;
    bs INTEGER;
BEGIN
    f := UTL_FILE.FOPEN('utl_file_demo', 'source.txt', 'W');
    UTL_FILE.PUT_LINE(f, 'alpha');
    UTL_FILE.PUT_LINE(f, 'beta');
    UTL_FILE.PUT_LINE(f, 'gamma');
    UTL_FILE.FCLOSE(f);

    UTL_FILE.FCOPY('utl_file_demo', 'source.txt',
                   'utl_file_demo', 'copy.txt', 2, 3);
    UTL_FILE.FGETATTR('utl_file_demo', 'copy.txt', ex, sz, bs);
    RAISE NOTICE 'copy: exists=%, bytes=%', ex, sz;

    UTL_FILE.FRENAME('utl_file_demo', 'copy.txt',
                     'utl_file_demo', 'renamed.txt', TRUE);
    UTL_FILE.FGETATTR('utl_file_demo', 'renamed.txt', ex, sz, bs);
    RAISE NOTICE 'renamed: exists=%, bytes=%', ex, sz;

    UTL_FILE.FREMOVE('utl_file_demo', 'renamed.txt');
    UTL_FILE.FGETATTR('utl_file_demo', 'renamed.txt', ex, sz, bs);
    RAISE NOTICE 'removed: exists=%, length_null=%, block_null=%',
        ex, sz IS NULL, bs IS NULL;
    UTL_FILE.FREMOVE('utl_file_demo', 'source.txt');
EXCEPTION WHEN OTHERS THEN
    UTL_FILE.FCLOSE_ALL();
    RAISE;
END;
/

On Linux, the copied content consists of the lines beta and gamma, each followed by LF, for a total of 11 bytes:

NOTICE:  copy: exists=t, bytes=11
NOTICE:  renamed: exists=t, bytes=11
NOTICE:  removed: exists=f, length_null=t, block_null=t

4.6. Reading and Writing UTF8 Files

DECLARE
    f UTL_FILE.FILE_TYPE;
    line TEXT;
BEGIN
    f := UTL_FILE.FOPEN_NCHAR('utl_file_demo', 'utf8.txt', 'W');
    UTL_FILE.PUT_LINE_NCHAR(f, '你好,IvorySQL');
    UTL_FILE.FCLOSE(f);

    f := UTL_FILE.FOPEN_NCHAR('utl_file_demo', 'utf8.txt', 'R');
    UTL_FILE.GET_LINE_NCHAR(f, line);
    RAISE NOTICE 'text=%, bytes=%', line, octet_length(line);
    UTL_FILE.FCLOSE(f);
    UTL_FILE.FREMOVE('utl_file_demo', 'utf8.txt');
EXCEPTION WHEN OTHERS THEN
    UTL_FILE.FCLOSE_ALL();
    RAISE;
END;
/

Output in a UTF8 database:

NOTICE:  text=你好,IvorySQL, bytes=17

4.7. Writing BYTEA Data

This example writes five bytes, 41 42 0a 43 44, representing AB, LF, and CD, with no final newline. Since the content is valid text, it can be verified using GET_LINE; arbitrary binary content should not be read through a text interface.

DECLARE
    f UTL_FILE.FILE_TYPE;
    line TEXT;
BEGIN
    f := UTL_FILE.FOPEN('utl_file_demo', 'raw.dat', 'W');
    UTL_FILE.PUT_RAW(f, decode('41420a4344', 'hex'), TRUE);
    UTL_FILE.FCLOSE(f);

    f := UTL_FILE.FOPEN('utl_file_demo', 'raw.dat', 'R');
    UTL_FILE.GET_LINE(f, line);
    RAISE NOTICE 'first=%', line;
    UTL_FILE.GET_LINE(f, line);
    RAISE NOTICE 'last=%', line;
    BEGIN
        UTL_FILE.GET_LINE(f, line);
    EXCEPTION WHEN NO_DATA_FOUND THEN
        RAISE NOTICE 'EOF';
    END;
    UTL_FILE.FCLOSE(f);
    UTL_FILE.FREMOVE('utl_file_demo', 'raw.dat');
EXCEPTION WHEN OTHERS THEN
    UTL_FILE.FCLOSE_ALL();
    RAISE;
END;
/
NOTICE:  first=AB
NOTICE:  last=CD
NOTICE:  EOF

4.8. Catching Invalid Seek Parameters

INVALID_OFFSET is an error message, not an exception variable declared in the package. After catching an error with WHEN OTHERS, inspect SQLSTATE and SQLERRM and rethrow any unexpected error.

DECLARE
    f UTL_FILE.FILE_TYPE;
BEGIN
    f := UTL_FILE.FOPEN('utl_file_demo', 'offset.txt', 'W');
    UTL_FILE.PUT(f, 'abc');
    UTL_FILE.FCLOSE(f);
    f := UTL_FILE.FOPEN('utl_file_demo', 'offset.txt', 'R');
    BEGIN
        UTL_FILE.FSEEK(f);
    EXCEPTION WHEN OTHERS THEN
        IF SQLSTATE <> 'P0001' OR SQLERRM <> 'INVALID_OFFSET' THEN
            RAISE;
        END IF;
        RAISE NOTICE 'error=%, pos=%', SQLERRM, UTL_FILE.FGETPOS(f);
    END;
    UTL_FILE.FCLOSE(f);
    UTL_FILE.FREMOVE('utl_file_demo', 'offset.txt');
EXCEPTION WHEN OTHERS THEN
    UTL_FILE.FCLOSE_ALL();
    RAISE;
END;
/
NOTICE:  error=INVALID_OFFSET, pos=0

4.9. Commit, Rollback, and File Contents

Handles remain usable across transaction commits. When a top-level transaction rolls back or aborts because of an unhandled error, the resource cleanup callback closes all open files in the current session. A subtransaction rollback caused by catching an error in an inner exception block does not trigger this session-wide closure. A file cleanup callback is also registered for normal backend exit, but it must not be treated as a durability guarantee in the event of a process crash.

File operations do not participate in database transaction rollback. Closing a stream may submit previously buffered writes to the operating system, so ROLLBACK does not undo written content, restore truncated files, or reverse deletion and renaming.

Run the following anonymous block directly at the top level in a session with autocommit enabled. Do not wrap it in an explicit transaction or add an exception handler to the block that executes COMMIT and ROLLBACK.

DECLARE
    f UTL_FILE.FILE_TYPE;
    line TEXT;
BEGIN
    f := UTL_FILE.FOPEN('utl_file_demo', 'transaction.txt', 'W');
    UTL_FILE.PUT_LINE(f, 'kept');
    COMMIT;
    RAISE NOTICE 'after commit: open=%', UTL_FILE.IS_OPEN(f);
    ROLLBACK;
    RAISE NOTICE 'after rollback: open=%', UTL_FILE.IS_OPEN(f);

    f := UTL_FILE.FOPEN('utl_file_demo', 'transaction.txt', 'R');
    UTL_FILE.GET_LINE(f, line);
    RAISE NOTICE 'content=%', line;
    UTL_FILE.FCLOSE(f);
    UTL_FILE.FREMOVE('utl_file_demo', 'transaction.txt');
END;
/
NOTICE:  after commit: open=t
NOTICE:  after rollback: open=f
NOTICE:  content=kept

4.10. Removing the Directory Registration

After completing the examples, remove the registration created in this section. Each example has already deleted its own files. If execution was interrupted, close the files first, then inspect the separate example directory for any remaining files.

DELETE FROM sys.utl_file_directory
WHERE dirname = 'utl_file_demo'
  AND dir = '/tmp/ivorysql_utl_file_demo';

Once the directory is empty, remove it on the server:

rmdir /tmp/ivorysql_utl_file_demo

5. Errors and Compatibility Boundaries

The current C implementation uses the following error messages. Except for NO_DATA_FOUND, the uppercase names in this table are reported using the generic raise_exception SQLSTATE P0001; they do not imply that the package declares an exception with the same name.

Error Message or Condition SQLSTATE Typical Cause

INVALID_PATH

P0001

The full path is outside the registered directories, or the operating system reports a missing file, denied access, a path component that is not a directory, or a similar error.

INVALID_MODE

P0001

The open mode is not an allowed single-character mode, for example rb.

INVALID_MAXLINESIZE

P0001

max_linesize or a non-null GET_LINE.len is outside the range 1–32767.

INVALID_FILEHANDLE

P0001

The handle has no valid slot in the current session, for example when reading after closing it.

INVALID_OPERATION

P0001

Reading from a write-only handle, writing to a read-only handle, or another operating system failure not mapped to a path error.

INVALID_OFFSET

P0001

Both seek offsets are null, or the target offset is outside the valid range.

READ_ERROR

P0001

An underlying read failure not mapped to INVALID_OPERATION; this should not simply be interpreted as a text line exceeding the length limit.

WRITE_ERROR

P0001

An underlying write, flush, or close failure; or a rename destination that already exists when overwriting is disabled.

VALUE_ERROR

P0001

A single text write subject to length checking exceeds its byte budget, with the detail buffer is too short. Do not assume that the predefined WHEN VALUE_ERROR handler catches it.

NO_DATA_FOUND / no data found

P0002

A read obtains no characters because of EOF. This can be caught with WHEN NO_DATA_FOUND.

null value not allowed

22004

A required argument is NULL, such as an explicitly null max_linesize or write buffer.

program limit exceeded

54000

An attempt to obtain a 51st simultaneously open file handle.

Other possible errors include 22023 parameter errors, such as nonpositive line numbers in FCOPY, character set conversion or validation errors, and database object permission errors. When diagnosing a failure, examine SQLSTATE, SQLERRM, and the DETAIL returned by the server together.

The current package does not declare dedicated exceptions such as ACCESS_DENIED, DELETE_FAILED, RENAME_FAILED, FILE_OPEN, CHARSETMISMATCH, INVALID_FILENAME, and INTERNAL_ERROR, which appear in Oracle documentation. They must not be listed as implemented package exceptions. Deletion and renaming failures are generally mapped to INVALID_PATH or INVALID_OPERATION according to the underlying error.

Public subprograms not yet provided include GET_RAW, PUT_NCHAR, and PUTF_NCHAR. Byte open modes are also unavailable. When migrating code, pay particular attention to directory authorization, per-call versus cumulative lengths, mixing NCHAR and ordinary interfaces, handle state after closing, and the fact that file operations are not undone by transaction rollback.

6. Verification Basis

Verification was performed on 2026-12-03. The instance reported its version as PostgreSQL 19.0 (IvorySQL 6.0), and the installed ivorysql_ora extension version was 1.1. All executable SQL examples above were extracted from the document and run through the instance’s Oracle compatibility port with ON_ERROR_STOP enabled, and the listed output was checked.

The corresponding source files are:

  • contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file—​1.0.sql: package types, public signatures, defaults, wrapper procedures, and initial directory table permissions.

  • contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c: path checks, file slots, input and output, positioning, error mapping, and resource cleanup.

  • contrib/ivorysql_ora/src/ivorysql_ora.c: registration of the utl_file.umask setting.

  • contrib/ivorysql_ora/sql/utl_file.sql and contrib/ivorysql_ora/sql/utl_file_putf.sql: existing regression cases used as verification references; the examples in this document were also run separately against the running instance.

Additional checks covered subdirectory access; rejection of sibling directories and paths outside registered directories; EOF on an empty file; invalid modes; explicit NULL arguments; lower and upper length limits; truncated multibyte characters; mixing ordinary and NCHAR interfaces; seek boundaries; misuse of read-only and write-only handles; repeated closing; the 50-handle limit; and the length behavior of PUT_RAW.