Repository navigation
Feature/utl file - #1168
Feature/utl file#1168
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds an Oracle-compatible UTL_FILE feature: new C implementation and SQL package exposing ora_utl_file_* functions, build/meson integration, a new GUC Changes
Sequence Diagram(s)sequenceDiagram
actor Client
participant SQL as "SQL Layer"
participant Cimpl as "C impl\n(ora_utl_file_*)"
participant Sys as "sys.utl_file_directory"
participant FS as "Filesystem"
Client->>SQL: CALL UTL_FILE.FOPEN(location, filename, mode)
SQL->>Cimpl: ora_utl_file_fopen(location, filename, mode, ...)
Cimpl->>Sys: validate location (SELECT dir ...)
Sys-->>Cimpl: dir path / locality info
Cimpl->>FS: open(path, mode, umask)
FS-->>Cimpl: fd / success
Cimpl-->>SQL: slot handle (integer)
SQL-->>Client: handle returned
Client->>SQL: CALL UTL_FILE.PUT_LINE(handle, text)
SQL->>Cimpl: ora_utl_file_put_line(handle, text)
Cimpl->>FS: write(buffer)
FS-->>Cimpl: bytes written
Cimpl-->>SQL: status
Client->>SQL: CALL UTL_FILE.FGETATTR(location, filename)
SQL->>Cimpl: ora_utl_file_fgetattr(location, filename)
Cimpl->>FS: stat(file)
FS-->>Cimpl: exists,length,block_size
Cimpl-->>SQL: attributes
Client->>SQL: CALL UTL_FILE.FCLOSE(handle)
SQL->>Cimpl: ora_utl_file_fclose(handle)
Cimpl->>FS: close(fd)
Cimpl->>Cimpl: free slot
Cimpl-->>SQL: closed
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 1 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (1 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
@bigplaice Once you okay, I will start adding new functions. |
|
@yasir-hussain-shah |
checking this. Will update shortly. |
f5304d6 to
60868e3
Compare
08e2b48 to
f738ad9
Compare
spell correction
regression fixes
8acd25e to
f945064
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (9)
contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c (9)
1235-1257:⚠️ Potential issue | 🔴 Critical
get_file_handle_from_slotreturnsNULLfor stale slots, causing UB in all callers.
INVALID_FILEHANDLE_WARNING()emits a warning and returnsNULL. Every caller —ora_utl_file_fflush,ora_utl_file_get_line,ora_utl_file_new_line,ora_utl_file_putf,do_put(and transitivelyput,put_line) — passes the result directly to stdio functions without a NULL guard, causing undefined behavior (crash or silent wrong-stream writes forfflush(NULL)).Promote the warning to an error so the function never returns
NULL.🐛 Proposed fix
- INVALID_FILEHANDLE_WARNING(); - return NULL; + INVALID_FILEHANDLE_EXCEPTION(); + pg_unreachable();🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c` around lines 1235 - 1257, get_file_handle_from_slot currently calls INVALID_FILEHANDLE_WARNING() and then returns NULL, which leads to UB in callers; change the function to never return NULL on a stale slot by promoting the warning to an error (i.e., replace the INVALID_FILEHANDLE_WARNING() call with the same failure path used by INVALID_FILEHANDLE_EXCEPTION() or otherwise raise/elog(ERROR) so the function aborts instead of returning NULL), ensuring callers like ora_utl_file_fflush, ora_utl_file_get_line, ora_utl_file_new_line, ora_utl_file_putf, do_put/put/put_line no longer receive NULL file pointers.
1414-1418:⚠️ Potential issue | 🟡 MinorMissing closing
)inGUC_check_errdetailerror message.🐛 Proposed fix
- GUC_check_errdetail("number is too big (only four digits are allowed"); + GUC_check_errdetail("number is too big (only four digits are allowed)");🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c` around lines 1414 - 1418, The error message call to GUC_check_errdetail in the digits-check branch is missing a closing parenthesis; update the call in the digits > 3 block (the GUC_check_errdetail invocation) to include the missing ')' at the end of the string so the string and function call are properly closed (i.e., finish the message "number is too big (only four digits are allowed)" and then close the GUC_check_errdetail(...) call).
869-881:⚠️ Potential issue | 🔴 Critical
put_rawroutes binary data throughdo_write→encode_text→pg_do_encoding_conversion, corrupting raw bytes.
do_writeperforms an encoding conversion intended for text. Rawbyteadata must bypass this path and be written withfwrite(VARDATA_ANY(data), 1, VARSIZE_ANY_EXHDR(data), fd)directly.🐛 Proposed fix
Datum ora_utl_file_put_raw(PG_FUNCTION_ARGS) { FILE *fd; - size_t max_linesize = 0; - int encoding = 0; CHECK_FILE_HANDLE(); - fd = get_file_handle_from_slot(PG_GETARG_UINT32(0), &max_linesize, &encoding); + fd = get_file_handle_from_slot(PG_GETARG_UINT32(0), NULL, NULL); + + if (fd == NULL) + INVALID_FILEHANDLE_EXCEPTION(); NOT_NULL_ARG(1); - do_write(fcinfo, 1, fd, max_linesize, encoding); + { + bytea *data = PG_GETARG_BYTEA_PP(1); + char *buf = VARDATA_ANY(data); + size_t len = VARSIZE_ANY_EXHDR(data); + + if (fwrite(buf, 1, len, fd) != len) + CHECK_ERRNO_PUT(); + + PG_FREE_IF_COPY(data, 1); + } PG_RETURN_VOID(); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c` around lines 869 - 881, ora_utl_file_put_raw currently sends binary data through do_write (which calls encode_text → pg_do_encoding_conversion) corrupting raw bytes; change ora_utl_file_put_raw to bypass do_write and instead retrieve the raw bytea argument and write it directly with fwrite using VARDATA_ANY(data) and VARSIZE_ANY_EXHDR(data) to the FILE* returned by get_file_handle_from_slot, preserving the existing NOT_NULL_ARG(1) and error handling; reference functions/symbols: ora_utl_file_put_raw, do_write, encode_text, pg_do_encoding_conversion, and use VARDATA_ANY/VARSIZE_ANY_EXHDR for the direct write.
508-529:⚠️ Potential issue | 🔴 CriticalFile descriptor leak in
fcopywhencopy_text_filefails.
IO_EXCEPTION()(line 526) callsereport(ERROR, …)which longjmps —fcloseon lines 528–529 is never reached on error, leaking both rawFILE*handles.🐛 Proposed fix
- if (copy_text_file(srcfile, dstfile, start_line, end_line)) - IO_EXCEPTION(); - - fclose(srcfile); - fclose(dstfile); + int copy_result = copy_text_file(srcfile, dstfile, start_line, end_line); + + fclose(srcfile); + fclose(dstfile); + + if (copy_result) + IO_EXCEPTION();🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c` around lines 508 - 529, The fcopy implementation leaks FILE* handles when copy_text_file fails because IO_EXCEPTION() longjmps before fclose(srcfile)/fclose(dstfile) run; update the error path so both srcfile and dstfile are closed before invoking IO_EXCEPTION(): after calling copy_text_file(srcfile, dstfile, start_line, end_line) check its failure case, call fclose(dstfile) and fclose(srcfile) (in that order to flush dst first) and then call IO_EXCEPTION(); alternatively wrap the copy/text sequence in a PG_TRY/PG_FINALLY and close srcfile/dstfile in the FINALLY block to guarantee cleanup; reference symbols: fcopy (the function containing this code), srcfile, dstfile, copy_text_file, IO_EXCEPTION.
1058-1098:⚠️ Potential issue | 🟡 Minor
close_all_files: staleerrnomay produce a misleading error message.When multiple
fclosecalls fail, each overwriteserrno;STRERROR_EXCEPTION(WRITE_ERROR)after the loop reports the errno from the last failing (or even a subsequent successful) call rather than the first failure.🐛 Proposed fix
static void close_all_files(void) { FILE *fd = NULL; - bool report_error = false; + int saved_errno = 0; for (int i = 0; i < MAX_SLOTS; i++) { if (slots[i].id != INVALID_SLOTID) { fd = slots[i].fd; slots[i].id = INVALID_SLOTID; slots[i].fd = NULL; slots[i].max_linesize = 0; slots[i].encoding = 0; - if(fd != NULL && fclose(fd) == 0) - continue; - else - report_error = true; + if (fd != NULL && fclose(fd) != 0) + { + if (saved_errno == 0) + saved_errno = errno; + } } } - if(report_error) + if (saved_errno != 0) + { + errno = saved_errno; STRERROR_EXCEPTION(WRITE_ERROR); + } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c` around lines 1058 - 1098, The loop in close_all_files overwrites errno on each fclose failure so STRERROR_EXCEPTION(WRITE_ERROR) reports the wrong errno; modify close_all_files to capture the first failure's errno into a local variable (e.g. int first_error_errno = 0) the moment a fclose(fd) fails (if first_error_errno == 0 then first_error_errno = errno), keep using report_error as now, and before calling STRERROR_EXCEPTION(WRITE_ERROR) restore errno = first_error_errno (or pass first_error_errno into the error-reporting path) so the reported strerror corresponds to the first fclose failure; references: close_all_files, slots, STRERROR_EXCEPTION, WRITE_ERROR, errno.
1103-1143:⚠️ Potential issue | 🟡 Minor
copy_text_file:buffer[len - 1]is undefined behavior whenlen == 0.If
fgetssomehow returns a buffer containing only a null terminator (len == 0), thedo-whileconditionbuffer[len - 1]dereferencesbuffer[-1]. Additionally, a final line with no trailing\ncauses the innerfgetsto returnNULL(errno=0) andreturn errno(returns 0), silently signalling success while the outer loop skips remaining copy iterations.🐛 Proposed fix
- } while(buffer[len - 1] != '\n'); + } while(len > 0 && buffer[len - 1] != '\n');Apply to both the skip loop (line 1123) and the copy loop (line 1137).
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c` around lines 1103 - 1143, In copy_text_file, avoid dereferencing buffer[len - 1] when len == 0 and properly detect EOF vs error from fgets in both the skip loop (the for(i = 1; i < start_line; i++) block) and the copy loop (for (; i <= end_line; i++) block): after fgets returns NULL check errno and feof(srcfile) and return a non-zero error code on premature EOF or actual error instead of returning errno==0; also whenever len is computed, ensure you test if len == 0 before inspecting buffer[len - 1] to prevent buffer[-1] access. Locate fixes around the symbols buffer, len, fgets, errno, and the do/while conditions in copy_text_file.
1009-1056:⚠️ Potential issue | 🔴 CriticalPath traversal: named-location paths skip
check_secure_locality, allowing directory escape via filename.When
safe_named_locationfinds a match,check_locality = falseand the finalcanonicalize_path'd path is never validated to remain under the resolved directory. A user can passfilename = '../../etc/passwd', which canonicalizes to/etc/passwdwith no locality check performed.🐛 Proposed fix: always call `check_secure_locality` after canonicalization
/* check locality in canonizalized form of path */ canonicalize_path(fullname); - if (check_locality) - check_secure_locality(fullname); + check_secure_locality(fullname); return fullname;Alternatively, after building
fullnamewith the named location, verify the canonicalized result still starts with the resolvedlocationprefix.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c` around lines 1009 - 1056, get_safe_path currently skips check_secure_locality when safe_named_location returns a location, allowing filename to escape the named directory after canonicalize_path; change the logic in get_safe_path so that after building and calling canonicalize_path(fullname) you always call check_secure_locality(fullname) (regardless of whether location was set), or alternatively verify the canonicalized fullname still begins with the resolved location prefix before returning; keep the existing safe_named_location/location memory handling (pfree(location)) but ensure locality is validated for both named-location and direct-directory branches (i.e., remove or ignore the check_locality conditional and call check_secure_locality unconditionally after canonicalize_path).
695-706:⚠️ Potential issue | 🟠 Major
ftell()return silently truncated toINT32for files larger than 2 GB.
ftell()returnslong; casting toint32viaPG_RETURN_INT32silently truncates for offsets >INT32_MAX, producing wrong or negative positions. Consider returningINT64or raising an explicit overflow error.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c` around lines 695 - 706, ora_utl_file_ftell currently truncates ftell() (long) to int32 via PG_RETURN_INT32, causing wrong values for large files; fix by capturing the ftell result into a long (e.g., long pos = ftell(fd)), check for error (pos == -1L) and raise a clear error with errno if so, and return the full 64-bit value using PG_RETURN_INT64((int64) pos) instead of PG_RETURN_INT32; update any related declaration if needed and keep references to CHECK_FILE_HANDLE(), get_file_handle_from_slot(), INVALID_FILEHANDLE_EXCEPTION(), and PG_RETURN_INT64 in the change.
671-693:⚠️ Potential issue | 🔴 Critical
fseekalways seeks fromSEEK_SETwith summed offsets, breaking relative-only seeks.Oracle semantics:
absolute_offsetnon-NULL →SEEK_SET; onlyrelative_offsetnon-NULL →SEEK_CUR. Summing both and always usingSEEK_SETmeansFSEEK(f, NULL, -10)seeks to position0 + (-10)(fails) instead of moving 10 bytes backward from the current position.🐛 Proposed fix
Datum ora_utl_file_fseek(PG_FUNCTION_ARGS) { FILE *fd; - long abs_offset = 0; - long rel_offset = 0; CHECK_FILE_HANDLE(); fd = get_file_handle_from_slot(PG_GETARG_UINT32(0), NULL, NULL); if(fd == NULL) INVALID_FILEHANDLE_EXCEPTION(); - abs_offset = PG_GETARG_IF_EXISTS(1, INT32, 0); - rel_offset = PG_GETARG_IF_EXISTS(2, INT32, 0); - - if (fseek(fd, abs_offset + rel_offset, SEEK_SET) != 0) - CUSTOM_EXCEPTION(INVALID_OFFSET, "Provided offsets are invalid."); + if (PG_NARGS() > 1 && !PG_ARGISNULL(1)) + { + if (fseek(fd, (long) PG_GETARG_INT32(1), SEEK_SET) != 0) + CUSTOM_EXCEPTION(INVALID_OFFSET, "Provided offsets are invalid."); + } + else if (PG_NARGS() > 2 && !PG_ARGISNULL(2)) + { + if (fseek(fd, (long) PG_GETARG_INT32(2), SEEK_CUR) != 0) + CUSTOM_EXCEPTION(INVALID_OFFSET, "Provided offsets are invalid."); + } PG_RETURN_VOID(); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c` around lines 671 - 693, In ora_utl_file_fseek, change the single fseek(fd, abs_offset + rel_offset, SEEK_SET) call to branch on which arguments are actually provided: if the absolute offset argument is present (use PG_ARGISNULL/PG_GETARG presence check for arg 1) perform fseek with SEEK_SET (you can add rel_offset to abs_offset if both present), but if the absolute offset is absent and only the relative offset is provided perform fseek with SEEK_CUR using rel_offset; keep the existing error handling (CUSTOM_EXCEPTION on non-zero return) and locate your changes inside ora_utl_file_fseek around the current fseek call.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c`:
- Around line 740-746: Remove the noisy ereport(LOG, ...) on EOF in the
GET_LINE/iseof path: delete the ereport(LOG, (errcode(ERRCODE_NO_DATA_FOUND),
errmsg("no data found"))); line(s) and leave the PG_RETURN_NULL() behavior as-is
so normal EOF doesn't spam server logs (if you instead need Oracle-style
exception semantics, replace that ereport(LOG, …) with ereport(ERROR,
(errcode(ERRCODE_NO_DATA_FOUND), errmsg(...))) to raise NO_DATA_FOUND).
- Around line 1289-1324: The get_line function currently returns a truncated
line when csize reaches max_linesize; update get_line to detect this truncation
after the while loop (check csize == max_linesize and loop exit was not due to
EOF/line terminator) and handle it by consuming and discarding the rest of the
physical line from fd (read until '\n' or EOF) so the stdio buffer is advanced,
then raise a VALUE_ERROR exception instead of returning the partial line; ensure
iseof and any allocated buffer are handled appropriately when raising the error
(use the same error/raise mechanism used elsewhere in this file).
---
Duplicate comments:
In `@contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c`:
- Around line 1235-1257: get_file_handle_from_slot currently calls
INVALID_FILEHANDLE_WARNING() and then returns NULL, which leads to UB in
callers; change the function to never return NULL on a stale slot by promoting
the warning to an error (i.e., replace the INVALID_FILEHANDLE_WARNING() call
with the same failure path used by INVALID_FILEHANDLE_EXCEPTION() or otherwise
raise/elog(ERROR) so the function aborts instead of returning NULL), ensuring
callers like ora_utl_file_fflush, ora_utl_file_get_line, ora_utl_file_new_line,
ora_utl_file_putf, do_put/put/put_line no longer receive NULL file pointers.
- Around line 1414-1418: The error message call to GUC_check_errdetail in the
digits-check branch is missing a closing parenthesis; update the call in the
digits > 3 block (the GUC_check_errdetail invocation) to include the missing ')'
at the end of the string so the string and function call are properly closed
(i.e., finish the message "number is too big (only four digits are allowed)" and
then close the GUC_check_errdetail(...) call).
- Around line 869-881: ora_utl_file_put_raw currently sends binary data through
do_write (which calls encode_text → pg_do_encoding_conversion) corrupting raw
bytes; change ora_utl_file_put_raw to bypass do_write and instead retrieve the
raw bytea argument and write it directly with fwrite using VARDATA_ANY(data) and
VARSIZE_ANY_EXHDR(data) to the FILE* returned by get_file_handle_from_slot,
preserving the existing NOT_NULL_ARG(1) and error handling; reference
functions/symbols: ora_utl_file_put_raw, do_write, encode_text,
pg_do_encoding_conversion, and use VARDATA_ANY/VARSIZE_ANY_EXHDR for the direct
write.
- Around line 508-529: The fcopy implementation leaks FILE* handles when
copy_text_file fails because IO_EXCEPTION() longjmps before
fclose(srcfile)/fclose(dstfile) run; update the error path so both srcfile and
dstfile are closed before invoking IO_EXCEPTION(): after calling
copy_text_file(srcfile, dstfile, start_line, end_line) check its failure case,
call fclose(dstfile) and fclose(srcfile) (in that order to flush dst first) and
then call IO_EXCEPTION(); alternatively wrap the copy/text sequence in a
PG_TRY/PG_FINALLY and close srcfile/dstfile in the FINALLY block to guarantee
cleanup; reference symbols: fcopy (the function containing this code), srcfile,
dstfile, copy_text_file, IO_EXCEPTION.
- Around line 1058-1098: The loop in close_all_files overwrites errno on each
fclose failure so STRERROR_EXCEPTION(WRITE_ERROR) reports the wrong errno;
modify close_all_files to capture the first failure's errno into a local
variable (e.g. int first_error_errno = 0) the moment a fclose(fd) fails (if
first_error_errno == 0 then first_error_errno = errno), keep using report_error
as now, and before calling STRERROR_EXCEPTION(WRITE_ERROR) restore errno =
first_error_errno (or pass first_error_errno into the error-reporting path) so
the reported strerror corresponds to the first fclose failure; references:
close_all_files, slots, STRERROR_EXCEPTION, WRITE_ERROR, errno.
- Around line 1103-1143: In copy_text_file, avoid dereferencing buffer[len - 1]
when len == 0 and properly detect EOF vs error from fgets in both the skip loop
(the for(i = 1; i < start_line; i++) block) and the copy loop (for (; i <=
end_line; i++) block): after fgets returns NULL check errno and feof(srcfile)
and return a non-zero error code on premature EOF or actual error instead of
returning errno==0; also whenever len is computed, ensure you test if len == 0
before inspecting buffer[len - 1] to prevent buffer[-1] access. Locate fixes
around the symbols buffer, len, fgets, errno, and the do/while conditions in
copy_text_file.
- Around line 1009-1056: get_safe_path currently skips check_secure_locality
when safe_named_location returns a location, allowing filename to escape the
named directory after canonicalize_path; change the logic in get_safe_path so
that after building and calling canonicalize_path(fullname) you always call
check_secure_locality(fullname) (regardless of whether location was set), or
alternatively verify the canonicalized fullname still begins with the resolved
location prefix before returning; keep the existing safe_named_location/location
memory handling (pfree(location)) but ensure locality is validated for both
named-location and direct-directory branches (i.e., remove or ignore the
check_locality conditional and call check_secure_locality unconditionally after
canonicalize_path).
- Around line 695-706: ora_utl_file_ftell currently truncates ftell() (long) to
int32 via PG_RETURN_INT32, causing wrong values for large files; fix by
capturing the ftell result into a long (e.g., long pos = ftell(fd)), check for
error (pos == -1L) and raise a clear error with errno if so, and return the full
64-bit value using PG_RETURN_INT64((int64) pos) instead of PG_RETURN_INT32;
update any related declaration if needed and keep references to
CHECK_FILE_HANDLE(), get_file_handle_from_slot(),
INVALID_FILEHANDLE_EXCEPTION(), and PG_RETURN_INT64 in the change.
- Around line 671-693: In ora_utl_file_fseek, change the single fseek(fd,
abs_offset + rel_offset, SEEK_SET) call to branch on which arguments are
actually provided: if the absolute offset argument is present (use
PG_ARGISNULL/PG_GETARG presence check for arg 1) perform fseek with SEEK_SET
(you can add rel_offset to abs_offset if both present), but if the absolute
offset is absent and only the relative offset is provided perform fseek with
SEEK_CUR using rel_offset; keep the existing error handling (CUSTOM_EXCEPTION on
non-zero return) and locate your changes inside ora_utl_file_fseek around the
current fseek call.
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (6)
contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c (5)
751-757:⚠️ Potential issue | 🟠 MajorRemove LOG-level reporting on normal EOF in
GET_LINE.Line 753 logs
NO_DATA_FOUNDatLOGfor a normal EOF condition; read loops will spam server logs. Return NULL quietly (or raise an exception at SQL layer if strict Oracle exception behavior is desired).🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c` around lines 751 - 757, In GET_LINE, remove the LOG-level ereport for the normal EOF path: delete the ereport(LOG, (errcode(ERRCODE_NO_DATA_FOUND), errmsg("no data found"))); that references iseof, and simply return PG_RETURN_NULL() for EOF; ensure the iseof branch no longer emits server logs (or replace with a non-LOG debug level if you prefer), leaving the rest of the function unchanged.
706-717:⚠️ Potential issue | 🟡 MinorGuard
ftellerror/overflow before returningINT32.Line 716 returns
ftell(fd)directly asINT32. This can silently truncate large offsets. Check for-1L, validate range, then return or raise.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c` around lines 706 - 717, The function ora_utl_file_ftell incorrectly returns ftell(fd) directly via PG_RETURN_INT32 which can truncate large offsets; modify ora_utl_file_ftell to call ftell(fd), check for error (result == -1L) and raise an error (using the same error reporting style as INVALID_FILEHANDLE_EXCEPTION or ereport), then validate the long result fits in a 32-bit signed range before returning; if it’s out of range raise an overflow/invalid argument error instead of silently truncating. Ensure you still use CHECK_FILE_HANDLE(), get_file_handle_from_slot(), and INVALID_FILEHANDLE_EXCEPTION() as present, but replace the direct PG_RETURN_INT32(ftell(fd)) with the guarded logic that checks for -1L and range before calling PG_RETURN_INT32.
1077-1113:⚠️ Potential issue | 🟡 MinorPreserve the first
errnoinclose_all_filesbefore raising.At Line 1113, the reported
WRITE_ERRORcan reflect a stale/latererrnofrom loop iterations. Capture the first failingerrnoand report that one.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c` around lines 1077 - 1113, In close_all_files, preserve the first failure errno so the raised WRITE_ERROR reports the original cause: add an int saved_errno = 0 before the loop; inside the loop where you detect fclose failure (fd != NULL && fclose(fd) != 0 branch), if report_error is false set saved_errno = errno and then set report_error = true (do not overwrite saved_errno on subsequent failures); after the loop, if(report_error) restore errno = saved_errno and then call STRERROR_EXCEPTION(WRITE_ERROR). Reference symbols: slots[], MAX_SLOTS, STRERROR_EXCEPTION, WRITE_ERROR, and the close_all_files logic.
682-702:⚠️ Potential issue | 🔴 CriticalFix
FSEEKcontrol flow: absolute-only seek is currently overwritten.At Line 690 + Line 697, the
elsebinds to the secondif, so an absolute-only call seeks and then resets to 0. Also, when both offsets are provided, both are applied. Useif / else if / elseso absolute takes precedence, otherwise relative, otherwise reset/no-op.Proposed fix
- if (PG_NARGS() > 1 && !PG_ARGISNULL(1)) + if (PG_NARGS() > 1 && !PG_ARGISNULL(1)) { - /* absolute_offset: seek from beginning */ + /* absolute_offset: seek from beginning */ long abs_offset = (long) PG_GETARG_INT32(1); - rewind(fd); /* first, reset pos to beginning */ if (fseek(fd, abs_offset, SEEK_SET) != 0) CUSTOM_EXCEPTION(INVALID_OFFSET, "Provided offsets are invalid."); } - if (PG_NARGS() > 2 && !PG_ARGISNULL(2)) + else if (PG_NARGS() > 2 && !PG_ARGISNULL(2)) { /* relative_offset: seek from current position */ long rel_offset = (long) PG_GETARG_INT32(2); if (fseek(fd, rel_offset, SEEK_CUR) != 0) CUSTOM_EXCEPTION(INVALID_OFFSET, "Provided offsets are invalid."); } else { - /* no offset provided: no-op or reset to beginning */ + /* no offset provided: reset to beginning */ if (fseek(fd, 0, SEEK_SET) != 0) CUSTOM_EXCEPTION(INVALID_OFFSET, "Provided offsets are invalid."); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c` around lines 682 - 702, The control flow for handling offsets applies both absolute and relative seeks (and the else binds to the second if), causing an absolute-only call to be overwritten; change the branching to if / else if / else so that when PG_NARGS() > 1 and PG_ARGISNULL(1) is false you perform the absolute seek using rewind(fd) and fseek(fd, abs_offset, SEEK_SET) and return/skip the other branches, otherwise if PG_NARGS() > 2 and PG_ARGISNULL(2) is false perform the relative fseek(fd, rel_offset, SEEK_CUR), else do the fallback fseek(fd, 0, SEEK_SET); keep the same CUSTOM_EXCEPTION on fseek errors and retain the existing variables abs_offset and rel_offset.
1320-1375:⚠️ Potential issue | 🟠 MajorDetect overlong lines and raise
VALUE_ERRORinstead of returning truncated data.
get_linecurrently returns partial content whencsize == max_linesizebefore a line terminator, leaving the remainder for the next call. That breaks line framing and Oracle compatibility. Detect this case, consume the rest of the physical line, and raiseVALUE_ERROR.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c` around lines 1320 - 1375, get_line currently returns truncated data when csize == max_linesize and the physical line continues; modify the post-read logic in get_line to detect this overlong-line condition (when csize >= max_linesize and the loop exited without hitting a line terminator or EOF), then consume/skip the remainder of the physical line from fd until you hit '\n' or EOF to restore stream framing, and raise a VALUE_ERROR (use CUSTOM_EXCEPTION(VALUE_ERROR, ...)) instead of returning truncated data; keep existing error handling paths (EBADF / STRERROR_EXCEPTION(READ_ERROR)) for other failures and reference variables/functions: get_line, csize, max_linesize, fd, eof, CUSTOM_EXCEPTION, STRERROR_EXCEPTION.contrib/ivorysql_ora/sql/utl_file.sql (1)
18-165:⚠️ Potential issue | 🟠 MajorExpand regression coverage for NCHAR/raw APIs and clean generated files.
This test still does not exercise
fopen_nchar,put_line_nchar,get_line_nchar, andput_raw, and cleanup at Line 163 only truncates metadata, leaving created files behind (regress*.txt). Please add positive-path cases for those APIs and remove created files in teardown.As per coding guidelines,
**/sql/*.sql: Test SQL files. Ensure comprehensive coverage of features.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@contrib/ivorysql_ora/sql/utl_file.sql` around lines 18 - 165, Add positive-path tests for the NCHAR/raw variants and delete generated files in teardown: call utl_file.fopen_nchar(...) to open a regress_nchar.txt, write using utl_file.put_line_nchar(...) and utl_file.put_raw(...), close and reopen with utl_file.fopen_nchar(...) then read back using utl_file.get_line_nchar(...) to assert contents; finally, in the cleanup section call utl_file.fremove(...) (or utl_file.fremove for each regress*.txt) and/or utl_file.fgetattr(...) checks to ensure the created files (regress.txt, regress2.txt, regressflush.txt, regress_nchar.txt) are removed instead of only truncating sys.utl_file_directory.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file--1.0.sql`:
- Around line 316-319: The PUT_LINE_NCHAR procedure currently forces autoflush
by hardcoding true; update the PROCEDURE PUT_LINE_NCHAR signature to add an
optional parameter autoflush IN BOOLEAN DEFAULT FALSE (matching
PUT_LINE/PUT_RAW) and change the implementation to pass this autoflush parameter
instead of the hardcoded true when calling the internal write/flush routine;
ensure the new parameter name and type match existing variants so callers can
omit it and existing behavior defaults to no autoflush.
In `@contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c`:
- Around line 1136-1149: In copy_text_file, the early returns on EOF/error (the
fgets checks that return errno) skip the final pfree(buffer) and leak memory;
change those direct returns to set a local result variable (e.g. int ret =
errno), jump to a single cleanup label (goto cleanup) and at cleanup free buffer
with pfree(buffer) (and close srcfile if needed) before returning the result;
update the two fgets error paths to assign errno to ret and goto cleanup so
buffer is always freed.
---
Duplicate comments:
In `@contrib/ivorysql_ora/sql/utl_file.sql`:
- Around line 18-165: Add positive-path tests for the NCHAR/raw variants and
delete generated files in teardown: call utl_file.fopen_nchar(...) to open a
regress_nchar.txt, write using utl_file.put_line_nchar(...) and
utl_file.put_raw(...), close and reopen with utl_file.fopen_nchar(...) then read
back using utl_file.get_line_nchar(...) to assert contents; finally, in the
cleanup section call utl_file.fremove(...) (or utl_file.fremove for each
regress*.txt) and/or utl_file.fgetattr(...) checks to ensure the created files
(regress.txt, regress2.txt, regressflush.txt, regress_nchar.txt) are removed
instead of only truncating sys.utl_file_directory.
In `@contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c`:
- Around line 751-757: In GET_LINE, remove the LOG-level ereport for the normal
EOF path: delete the ereport(LOG, (errcode(ERRCODE_NO_DATA_FOUND), errmsg("no
data found"))); that references iseof, and simply return PG_RETURN_NULL() for
EOF; ensure the iseof branch no longer emits server logs (or replace with a
non-LOG debug level if you prefer), leaving the rest of the function unchanged.
- Around line 706-717: The function ora_utl_file_ftell incorrectly returns
ftell(fd) directly via PG_RETURN_INT32 which can truncate large offsets; modify
ora_utl_file_ftell to call ftell(fd), check for error (result == -1L) and raise
an error (using the same error reporting style as INVALID_FILEHANDLE_EXCEPTION
or ereport), then validate the long result fits in a 32-bit signed range before
returning; if it’s out of range raise an overflow/invalid argument error instead
of silently truncating. Ensure you still use CHECK_FILE_HANDLE(),
get_file_handle_from_slot(), and INVALID_FILEHANDLE_EXCEPTION() as present, but
replace the direct PG_RETURN_INT32(ftell(fd)) with the guarded logic that checks
for -1L and range before calling PG_RETURN_INT32.
- Around line 1077-1113: In close_all_files, preserve the first failure errno so
the raised WRITE_ERROR reports the original cause: add an int saved_errno = 0
before the loop; inside the loop where you detect fclose failure (fd != NULL &&
fclose(fd) != 0 branch), if report_error is false set saved_errno = errno and
then set report_error = true (do not overwrite saved_errno on subsequent
failures); after the loop, if(report_error) restore errno = saved_errno and then
call STRERROR_EXCEPTION(WRITE_ERROR). Reference symbols: slots[], MAX_SLOTS,
STRERROR_EXCEPTION, WRITE_ERROR, and the close_all_files logic.
- Around line 682-702: The control flow for handling offsets applies both
absolute and relative seeks (and the else binds to the second if), causing an
absolute-only call to be overwritten; change the branching to if / else if /
else so that when PG_NARGS() > 1 and PG_ARGISNULL(1) is false you perform the
absolute seek using rewind(fd) and fseek(fd, abs_offset, SEEK_SET) and
return/skip the other branches, otherwise if PG_NARGS() > 2 and PG_ARGISNULL(2)
is false perform the relative fseek(fd, rel_offset, SEEK_CUR), else do the
fallback fseek(fd, 0, SEEK_SET); keep the same CUSTOM_EXCEPTION on fseek errors
and retain the existing variables abs_offset and rel_offset.
- Around line 1320-1375: get_line currently returns truncated data when csize ==
max_linesize and the physical line continues; modify the post-read logic in
get_line to detect this overlong-line condition (when csize >= max_linesize and
the loop exited without hitting a line terminator or EOF), then consume/skip the
remainder of the physical line from fd until you hit '\n' or EOF to restore
stream framing, and raise a VALUE_ERROR (use CUSTOM_EXCEPTION(VALUE_ERROR, ...))
instead of returning truncated data; keep existing error handling paths (EBADF /
STRERROR_EXCEPTION(READ_ERROR)) for other failures and reference
variables/functions: get_line, csize, max_linesize, fd, eof, CUSTOM_EXCEPTION,
STRERROR_EXCEPTION.
ℹ️ Review info
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
contrib/ivorysql_ora/expected/utl_file.outcontrib/ivorysql_ora/sql/utl_file.sqlcontrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file--1.0.sqlcontrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c
🚧 Files skipped from review as they are similar to previous changes (1)
- contrib/ivorysql_ora/expected/utl_file.out
This reverts commit 5bb99f1.
There was a problem hiding this comment.
♻️ Duplicate comments (7)
contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c (7)
85-86: Remove redundantexternfor locally definedutl_file_umask_str.Line 85 declares
extern char *utl_file_umask_str;, then Line 86 defines it in the same file. Keep only the definition.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c` around lines 85 - 86, The variable utl_file_umask_str is declared with extern and immediately defined in the same file, creating a redundant declaration; remove the line "extern char *utl_file_umask_str;" and keep only the definition "char *utl_file_umask_str = NULL;" in utl_file.c so there is a single definition of utl_file_umask_str.
1105-1114:⚠️ Potential issue | 🟡 Minor
close_all_filesmay report the wrong close error.
errnocan be overwritten across loop iterations, so the final exception may not reflect the first real failure.Proposed fix
- bool report_error = false; + int first_errno = 0; @@ - if(fd != NULL && fclose(fd) == 0) - continue; - else - report_error = true; + if (fd != NULL && fclose(fd) != 0 && first_errno == 0) + first_errno = errno; @@ - if(report_error) - STRERROR_EXCEPTION(WRITE_ERROR); + if (first_errno != 0) + { + errno = first_errno; + STRERROR_EXCEPTION(WRITE_ERROR); + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c` around lines 1105 - 1114, The loop in close_all_files can lose the original close error because errno may change during subsequent iterations; modify close_all_files to record the first failure's error details (e.g., save errno into a local variable like first_errno and optionally the file name or fd) when fclose(fd) != 0, set report_error, but do not overwrite first_errno on later failures, and then call STRERROR_EXCEPTION(WRITE_ERROR) using that saved first_errno (or formatted message based on it) so the thrown exception reflects the initial close failure rather than a later errno value.
1321-1358:⚠️ Potential issue | 🟠 Major
get_linereturns truncated lines instead of raisingVALUE_ERROR.When
csizereachesmax_linesizebefore newline, the function currently returns partial data and leaves the logical line split across calls.Proposed fix (detect overflow, drain rest of line, then raise)
while (csize < max_linesize && (c = fgetc(fd)) != EOF) { ... } + + /* Hit max_linesize before line terminator: Oracle-compatible VALUE_ERROR */ + if (!eof && csize == max_linesize) + { + while ((c = fgetc(fd)) != EOF) + { + if (c == '\n') + break; + if (c == '\r') + { + int c2 = fgetc(fd); + if (c2 != '\n' && c2 != EOF) + ungetc(c2, fd); + break; + } + } + pfree(buffer); + CUSTOM_EXCEPTION(VALUE_ERROR, "Line too long for specified buffer size."); + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c` around lines 1321 - 1358, The loop in get_line currently returns a truncated line when csize hits max_linesize instead of signaling an overflow; modify get_line to detect when csize == max_linesize, then drain the remainder of the physical line from fd (consume characters until '\n' or EOF, handling '\r\n') to leave the stream positioned after the logical line, set appropriate eof/iseof state, and then raise/return a VALUE_ERROR (or the function's error mechanism) indicating line too long; update references around variables csize, max_linesize, fd, eof, buffer and the post-loop conversion/return block so that when overflow is detected you do not perform normal decoding/memory returns for truncated data but instead free any temporary buffers and propagate the VALUE_ERROR.
752-758:⚠️ Potential issue | 🟠 MajorNormal EOF should not emit
LOGnoise inGET_LINE.Lines 754-756 log every expected EOF. In loops this can spam server logs.
Proposed fix
if (iseof) { - ereport(LOG, - (errcode(ERRCODE_NO_DATA_FOUND), - errmsg("no data found"))); - PG_RETURN_NULL(); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c` around lines 752 - 758, The GET_LINE branch currently emits an ereport(LOG, ...) on normal EOF (when iseof is true), which causes noisy logs; update the code in the GET_LINE/utl_file_get_line path to stop logging normal EOFs by removing or changing the ereport(LOG, ...) call so the function simply returns PG_RETURN_NULL() on iseof (leaving other error paths unchanged), i.e., eliminate the ereport(LOG, (errcode(ERRCODE_NO_DATA_FOUND), errmsg("no data found"))) around the iseof handling.
1137-1157:⚠️ Potential issue | 🟡 Minor
copy_text_fileleaks memory on early return paths.At Lines 1137/1149/1153, early returns skip
pfree(buffer)at Line 1157.Proposed fix
static int copy_text_file(FILE *srcfile, FILE *dstfile, int start_line, int end_line) { char *buffer; size_t len; int i; + int rc = 0; @@ if (fgets(buffer, MAX_LINESIZE, srcfile) == NULL) - return errno; /* EOF or error */ + { + rc = errno; + goto cleanup; + } @@ if (fgets(buffer, MAX_LINESIZE, srcfile) == NULL) - return errno; /* EOF or error */ + { + rc = errno; + goto cleanup; + } len = strlen(buffer); if (fwrite(buffer, 1, len, dstfile) != len) - return errno; + { + rc = errno; + goto cleanup; + } } while(len > 0 && buffer[len - 1] != '\n'); } +cleanup: pfree(buffer); - - return 0; + return rc; }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c` around lines 1137 - 1157, The function copy_text_file leaks the allocated buffer when early-returning on fgets/fwrite failures; update copy_text_file to always free buffer before any return by introducing a single cleanup path (e.g., set an error code and goto cleanup) or explicitly call pfree(buffer) prior to each return where fgets or fwrite fails, referencing the buffer variable and the srcfile/dstfile read/write checks to ensure pfree(buffer) is invoked on all error paths.
717-717:⚠️ Potential issue | 🟡 Minor
ftellreturn is unchecked and can be truncated.Line 717 returns
ftell(fd)directly asINT32;ftell == -1Lis not handled, and large offsets can overflowINT32.Proposed fix
- PG_RETURN_INT32(ftell(fd)); + { + long pos = ftell(fd); + if (pos == -1L) + STRERROR_EXCEPTION(INVALID_OPERATION); + if (pos > INT32_MAX || pos < INT32_MIN) + CUSTOM_EXCEPTION(INVALID_OPERATION, "File position is out of supported range."); + PG_RETURN_INT32((int32) pos); + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c` at line 717, Replace the direct PG_RETURN_INT32(ftell(fd)) with a guarded sequence: call ftell(fd) into a long (e.g., pos), check for error (pos == -1L) and report/return an error via ereport/elog or appropriate PostgreSQL error path, then check that pos fits into INT32 (compare against INT32_MAX/INT32_MIN) and if it doesn't, raise/return an overflow error; finally cast to int and return via PG_RETURN_INT32((int)pos). Use the symbols ftell, PG_RETURN_INT32, INT32_MAX/INT32_MIN (and fd) to locate and implement the checks.
683-703:⚠️ Potential issue | 🔴 Critical
ora_utl_file_fseekhas a control-flow bug and wrong offset semantics.At Line 698, the
elsebinds to the secondif, so anabsolute_offset-only call gets reset to position 0. Also, when both offsets are provided, both are applied, which diverges from Oracle-style precedence.Proposed fix
- if (PG_NARGS() > 1 && !PG_ARGISNULL(1)) + if (PG_NARGS() > 1 && !PG_ARGISNULL(1)) { - /* absolute_offset: seek from beginning */ + /* absolute_offset takes precedence */ long abs_offset = (long) PG_GETARG_INT32(1); - rewind(fd); /* first, reset pos to beginning */ if (fseek(fd, abs_offset, SEEK_SET) != 0) CUSTOM_EXCEPTION(INVALID_OFFSET, "Provided offsets are invalid."); } - if (PG_NARGS() > 2 && !PG_ARGISNULL(2)) + else if (PG_NARGS() > 2 && !PG_ARGISNULL(2)) { /* relative_offset: seek from current position */ long rel_offset = (long) PG_GETARG_INT32(2); if (fseek(fd, rel_offset, SEEK_CUR) != 0) CUSTOM_EXCEPTION(INVALID_OFFSET, "Provided offsets are invalid."); } - else - { - /* no offset provided: no-op or reset to beginning */ - if (fseek(fd, 0, SEEK_SET) != 0) - CUSTOM_EXCEPTION(INVALID_OFFSET, "Provided offsets are invalid."); - } + /* if both offsets are NULL, keep current position */🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c` around lines 683 - 703, The code in ora_utl_file_fseek incorrectly binds the final else to the relative-offset check and applies both offsets; change the control flow so absolute offset (PG_ARGISNULL(1) check / absolute_offset) takes precedence: if arg1 provided, seek once to absolute_offset using fseek(fd, absolute_offset, SEEK_SET) (no prior rewind), else if arg2 provided, seek once by rel_offset via fseek(fd, rel_offset, SEEK_CUR), else do nothing (no implicit reset to 0); update the branches around fd, absolute_offset and rel_offset so only one fseek is performed according to this precedence and preserve error handling via CUSTOM_EXCEPTION on fseek failure.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In `@contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c`:
- Around line 85-86: The variable utl_file_umask_str is declared with extern and
immediately defined in the same file, creating a redundant declaration; remove
the line "extern char *utl_file_umask_str;" and keep only the definition "char
*utl_file_umask_str = NULL;" in utl_file.c so there is a single definition of
utl_file_umask_str.
- Around line 1105-1114: The loop in close_all_files can lose the original close
error because errno may change during subsequent iterations; modify
close_all_files to record the first failure's error details (e.g., save errno
into a local variable like first_errno and optionally the file name or fd) when
fclose(fd) != 0, set report_error, but do not overwrite first_errno on later
failures, and then call STRERROR_EXCEPTION(WRITE_ERROR) using that saved
first_errno (or formatted message based on it) so the thrown exception reflects
the initial close failure rather than a later errno value.
- Around line 1321-1358: The loop in get_line currently returns a truncated line
when csize hits max_linesize instead of signaling an overflow; modify get_line
to detect when csize == max_linesize, then drain the remainder of the physical
line from fd (consume characters until '\n' or EOF, handling '\r\n') to leave
the stream positioned after the logical line, set appropriate eof/iseof state,
and then raise/return a VALUE_ERROR (or the function's error mechanism)
indicating line too long; update references around variables csize,
max_linesize, fd, eof, buffer and the post-loop conversion/return block so that
when overflow is detected you do not perform normal decoding/memory returns for
truncated data but instead free any temporary buffers and propagate the
VALUE_ERROR.
- Around line 752-758: The GET_LINE branch currently emits an ereport(LOG, ...)
on normal EOF (when iseof is true), which causes noisy logs; update the code in
the GET_LINE/utl_file_get_line path to stop logging normal EOFs by removing or
changing the ereport(LOG, ...) call so the function simply returns
PG_RETURN_NULL() on iseof (leaving other error paths unchanged), i.e., eliminate
the ereport(LOG, (errcode(ERRCODE_NO_DATA_FOUND), errmsg("no data found")))
around the iseof handling.
- Around line 1137-1157: The function copy_text_file leaks the allocated buffer
when early-returning on fgets/fwrite failures; update copy_text_file to always
free buffer before any return by introducing a single cleanup path (e.g., set an
error code and goto cleanup) or explicitly call pfree(buffer) prior to each
return where fgets or fwrite fails, referencing the buffer variable and the
srcfile/dstfile read/write checks to ensure pfree(buffer) is invoked on all
error paths.
- Line 717: Replace the direct PG_RETURN_INT32(ftell(fd)) with a guarded
sequence: call ftell(fd) into a long (e.g., pos), check for error (pos == -1L)
and report/return an error via ereport/elog or appropriate PostgreSQL error
path, then check that pos fits into INT32 (compare against INT32_MAX/INT32_MIN)
and if it doesn't, raise/return an overflow error; finally cast to int and
return via PG_RETURN_INT32((int)pos). Use the symbols ftell, PG_RETURN_INT32,
INT32_MAX/INT32_MIN (and fd) to locate and implement the checks.
- Around line 683-703: The code in ora_utl_file_fseek incorrectly binds the
final else to the relative-offset check and applies both offsets; change the
control flow so absolute offset (PG_ARGISNULL(1) check / absolute_offset) takes
precedence: if arg1 provided, seek once to absolute_offset using fseek(fd,
absolute_offset, SEEK_SET) (no prior rewind), else if arg2 provided, seek once
by rel_offset via fseek(fd, rel_offset, SEEK_CUR), else do nothing (no implicit
reset to 0); update the branches around fd, absolute_offset and rel_offset so
only one fseek is performed according to this precedence and preserve error
handling via CUSTOM_EXCEPTION on fseek failure.
There was a problem hiding this comment.
Actionable comments posted: 4
♻️ Duplicate comments (2)
contrib/ivorysql_ora/sql/utl_file.sql (1)
90-100:⚠️ Potential issue | 🟠 Major
block_sizeassertions make this regression output host-dependent.
fgetattr’sblock_sizevaries by filesystem/mount options, so printing and asserting it makesutl_file.outfragile across environments.♻️ Suggested test-output hardening
- raise notice 'fexists = %, file_length = %, block_size = %', fexists, file_length, block_size; + raise notice 'fexists = %, file_length = %', fexists, file_length; ... - raise notice 'fexists = %, file_length = %, block_size = %', fexists, file_length, block_size; + raise notice 'fexists = %, file_length = %', fexists, file_length; ... - raise notice 'fexists = %, file_length = %, block_size = %', fexists, file_length, block_size; + raise notice 'fexists = %, file_length = %', fexists, file_length; ... - raise notice 'fexists = %, file_length = %, block_size = %', fexists, file_length, block_size; + raise notice 'fexists = %, file_length = %', fexists, file_length;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@contrib/ivorysql_ora/sql/utl_file.sql` around lines 90 - 100, The test prints and asserts fgetattr's block_size (variable block_size), which varies by filesystem and makes utl_file.out host-dependent; update the test around fgetattr/block_size to stop asserting an exact block_size and avoid relying on its printed value—either remove block_size from the raise notice output or replace strict assertions with a relaxed check (e.g., ensure block_size is positive/non-null or skip checks entirely) in the fgetattr handling so the regression output (utl_file.out) is stable across environments.contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c (1)
1137-1158:⚠️ Potential issue | 🟡 Minor
copy_text_fileleaksbufferon early return paths.Both
fgetsandfwritefailure exits bypasspfree(buffer).♻️ Suggested cleanup pattern
static int copy_text_file(FILE *srcfile, FILE *dstfile, int start_line, int end_line) { char *buffer; size_t len; int i; + int rc = 0; @@ if (fgets(buffer, MAX_LINESIZE, srcfile) == NULL) - return errno; /* EOF or error */ + { + rc = errno; /* EOF or error */ + goto cleanup; + } @@ if (fgets(buffer, MAX_LINESIZE, srcfile) == NULL) - return errno; /* EOF or error */ + { + rc = errno; /* EOF or error */ + goto cleanup; + } @@ if (fwrite(buffer, 1, len, dstfile) != len) - return errno; + { + rc = errno; + goto cleanup; + } } while(len > 0 && buffer[len - 1] != '\n'); } +cleanup: pfree(buffer); - - return 0; + return rc; }#!/bin/bash rg -n -A25 -B6 'static int\s+copy_text_file|return errno|pfree\(buffer\)' contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c` around lines 1137 - 1158, copy_text_file leaks the allocated buffer on early-return paths from failed fgets/fwrite; ensure buffer is freed before any return by adding a single cleanup path: allocate buffer at top, replace direct "return errno" in the fgets/fwrite failure checks with setting a local "err = errno" and jumping to a cleanup label (or call pfree(buffer) immediately before returning), then in the cleanup block pfree(buffer) and return err; references: function copy_text_file, local variable buffer, file handles srcfile/dstfile, and the fgets/fwrite failure checks.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@contrib/ivorysql_ora/sql/utl_file.sql`:
- Around line 121-143: The test covers reset and absolute fseek paths but not
the relative-offset branch; add a small block that sets a known position with
utl_file.fgetpos(f1), then call utl_file.fseek(f1, <non-zero relative offset>,
NULL) (i.e. pass a non-NULL relative_offset) to move relative to the current
position, then call utl_file.fgetpos and utl_file.get_line to verify the pointer
moved as expected; use the existing file handle names (f1), fgetpos, fseek,
get_line and raise notice/assertions to validate the relative seek, and ensure
cleanup (utl_file.fclose_all()) and exception handling mirrors the existing
pattern.
- Around line 163-165: The cleanup currently truncates sys.utl_file_directory
which is too broad; replace the truncate with a targeted delete that removes
only the directory row created by this test (e.g. use DELETE FROM
sys.utl_file_directory WHERE directory_name =
'<the_directory_name_used_in_this_script>' OR directory_path =
'<the_path_used>'), then COMMIT; this ensures only the specific entry inserted
by this script is removed and avoids dropping unrelated registry entries or
order-dependent failures.
In `@contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c`:
- Around line 437-443: The FCLOSE branch currently treats an invalid handle by
calling INVALID_FILEHANDLE_WARNING() and returning NULL; change it to raise the
proper exception like other functions: when free_slot(PG_GETARG_UINT32(0))
returns NULL in FCLOSE, replace the INVALID_FILEHANDLE_WARNING() and
PG_RETURN_NULL() calls with a single call to INVALID_FILEHANDLE_EXCEPTION() so
FCLOSE behaves consistently with fseek/ftell/get_line and the later code path
that uses INVALID_FILEHANDLE_EXCEPTION().
- Around line 527-534: copy_text_file returns an errno value which gets
clobbered by the subsequent fclose calls before IO_EXCEPTION() reads errno; fix
this by storing copy_result into a local variable (e.g. saved_errno), perform
fclose(srcfile) and fclose(dstfile), then restore errno = saved_errno before
calling IO_EXCEPTION(); reference symbols: copy_text_file, copy_result,
saved_errno (new), srcfile, dstfile, and IO_EXCEPTION.
---
Duplicate comments:
In `@contrib/ivorysql_ora/sql/utl_file.sql`:
- Around line 90-100: The test prints and asserts fgetattr's block_size
(variable block_size), which varies by filesystem and makes utl_file.out
host-dependent; update the test around fgetattr/block_size to stop asserting an
exact block_size and avoid relying on its printed value—either remove block_size
from the raise notice output or replace strict assertions with a relaxed check
(e.g., ensure block_size is positive/non-null or skip checks entirely) in the
fgetattr handling so the regression output (utl_file.out) is stable across
environments.
In `@contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c`:
- Around line 1137-1158: copy_text_file leaks the allocated buffer on
early-return paths from failed fgets/fwrite; ensure buffer is freed before any
return by adding a single cleanup path: allocate buffer at top, replace direct
"return errno" in the fgets/fwrite failure checks with setting a local "err =
errno" and jumping to a cleanup label (or call pfree(buffer) immediately before
returning), then in the cleanup block pfree(buffer) and return err; references:
function copy_text_file, local variable buffer, file handles srcfile/dstfile,
and the fgets/fwrite failure checks.
ℹ️ Review info
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
contrib/ivorysql_ora/expected/utl_file.outcontrib/ivorysql_ora/sql/utl_file.sqlcontrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c
Final draft for review
Summary by CodeRabbit
New Features
Tests