UTL_FILE package implementation
1. Purpose
IvorySQL implements Oracle’s UTL_FILE package, providing server-side text file I/O including open, close, read, write, flush, position seeking, file attribute queries, and file copy/remove/rename. Its public API, open modes, line-length limits, 50-open-file limit, and exception names match Oracle. For user examples, see UTL_FILE package.
Two security mechanisms that PostgreSQL’s built-in file functions do not provide are added alongside:
-
a
sys.utl_file_directoryregistry table that whitelists accessible directories, mirroring Oracle’s directory objects; -
a
utl_file.umaskGUC that controls the permission mask of files created byFOPEN.
2. Implementation
2.1. Code organization and call path
| Source path | Responsibility |
|---|---|
|
Registers the C entry points |
|
C implementation: path security checks, handle slot management, stdio-based I/O, umask GUC hooks |
|
Regression cases |
|
Expected results |
|
Build integration and SQL merge for the new directory |
|
Declares the |
UTL_FILE.FOPEN(location, filename, open_mode, max_linesize)
→ package body: file.id := sys.ora_utl_file_fopen(location, filename, open_mode, max_linesize)
→ ora_utl_file_fopen() → get_safe_path() → fopen() → reserve_slot()
UTL_FILE.PUT_LINE(file, buffer, autoflush)
→ sys.ora_utl_file_put_line(file.id, buffer, autoflush)
→ ora_utl_file_put_line() → get_file_handle_from_slot() → fprintf()/fflush()
UTL_FILE.GET_LINE(file, buffer, len)
→ sys.ora_utl_file_get_line(file.id, len)
→ ora_utl_file_get_line() → get_line() (returns NULL at EOF)
The UTL_FILE. subprograms in the package body are thin wrappers: they unpack the composite file handle and forward the numeric slot id to the sys.ora_utl_file_ C entry points. FOPEN_NCHAR/GET_LINE_NCHAR/PUT_LINE_NCHAR pass the encoding name UTF8 explicitly; FOPEN without the encoding argument uses the database encoding.
2.2. Security model
2.2.1. Directory registry
Access is restricted to directories registered in sys.utl_file_directory (dirname name PRIMARY KEY, dir TEXT). REVOKE ALL … FROM PUBLIC followed by GRANT SELECT TO PUBLIC means only superusers can maintain the registry, while unprivileged users can see it.
Every operation that turns location + filename into a filesystem path goes through get_safe_path():
-
safe_named_location()looks the location up by exactdirnameequality (deliberately notLIKE, to avoid_/%special handling) and substitutes the registered path when found. -
The full path is assembled and passed through
canonicalize_path(). -
check_secure_locality()runs a cached SPI query that verifies the canonicalized path lies within a registered directory using prefix comparison with explicit/handling:
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
If no registered directory matches, the operation fails with INVALID_PATH (errdetail: File location is invalid., errhint: locality is not found in sys.utl_file_directory table). Because the check runs on the canonicalized full path, ..-style escapes resolve to real paths before matching and cannot smuggle writes outside the registry.
2.2.2. utl_file.umask
FOPEN creates files with the mode implied by fopen(), masked by utl_file.umask (default 0077). The implementation brackets the fopen() call with umask() save/restore so no other operations in the process are affected.
The GUC is declared as a string with check/assign hooks:
-
the check hook rejects non-octal digits, and inside normal processing requires superuser (
ERCODE_INSUFFICIENT_PRIVILEGEotherwise); -
the assign hook converts the string to an integer used by
FOPEN.
2.3. Handle management
Handles live in a fixed table of 50 slots (MAX_SLOTS, matching Oracle 10g) holding the FILE*, max_linesize, and encoding. FOPEN allocates a slot and stores its numeric id in the composite file handle; exceeding the limit fails with ERRCODE_PROGRAM_LIMIT_EXCEEDED.
PostgreSQL’s AllocateFile is intentionally not used: it auto-closes files at transaction commit/abort, while Oracle-compatible handles must survive COMMIT. Instead:
-
a
ResourceOwnerrelease callback closes handles on transaction abort or session end; -
a
before_shmem_exithook does a final sweep so buffered data is flushed and files closed even on abnormal backend termination.
This yields the documented lifecycle: IS_OPEN stays TRUE across COMMIT, becomes FALSE after ROLLBACK, and all handles are gone when the session exits. FCLOSE_ALL closes every slot owned by the session.
2.4. I/O behavior and exceptions
-
All text I/O goes through stdio with the encoding recorded at open time, so
GET_LINE/PUT_LINEperform conversion between the database encoding and the file encoding. -
GET_LINEreturns at most the lesser oflen, the distance to the next line terminator, andmax_linesize— the Oracle Operational Notes rule; the terminator itself is not stored, and blank lines yield empty strings. -
GET_LINEreads up tomax_linesizebytes per call (lentemporarily lowers it); at EOF it logsno data foundatLOGlevel and returnsNULL, so callers can loop onWHILE line IS NOT NULL. TheNO_DATA_FOUNDcondition is therefore observable in the server log rather than raised as an error. -
PUTFimplements Oracle’s limited-printf()format:\nbecomes the platform line terminator,%sconsumes the next argument (unmatched formatters render as an empty string, includingNULLarguments), and%%is an IvorySQL extension producing a literal%. ACHECK_LENGTHguard raisesVALUE_ERROR("buffer is too short") as soon as the accumulated output exceedsmax_linesize. -
FSEEKsupports absolute (SEEK_SET, preceded by arewind) and relative (SEEK_CUR, may be negative) offsets; bothNULLresets the position to 0. Invalid combinations raiseINVALID_OFFSET. -
FFLUSHexplicitly `fflush()`es the stream, which is what makes buffered writes visible to a concurrently opened read handle. -
FGETATTRreturns(fexists, file_length, block_size)via a composite type;file_lengthis carried asnumericto match Oracle’sNUMBER. -
FCOPYcopies line ranges (start_linemust be positive);FRENAMErefuses to clobber the destination unlessoverwrite = TRUE(WRITE_ERROR: Destination file already exists).
Oracle-compatible exceptions (INVALID_FILEHANDLE, INVALID_MAXLINESIZE, INVALID_MODE, INVALID_OFFSET, INVALID_OPERATION, INVALID_PATH, READ_ERROR, VALUE_ERROR, WRITE_ERROR) are raised as ERRCODE_RAISE_EXCEPTION with the Oracle exception name as SQLERRM, so WHEN OTHERS plus SQLERRM reproduces Oracle’s error handling style. Oracle defines a larger exception set (also ACCESS_DENIED, CHARSETMISMATCH, DELETE_FAILED, FILE_OPEN, INTERNAL_ERROR, INVALID_FILENAME, RENAME_FAILED); the implementation does not detect these conditions specifically, and the underlying operating system errors surface under the closest name above, with strerror(errno) text in the DETAIL field.
3. Error Handling Example
3.1. Unregistered directory
DECLARE
f sys.ora_utl_file_file_type;
BEGIN
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
The path check reports an error before opening the file. This example assumes wrong_directory is neither registered nor a valid path within a registered directory.
4. Regression verification
The utl_file regression group covers: FOPEN against an unregistered directory (INVALID_PATH), the write/read round trip across PUT_LINE/PUT/NEW_LINE/PUTF/GET_LINE (including len-clipped reads), FGETATTR/FCOPY/FREMOVE/FRENAME, the FFLUSH visibility barrier and FSEEK/FGETPOS absolute/relative seeks, exception handling with FCLOSE_ALL, and handle lifecycle across COMMIT/ROLLBACK.
From a configured and built IvorySQL source tree, run make -C contrib/ivorysql_ora oracle-installcheck ORA_REGRESS=utl_file to verify this test group. The target instance must have the matching version of the ivorysql_ora extension installed.