UTL_FILE Package Implementation

1. Purpose

IvorySQL’s UTL_FILE package provides server-side file operations for opening, closing, reading, writing, flushing, seeking, querying attributes, copying, deleting, and renaming. It provides a subset of Oracle-compatible interfaces. For usage and compatibility boundaries, see UTL_FILE Package.

Files are accessed by the database server process. sys.utl_file_directory registers the directories that may be accessed, and utl_file.umask controls the permission mask for files created by FOPEN.

2. Implementation

2.1. Code Organization and Call Flow

All paths in the following table are relative to contrib/ivorysql_ora/.

Source Path Responsibility

src/builtin_packages/utl_file/utl_file—​1.0.sql

Defines the underlying sys.ora_utl_file_* functions, the ora_utl_file_fgetattr_result composite type, the directory table, and the UTL_FILE package.

src/builtin_packages/utl_file/utl_file.c

Implements path checks, handle slots, stdio I/O, resource cleanup, and umask hooks.

sql/utl_file.sql, sql/utl_file_putf.sql, and the corresponding .out files under expected/

Regression cases and expected results for package interfaces, handle lifetimes, and formatted output with multibyte encodings.

Makefile, meson.build, ivorysql_ora_merge_sqls, gensql.pl

Build the shared library and generate extension installation scripts from the SQL path list and version information.

src/ivorysql_ora.c

Registers utl_file.umask in _PG_init().

The main call flows are shown below, omitting argument checks and error branches:

UTL_FILE.FOPEN(...)
    → sys.ora_utl_file_fopen(...)
    → get_safe_path() → temporarily set umask → fopen() → restore umask → reserve_slot()
UTL_FILE.PUT_LINE(file, buffer, autoflush)
    → sys.ora_utl_file_put_line(file.id, buffer, autoflush)
    → do_put() → do_write() → encoding conversion, length check, fwrite()
    → put_lines() → fputc('\n') → fflush() if autoflush is enabled
UTL_FILE.GET_LINE(file, buffer, len)
    → sys.ora_utl_file_get_line(file.id, len)
    → get_line() → fgetc()/ungetc() → encoding validation and conversion
    → return TEXT; raise NO_DATA_FOUND if no characters were read because of EOF

The public handle is the package record UTL_FILE.FILE_TYPE, containing id, datatype, and byte_mode; there is no SQL type named sys.ora_utl_file_file_type. The package body passes file.id to the underlying functions, which perform the operation through C entry points or SQL wrapper overloads.

FOPEN uses the database encoding, while FOPEN_NCHAR explicitly passes 'UTF8' when opening the file. The actual encoding is stored in the C slot. GET_LINE_NCHAR and PUT_LINE_NCHAR neither reset the encoding nor check the record’s datatype. PUT_LINE_NCHAR always enables flushing. Byte open modes are not currently implemented.

2.2. Security Model

2.2.1. Directory Registration Table

The installation script creates sys.utl_file_directory(dirname name PRIMARY KEY, dir TEXT), revokes all privileges from PUBLIC, and then grants SELECT. The table owner, superusers, and roles granted the necessary table privileges can maintain registrations. The table does not provide a model for granting directory READ and WRITE privileges separately to individual users.

Operations that require file paths pass through get_safe_path(). Copying and renaming check both source and destination paths:

  1. safe_named_location() looks up an alias by equality against dirname. If a non-null path is found, it substitutes that path; otherwise, it treats location as a path.

  2. The directory, /, and filename are joined, and canonicalize_path() normalizes the result.

  3. check_secure_locality() executes an SPI query to check whether the full path falls under a registered directory.

The internal query is shown below. $1 is bound by the C layer; this is not standalone SQL that can be executed without parameter binding:

SELECT 1 FROM sys.utl_file_directory
WHERE CASE WHEN substring(dir from '.$') = '/' THEN
    substring($1, 1, length(dir)) = dir
ELSE
    substring($1, 1, length(dir) + 1) = dir || '/'
END

Equality comparisons avoid wildcard interpretation of _ and %, while the separator check prevents matching sibling directories that share a name prefix. SPI caches the query plan but still queries the registration table on each call. If no row matches, INVALID_PATH is raised.

The check permits subdirectory access, but it only normalizes path strings and does not resolve symbolic links; it must not be regarded as a file system sandbox. Removing a registration affects subsequent opens. Handles that are already open do not recheck the directory table.

2.2.2. utl_file.umask

utl_file.umask is a string GUC with a default value of '0077', declared as PGC_USERSET. Permission to change it is restricted by the check hook:

  • During normal processing within a transaction, the check hook requires a superuser. It validates up to four octal digits and stores the converted integer in extra.

  • The assign hook reads the integer from extra and assigns it to the internal mask variable.

FOPEN and FOPEN_NCHAR save and set the process mask before fopen(), then restore it after the call returns. Permissions on existing files remain unchanged. FCOPY does not perform this mask switch; its resulting permissions depend on the backend’s original mask and file system rules.

2.3. Handle Management

Each backend uses 50 static slots containing FILE *, max_linesize, the encoding, and a uint32 id. An id of 0 indicates a free slot. IDs are generated by a counter and cannot be used across sessions.

FOPEN allocates a slot after calling fopen(). If no slot is available, it raises 54000 / program limit exceeded, but the file may already have been created or truncated. FCLOSE releases the slot and closes the stream; FCLOSE_ALL closes all slots. After closure, IS_OPEN returns FALSE for the old handle.

To keep handles usable after COMMIT, the implementation does not use AllocateFile, which automatically closes streams at transaction end. Two types of callbacks are registered after the first successful open:

  • The resource release callback closes all slots in the current session only during RESOURCE_RELEASE_AFTER_LOCKS when isTopLevel = TRUE and isCommit = FALSE. This includes handles left open by previously committed transactions. Commits and subtransaction rollbacks within inner exception blocks do not trigger this closure.

  • The before_shmem_exit callback closes files during normal exit processing, but is not guaranteed to run after a crash, immediate exit, or SIGKILL.

Closing a stream may flush buffered data. File operations do not participate in database transaction rollback: ROLLBACK does not restore truncated files or undo writes, deletions, or renames.

2.4. I/O Behavior and Errors

  • GET_LINE reads byte by byte, recognizes LF, CRLF, and CR, validates the encoding, and converts the result to the database encoding. The limit per call is min(len, max_linesize); when len is null, max_linesize is used. The valid length range is 1–32767.

  • An empty line returns zero-length text. If no characters are read because of EOF, the entry point raises ERROR / P0002 / no data found; catch NO_DATA_FOUND to end a reading loop. A newline left unconsumed when the byte limit is reached remains for the next read, which may return an empty string. Splitting a multibyte character may raise an encoding error.

  • PUT and PUT_LINE check the converted byte length of the argument for each call, without accumulating lengths across calls. The newline appended by PUT_LINE is excluded from the check. NEW_LINE does not perform this length check. PUT_RAW writes BYTEA directly, without encoding conversion or a max_linesize check.

  • PUTF scans complete characters using the file encoding and supports %s, %%, and a backslash followed by n. It accumulates output bytes within a single call, including newlines. Exceeding the limit raises VALUE_ERROR, and a prefix already written may remain. Multibyte scanning and boundaries are covered by the utl_file_putf regression suite.

  • FSEEK requires at least one offset, with the absolute offset taking precedence. After flushing, measuring the file length, and restoring the original position, it checks that the target is within [0, file length] and seeks using SEEK_SET. Out-of-range arguments raise INVALID_OFFSET. FGETPOS returns a 32-bit INTEGER.

  • FFLUSH calls fflush() to submit the stdio buffer to the operating system. It does not call fsync() and cannot guarantee persistence to physical storage.

  • FGETATTR returns attributes through a composite type: the length is converted from st_size to numeric, and the block size comes from st_blksize. Any stat() failure returns FALSE, NULL, NULL, which does not exclusively indicate a missing file.

  • FCOPY uses fgets(), strlen(), and fwrite() to copy text by LF-delimited lines. The destination is created or truncated first, and the operation is unsuitable for data containing NUL bytes. FREMOVE calls unlink(). When overwriting is disabled, FRENAME checks the destination before calling rename(); this does not provide an atomic no-overwrite guarantee under concurrency.

INVALID_FILEHANDLE, INVALID_MAXLINESIZE, INVALID_MODE, INVALID_OFFSET, INVALID_OPERATION, INVALID_PATH, READ_ERROR, VALUE_ERROR, and WRITE_ERROR are all P0001 error messages, not package exception declarations. Check SQLSTATE and SQLERRM in a WHEN OTHERS handler; do not assume that the predefined WHEN VALUE_ERROR handler catches the message with the same name.

IO_EXCEPTION() maps EACCES, ENAMETOOLONG, ENOENT, and ENOTDIR to INVALID_PATH, and other errno values to INVALID_OPERATION, with details from strerror(errno). Dedicated exceptions such as ACCESS_DENIED and CHARSETMISMATCH are not implemented. NULL argument, encoding, and permission errors may also occur.

3. Error Handling Example

3.1. Unregistered Directory

Run this example in IvorySQL psql connected through the Oracle compatibility port. It assumes that the absolute path below is outside all registered directories. The path check fails before the operating system attempts to open the file.

DECLARE
    f UTL_FILE.FILE_TYPE;
BEGIN
    f := UTL_FILE.FOPEN('/tmp/utl_file_impl_unregistered_20261203',
                        'missing.txt', 'R');
END;
/

The expected error is shown below, with the call stack omitted:

ERROR:  INVALID_PATH
DETAIL:  File location is invalid.
HINT:  locality is not found in sys.utl_file_directory table

4. Regression Verification

utl_file covers paths, reading and writing, attributes and file management, flushing, seek boundaries, EOF, NCHAR, and handle lifetimes. utl_file_putf adds multibyte encodings, format substitution, and length boundaries. Both regression suites passed on the current instance.

Run the following commands from the directory containing IvorySQL/ and inst/. Create a separate database through the PG port, then run the tests through the Oracle port to avoid case differences between the database name created and the connection name. The test database must contain the matching extension. The database name must be unused; adjust the ports and installation path for your environment.

./inst/bin/createdb -h 127.0.0.1 -p 5432 -U highgo \
  -T template0 -E UTF8 utl_file_impl_check_20261203
mkdir -p /tmp/utl_file_impl_check_20261203
LD_LIBRARY_PATH=/home/highgo/6.0/inst/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} \
make -C IvorySQL/contrib/ivorysql_ora oracle-installcheck \
  ORA_REGRESS='utl_file utl_file_putf' TAP_TESTS= \
  ORACLE_REGRESS_OPTS='--host=127.0.0.1 --port=1521 --user=highgo --dbname=utl_file_impl_check_20261203 --use-existing --outputdir=/tmp/utl_file_impl_check_20261203'

ORACLE_REGRESS_OPTS passes options to the Oracle regression runner, and TAP_TESTS= prevents additional TAP tests from running. The original cases use fixed file names in the data directory. Run them on a dedicated test instance or first confirm that those names are unused. Afterwards, clean up only the files and database created by this test run.