From 4e3ff3682abdd55f241d798a56bf1195be816815 Mon Sep 17 00:00:00 2001 From: himmel Date: Mon, 30 Nov 2026 16:00:34 +0800 Subject: [PATCH] docs: document UTL_FILE --- .../utl_file_impl.adoc | 125 ++++++ .../oracle_compatibility/compat_utl_file.adoc | 409 ++++++++++++++++++ .../utl_file_impl.adoc | 125 ++++++ .../oracle_compatibility/compat_utl_file.adoc | 409 ++++++++++++++++++ 4 files changed, 1068 insertions(+) create mode 100644 CN/modules/ROOT/pages/master/compatibility_features_design/utl_file_impl.adoc create mode 100644 CN/modules/ROOT/pages/master/oracle_compatibility/compat_utl_file.adoc create mode 100644 EN/modules/ROOT/pages/master/compatibility_features_design/utl_file_impl.adoc create mode 100644 EN/modules/ROOT/pages/master/oracle_compatibility/compat_utl_file.adoc diff --git a/CN/modules/ROOT/pages/master/compatibility_features_design/utl_file_impl.adoc b/CN/modules/ROOT/pages/master/compatibility_features_design/utl_file_impl.adoc new file mode 100644 index 00000000..127907b1 --- /dev/null +++ b/CN/modules/ROOT/pages/master/compatibility_features_design/utl_file_impl.adoc @@ -0,0 +1,125 @@ +:sectnums: +:sectnumlevels: 5 + += UTL_FILE 包实现说明 + +== 目的 + +IvorySQL 实现 Oracle 的 `UTL_FILE` 包,提供服务端文本文件 I/O 能力,支持文件的打开、关闭、读写、刷新、位置定位、属性查询以及复制、删除和重命名。其公开 API、打开模式、行长限制、最多 50 个同时打开文件的上限以及异常命名均与 Oracle 保持一致。用户示例见 xref:master/oracle_compatibility/compat_utl_file.adoc[UTL_FILE 包]。 + +实现同时补齐了 PostgreSQL 内置文件函数不具备的两层安全机制: + +* `sys.utl_file_directory` 注册表,以白名单方式限定可访问目录,对应 Oracle 的目录对象; +* `utl_file.umask` GUC 参数,控制 `FOPEN` 创建文件的权限掩码。 + +== 实现说明 + +=== 代码组织与调用关系 + +[cols="3,3",options="header"] +|=== +|源码路径 |职责 +|`contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file--1.0.sql` |注册 C 入口 `sys.ora_utl_file_*`、复合类型(`ORA_UTL_FILE_FILE_TYPE`、`ora_utl_file_fgetattr_result`)、`sys.utl_file_directory` 表,以及 `UTL_FILE` 包说明与包体 +|`contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c` |C 实现:路径安全检查、句柄槽位管理、基于 stdio 的 I/O、umask GUC 钩子 +|`contrib/ivorysql_ora/sql/utl_file.sql` |回归用例 +|`contrib/ivorysql_ora/expected/utl_file.out` |预期结果 +|`Makefile`、`meson.build`、`ivorysql_ora_merge_sqls` |新目录的构建集成与 SQL 合并 +|`src/ivorysql_ora.c` |在 `_PG_init` 中声明 `utl_file.umask` 自定义 GUC +|=== + +[source,text] +---- +UTL_FILE.FOPEN(location, filename, open_mode, max_linesize) + → 包体: 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()(文件末尾返回 NULL) +---- + +包体中的 `UTL_FILE.*` 子程序只是薄封装:拆开复合文件句柄,把数字槽位 id 转发给 `sys.ora_utl_file_*` C 入口。`FOPEN_NCHAR`/`GET_LINE_NCHAR`/`PUT_LINE_NCHAR` 显式传入编码名 `UTF8`;不带编码参数的 `FOPEN` 使用数据库编码。 + +=== 安全模型 + +==== 目录注册表 + +访问被限制在注册于 `sys.utl_file_directory (dirname name PRIMARY KEY, dir TEXT)` 的目录内。先 `REVOKE ALL ... FROM PUBLIC` 再 `GRANT SELECT TO PUBLIC`,即只有超级用户能维护注册表,普通用户只读可见。 + +所有把 `location` + `filename` 拼接为文件系统路径的操作都要经过 `get_safe_path()`: + +. `safe_named_location()` 按 `dirname` 精确等值查找(有意不用 `LIKE`,避免 `_`/`%` 的特殊语义),命中则替换为注册路径。 +. 拼出完整路径后先做 `canonicalize_path()` 规范化。 +. `check_secure_locality()` 通过缓存的 SPI 查询,用带显式 `/` 处理的前缀比较验证规范化后的路径位于某个已注册目录之内: + +[source,text] +---- +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 +---- + +没有任何注册目录命中时报 `INVALID_PATH`(`errdetail: File location is invalid.`,`errhint: locality is not found in sys.utl_file_directory table`)。由于检查在规范化后的完整路径上进行,`..` 之类的路径穿越在匹配前已被解析成真实路径,无法把写入范围偷渡到注册目录之外。 + +==== utl_file.umask + +`FOPEN` 创建的文件权限为 `fopen()` 的默认模式套用 `utl_file.umask` 掩码(默认 `0077`)。实现上在 `fopen()` 调用前后用 `umask()` 保存/恢复进程级掩码,不影响进程中的其他操作。 + +该 GUC 以字符串类型声明,并挂载 check/assign 钩子: + +* check 钩子拒绝非八进制数字;在正常处理模式下要求超级用户,否则报 `ERCODE_INSUFFICIENT_PRIVILEGE`; +* assign 钩子把字符串转成整数供 `FOPEN` 使用。 + +=== 句柄管理 + +句柄存放在 50 个固定槽位(`MAX_SLOTS`,与 Oracle 10g 一致)中,槽位记录 `FILE*`、`max_linesize` 和编码。`FOPEN` 分配槽位并把数字 id 存入复合文件句柄;超过上限时报 `ERRCODE_PROGRAM_LIMIT_EXCEEDED`。 + +实现有意不使用 PostgreSQL 的 `AllocateFile`:它会在事务提交/中止时自动关闭文件,而 Oracle 兼容的句柄必须在 `COMMIT` 后继续存活。因此改用: + +* `ResourceOwner` 释放回调,在事务中止或会话结束时关闭句柄; +* `before_shmem_exit` 钩子做最终兜底,即使后端异常退出也能刷缓冲并关闭文件。 + +由此得到文档所述的生命周期:`IS_OPEN` 在 `COMMIT` 后仍为 `TRUE`,`ROLLBACK` 后变为 `FALSE`,会话退出后所有句柄消失。`FCLOSE_ALL` 关闭本会话持有的全部槽位。 + +=== I/O 行为与异常 + +* 全部文本 I/O 走 stdio,并在打开时记录编码,`GET_LINE`/`PUT_LINE` 由此在数据库编码与文件编码之间转换。 +* `GET_LINE` 的返回量取 `len`、到下一行终止符的距离、`max_linesize` 三者的最小值——即 Oracle Operational Notes 的规则;行终止符本身不存入缓冲区,读空行得到空字符串。 +* `GET_LINE` 每次最多读取 `max_linesize` 字节(`len` 参数可临时调低);读到文件末尾时以 `LOG` 级别记录 `no data found` 并返回 `NULL`,调用方可以直接用 `WHILE line IS NOT NULL` 循环。`NO_DATA_FOUND` 因此体现在服务器日志中,而不是作为错误抛出。 +* `PUTF` 实现 Oracle 的受限 `printf()` 格式:`\n` 替换为平台行终止符,`%s` 依次消耗参数(多余的格式符与 `NULL` 参数都渲染为空字符串),`%%` 为 IvorySQL 扩展、输出字面量 `%`。`CHECK_LENGTH` 守卫在累计输出超过 `max_linesize` 时立即抛出 `VALUE_ERROR`("buffer is too short")。 +* `FSEEK` 支持绝对偏移(`SEEK_SET`,先 `rewind`)与相对偏移(`SEEK_CUR`,可为负);两个参数都为 `NULL` 时位置重置为 0。非法组合报 `INVALID_OFFSET`。 +* `FFLUSH` 显式对流执行 `fflush()`,这是让缓冲写入对并发打开的读句柄可见的关键。 +* `FGETATTR` 通过复合类型返回 `(fexists, file_length, block_size)`;`file_length` 以 `numeric` 承载以对应 Oracle 的 `NUMBER`。 +* `FCOPY` 支持按行区间复制(`start_line` 必须为正);`FRENAME` 在 `overwrite = TRUE` 之前拒绝覆盖目标文件(`WRITE_ERROR: Destination file already exists`)。 + +Oracle 兼容异常(`INVALID_FILEHANDLE`、`INVALID_MAXLINESIZE`、`INVALID_MODE`、`INVALID_OFFSET`、`INVALID_OPERATION`、`INVALID_PATH`、`READ_ERROR`、`VALUE_ERROR`、`WRITE_ERROR`)以 `ERRCODE_RAISE_EXCEPTION` 抛出、以 Oracle 异常名作为 `SQLERRM`,因此 `WHEN OTHERS` + `SQLERRM` 可以复现 Oracle 的错误处理风格。Oracle 定义的异常集合更大(还包括 `ACCESS_DENIED`、`CHARSETMISMATCH`、`DELETE_FAILED`、`FILE_OPEN`、`INTERNAL_ERROR`、`INVALID_FILENAME`、`RENAME_FAILED`);实现未针对这些条件做专门识别,底层操作系统错误会以上表中最接近的名称抛出,`DETAIL` 字段中带 `strerror(errno)` 文本。 + +== 错误处理示例 + +=== 未注册的目录 + +[source,sql] +---- +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 +---- + +目录未在 `sys.utl_file_directory` 中注册时,路径检查在打开文件之前报错。示例假设 `wrong_directory` 未注册,也不是已注册目录下的有效路径。 + +== 回归验证 + +`utl_file` 回归组覆盖:对未注册目录执行 `FOPEN`(`INVALID_PATH`)、`PUT_LINE`/`PUT`/`NEW_LINE`/`PUTF`/`GET_LINE` 的写入读回闭环(含按 `len` 截短的读取)、`FGETATTR`/`FCOPY`/`FREMOVE`/`FRENAME`、`FFLUSH` 可见性屏障与 `FSEEK`/`FGETPOS` 的绝对/相对定位、配合 `FCLOSE_ALL` 的异常处理,以及 `COMMIT`/`ROLLBACK` 跨越下的句柄生命周期。 + +在已完成配置构建的 IvorySQL 源码树中执行 `make -C contrib/ivorysql_ora oracle-installcheck ORA_REGRESS=utl_file` 即可验证本测试组。目标实例需安装匹配版本的 `ivorysql_ora` 扩展。 diff --git a/CN/modules/ROOT/pages/master/oracle_compatibility/compat_utl_file.adoc b/CN/modules/ROOT/pages/master/oracle_compatibility/compat_utl_file.adoc new file mode 100644 index 00000000..e18ee5da --- /dev/null +++ b/CN/modules/ROOT/pages/master/oracle_compatibility/compat_utl_file.adoc @@ -0,0 +1,409 @@ +:sectnums: +:sectnumlevels: 5 + += UTL_FILE 包 + +== 目的 + +`UTL_FILE` 包用于在 PL/iSQL 中读写服务器上的文本文件,也提供查询文件属性、复制、删除和重命名文件的过程。`FOPEN` 返回 `sys.ORA_UTL_FILE_FILE_TYPE` 类型的句柄,后续读写和关闭操作使用该句柄。 + +== 功能说明 + +=== 安全前提 + +`UTL_FILE` 使用 `sys.utl_file_directory` 表限制可访问的目录。使用文件操作前,需要先在表中注册目录。 + +[source,sql] +---- +CREATE TABLE sys.utl_file_directory( + dirname name PRIMARY KEY, + dir TEXT +); +---- + +* 普通用户对该表只有 `SELECT` 权限;新增、删除注册目录需要超级用户权限。对应 Oracle 中仅默认授予 `SYS`、`SYSTEM` 的 `CREATE DIRECTORY` 权限。 +* 使用前先注册目录,之后通过 `dirname` 名称引用: + +[source,sql] +---- +-- 将数据目录注册为名为 'data_directory' 的目录对象 +INSERT INTO sys.utl_file_directory(dirname, dir) +VALUES ('data_directory', current_setting('data_directory')); +---- + +* `location` 参数既可以是已注册的 `dirname`,也可以是原始路径。原始路径会先做规范化,并且必须落在某个已注册目录之内(前缀匹配),否则报 `INVALID_PATH`。 +* 与 Oracle 一致,**已注册目录的子目录不会自动获得访问权**,必须以完整路径单独注册。 +* 文件权限掩码:`FOPEN` 创建的文件受 `utl_file.umask` 参数控制(默认 `0077`)。仅超级用户可以修改该参数,取值必须为 3–4 位八进制数字: + +[source,sql] +---- +SET utl_file.umask = '0022'; +SHOW utl_file.umask; +---- + +=== 函数与过程一览 + +[cols="4,2,4",options="header"] +|=== +|调用 |返回类型 |说明 +|`FOPEN(location, filename, open_mode [, max_linesize])` |`ORA_UTL_FILE_FILE_TYPE` |打开文件用于输入或输出。`open_mode` 为单字符:`R`(读)、`W`(写,截断)、`A`(追加)。`max_linesize` 默认 1024,范围 1–32767 +|`FOPEN_NCHAR(location, filename, open_mode [, max_linesize])` |`ORA_UTL_FILE_FILE_TYPE` |以 Unicode 模式打开文件用于输入或输出,文件以 UTF-8 而非数据库字符集读写。参数同 `FOPEN` +|`IS_OPEN(file)` |`BOOLEAN` |测试句柄是否指向一个已打开但尚未关闭的文件 +|`FCLOSE(file)` |— |关闭文件句柄标识的已打开文件 +|`FCLOSE_ALL` |— |关闭当前会话打开的所有文件句柄;属应急清理过程,例如 PL/iSQL 程序因异常退出时使用 +|`FFLUSH(file)` |— |把所有待写入数据物理写入文件;适用于文件尚未关闭就需要读取的场景(如调试信息) +|`FGETPOS(file)` |`INTEGER` |返回文件内当前的相对偏移位置(字节);`0` 表示文件开头 +|`FSEEK(file [, absolute_offset [, relative_offset]])` |— |按指定字节数向前或向后调整文件指针。`absolute_offset` 为相对文件开头的字节位置;`relative_offset` 相对当前位置向前(正数)或向后(负数)移动;两者都省略时 IvorySQL 将位置重置为 0 +|`GET_LINE(file, buffer OUT, [len])` |— |读取文本到 `buffer`,遇到行终止符(不含终止符本身)、文件末尾或 `len` 字节三者中先到者即停止。`len` 默认取 `max_linesize`;两者都指定时以较小值为准。读到文件末尾返回 `NULL` +|`GET_LINE_NCHAR(file, buffer OUT, [len])` |— |从 `FOPEN_NCHAR` 打开的文件中按 Unicode 读取文本 +|`NEW_LINE(file [, lines])` |— |写入一个或多个操作系统相关的行终止符(默认 1)。与 `PUT` 分开的原因是行终止符是平台相关的字符序列 +|`PUT(file, buffer)` |— |把 `buffer` 中的字符串写入文件,不追加行终止符;需要用 `NEW_LINE` 或 `PUT_LINE` 结束一行 +|`PUTF(file, format [, arg1..arg5])` |— |带格式的 `PUT`,类似功能受限的 `printf()`。`format` 中的 `%s` 依次被 `arg1`–`arg5` 替换,`\n` 替换为平台行终止符,`%%` 表示字面量 `%`(IvorySQL 扩展)。`%s` 多于参数时以空字符串替换 +|`PUT_LINE(file, buffer [, autoflush])` |— |写入一行并追加平台相关的行终止符;`autoflush = TRUE` 时写完立即把缓冲区刷到磁盘 +|`PUT_LINE_NCHAR(file, buffer)` |— |向 `FOPEN_NCHAR` 打开的文件写入 Unicode 行;追加行终止符 +|`PUT_RAW(file, buffer [, autoflush])` |— |把 `BYTEA` 值(对应 Oracle 的 `RAW`)写入文件,不追加行终止符;`autoflush = TRUE` 时写完即刷新 +|`FCOPY(src_location, src_filename, dest_location, dest_file [, start_line [, end_line]])` |— |把文件的连续部分复制到新建文件。默认复制整个文件;`start_line`(默认 1)与 `end_line`(默认为文件末尾)可选地选取源文件中间的一段。源文件以读模式打开,目标文件以写模式打开 +|`FREMOVE(location, filename)` |— |删除磁盘文件(需具备足够权限);文件与目录权限由操作系统校验 +|`FRENAME(src_location, src_filename, dest_location, dest_filename [, overwrite])` |— |把文件重命名为新名称,类似 UNIX 的 `mv` 命令。`overwrite` 默认 `FALSE`;目标文件已存在且 `overwrite` 为 `FALSE` 时报 `WRITE_ERROR` +|`FGETATTR(location, filename, fexists OUT, file_length OUT, block_size OUT)` |— |读取并返回磁盘文件属性:是否存在、字节长度(文件不存在时为 `NULL`)、文件系统块大小(文件不存在时为 `NULL`) +|=== + +与 Oracle 相比尚未实现:`GET_RAW`、`PUT_NCHAR`、`PUTF_NCHAR`,以及字节模式(`rb`/`wb`/`ab`)打开。 + +文件句柄类型与 Oracle 私有 `FILE_TYPE` 记录逐字段对应;用户不应引用或修改其内容: + +[source,sql] +---- +CREATE TYPE sys.ORA_UTL_FILE_FILE_TYPE AS(id INTEGER, datatype INTEGER, byte_mode BOOLEAN); +---- + +=== 调用方式 + +`UTL_FILE` 的子程序通常在 PL/iSQL 匿名块中调用: + +[source,sql] +---- +DECLARE + f sys.ora_utl_file_file_type; + line TEXT; +BEGIN + f := UTL_FILE.FOPEN('data_directory', 'regress.txt', 'W'); + + UTL_FILE.PUT_LINE(f, 'abc'); + UTL_FILE.PUT_LINE(f, '-----'); + UTL_FILE.FCLOSE(f); + + f := UTL_FILE.FOPEN('data_directory', 'regress.txt', 'R'); + UTL_FILE.GET_LINE(f, line); + WHILE line IS NOT NULL LOOP + RAISE NOTICE '>>%<<', line; + UTL_FILE.GET_LINE(f, line); + END LOOP; + UTL_FILE.FCLOSE(f); +END; +/ +---- + +在 Oracle 兼容模式(`ivorysql.compatible_mode = oracle`)下可直接使用。与 Oracle 相同,文件位置与文件名作为独立字符串传入,以便对位置做注册表校验;两者拼在一起必须在操作系统上是合法的文件名。 + +=== 打开模式 + +遵循 Oracle `FOPEN` 的定义: + +[cols="2,4,4",options="header"] +|=== +|模式 |说明 |备注 +|`R` |读文本 |文件必须已存在 +|`W` |写文本并截断 |文件不存在则创建,已存在则清空 +|`A` |追加文本 |写入内容添加到文件末尾;文件不存在时会创建,与 Oracle「append 模式下文件不存在则以写模式创建」的说明一致 +|=== + +模式参数不区分大小写(`'r'`、`'w'`、`'a'` 均可),其他取值报 `INVALID_MODE`。Oracle 还支持字节模式 `rb`、`wb`、`ab`,IvorySQL 暂不支持。 + +=== 操作规则 + +使用文件句柄时需要注意以下限制: + +* **GET_LINE 实际返回的字节数**取三者的最小值:`GET_LINE` 的 `len` 参数、到下一个行终止符之间的字节数、`FOPEN` 指定的 `max_linesize`。行终止符本身不会读入缓冲区,因此读空行得到空字符串。 +* **max_linesize** 取值范围 1–32767,未指定时默认 1024。`GET_LINE` 的 `len` 参数遵循相同范围;`max_linesize` 与 `len` 取值不同时以较小者为准。 +* **字符集**:`FOPEN` 打开的文件预期使用数据库字符集编码,`FOPEN_NCHAR` 打开的文件预期使用 UTF-8 编码。以非预期字符集读文件时结果不可预测。 +* **连续 PUT 的总写入量**在两次刷新之间不应超过行限制;超出 `max_linesize` 报 `VALUE_ERROR`("buffer is too short")。 +* **同时打开文件数上限**:每个会话最多同时打开 50 个文件(与 Oracle 相同),超过后 `FOPEN` 报 "program limit exceeded" 错误。 +* 文件位置与文件名参数中不能使用操作系统相关的参数(如 UNIX 环境变量)。 + +== 语法示例 + +逐行写入并读回文件: + +[source,sql] +---- +DECLARE + f sys.ora_utl_file_file_type; + line TEXT; + i INTEGER; +BEGIN + f := UTL_FILE.FOPEN('data_directory', 'regress.txt', 'W'); + + UTL_FILE.PUT_LINE(f, 'abc'); + UTL_FILE.PUT_LINE(f, '123'::numeric); + UTL_FILE.NEW_LINE(f, 2); + UTL_FILE.PUT(f, 'a'); + UTL_FILE.PUT(f, 'b'); + UTL_FILE.NEW_LINE(f); + UTL_FILE.PUTF(f, '[1=%s, 2=%s]', 'one', 'two'); + UTL_FILE.NEW_LINE(f); + UTL_FILE.FCLOSE(f); + + f := UTL_FILE.FOPEN('data_directory', 'regress.txt', 'R'); + i := 1; + UTL_FILE.GET_LINE(f, line); + WHILE line IS NOT NULL LOOP + RAISE NOTICE '[%] >>%<<', i, line; + UTL_FILE.GET_LINE(f, line); + i := i + 1; + END LOOP; + UTL_FILE.FCLOSE(f); + + EXCEPTION + WHEN OTHERS THEN + RAISE NOTICE 'exception: %', sqlerrm; + UTL_FILE.FCLOSE_ALL(); +END; +/ +---- + +输出: + +[source,text] +---- +NOTICE: [1] >>abc<< +NOTICE: [2] >>123<< +NOTICE: [3] >><< +NOTICE: [4] >>ab<< +NOTICE: [5] >>[1=one, 2=two]<< +---- + +使用 `PUTF` 写入格式化文本: + +[source,sql] +---- +DECLARE + my_world VARCHAR2 := 'Zork'; + f sys.ora_utl_file_file_type; +BEGIN + f := UTL_FILE.FOPEN('data_directory', 'zork.txt', 'W'); + UTL_FILE.PUTF(f, 'Hello, world!\nI come from %s with %s.\n', + my_world, + 'greetings for all earthlings'); + UTL_FILE.FCLOSE(f); +END; +/ +---- + +文件属性、复制、删除与重命名: + +[source,sql] +---- +DECLARE + fexists BOOLEAN; + file_length NUMBER; + block_size INTEGER; +BEGIN + UTL_FILE.FCOPY('data_directory', 'regress.txt', 'data_directory', 'regress2.txt'); + UTL_FILE.FGETATTR('data_directory', 'regress2.txt', fexists, file_length, block_size); + RAISE NOTICE 'fexists = %, file_length = %, block_size = %', fexists, file_length, block_size; + + UTL_FILE.FREMOVE('data_directory', 'regress2.txt'); + UTL_FILE.FGETATTR('data_directory', 'regress2.txt', fexists, file_length, block_size); + RAISE NOTICE 'fexists = %', fexists; + + UTL_FILE.FRENAME('data_directory', 'regress.txt', 'data_directory', 'regress2.txt', TRUE); +END; +/ +---- + +输出: + +[source,text] +---- +NOTICE: fexists = t, file_length = 24, block_size = 4096 +NOTICE: fexists = f +---- + +`max_linesize` 和 `len` 的用法:`GET_LINE` 请求的字节数超过 `FOPEN` 的 `max_linesize`,实际返回字节数以较小值为上限: + +[source,sql] +---- +DECLARE + v1 TEXT; + f1 sys.ora_utl_file_file_type; +BEGIN + -- MAX_LINESIZE(256)小于 GET_LINE 的长度请求(32767), + -- 因此返回字节数为 256 以内(若提前遇到行终止符则更少)。 + f1 := UTL_FILE.FOPEN('data_directory', 'u12345.tmp', 'R', 256); + UTL_FILE.GET_LINE(f1, v1, 32767); + UTL_FILE.FCLOSE(f1); + + -- FOPEN 的 MAX_LINESIZE 为空时默认 1024, + -- 因此返回字节数为 1024 以内(若提前遇到行终止符则更少)。 + f1 := UTL_FILE.FOPEN('data_directory', 'u12345.tmp', 'R'); + UTL_FILE.GET_LINE(f1, v1, 32767); + UTL_FILE.FCLOSE(f1); + + -- GET_LINE 未指定字节数时默认取 FOPEN 的 MAX_LINESIZE, + -- 后者为空时同样默认 1024。 + f1 := UTL_FILE.FOPEN('data_directory', 'u12345.tmp', 'R'); + UTL_FILE.GET_LINE(f1, v1); + UTL_FILE.FCLOSE(f1); +END; +/ +---- + +`FFLUSH`、`FSEEK` 与 `FGETPOS` 配合可实现「先写后读」:缓冲区中的数据只有经过 `FFLUSH` 后对其他句柄可见,`FSEEK` 可以跳转到记录下来的偏移位置: + +[source,sql] +---- +DECLARE + f sys.ora_utl_file_file_type; + f1 sys.ora_utl_file_file_type; + line TEXT; + line2_pos INTEGER; +BEGIN + f := UTL_FILE.FOPEN('data_directory', 'regressflush.txt', 'W'); + f1 := UTL_FILE.FOPEN('data_directory', 'regressflush.txt', 'R'); + + FOR i IN 1..5 LOOP + UTL_FILE.PUT_LINE(f, 'line ' || i::text); + END LOOP; + + UTL_FILE.FFLUSH(f); -- 使缓冲数据对读句柄可见 + + UTL_FILE.FSEEK(f1); -- 读位置重置到 0 + UTL_FILE.GET_LINE(f1, line); + line2_pos := UTL_FILE.FGETPOS(f1); -- 记下第 2 行的偏移 + + WHILE line IS NOT NULL LOOP + RAISE NOTICE '>>%<<', line; + UTL_FILE.GET_LINE(f1, line); + END LOOP; + + UTL_FILE.FSEEK(f1, line2_pos, NULL); -- 绝对定位回第 2 行 + UTL_FILE.GET_LINE(f1, line); + RAISE NOTICE '>>%<<', line; + + UTL_FILE.FSEEK(f1, NULL, -7); -- 相对定位回退一条记录 + UTL_FILE.GET_LINE(f1, line); + RAISE NOTICE '>>%<<', line; + + UTL_FILE.FCLOSE_ALL(); +END; +/ +---- + +已知字节偏移时,可以用 `FSEEK` 回到之前的位置。在到达指定字节数之前先到达文件开头时,文件指针落在文件开头;先到达文件末尾时则报 `INVALID_OFFSET`。 + +== 异常 + +`UTL_FILE` 抛出 Oracle 风格的异常,可用 `WHEN OTHERS` 捕获并通过 `SQLERRM` 查看。异常集合遵循 Oracle 的 *UTL_FILE Exceptions* 表: + +[cols="3,5",options="header"] +|=== +|异常 |说明 +|`INVALID_PATH` |文件位置无效 +|`INVALID_MODE` |`FOPEN` 的 `open_mode` 参数无效 +|`INVALID_FILEHANDLE` |文件句柄无效 +|`INVALID_OPERATION` |文件无法按要求打开或操作,例如对以 `W`/`A` 模式打开的句柄执行读取 +|`READ_ERROR` |目标缓冲区过小,或读取过程中发生操作系统错误 +|`WRITE_ERROR` |写入过程中发生操作系统错误;`FRENAME` 发现目标文件已存在且 `overwrite` 为 `FALSE` 时同样报此异常 +|`INTERNAL_ERROR` |未指定的 PL/iSQL 错误 +|`CHARSETMISMATCH` |文件用 `FOPEN_NCHAR` 打开,但后续 I/O 使用了 `PUTF`、`GET_LINE` 等非 NCHAR 函数 +|`FILE_OPEN` |因文件处于打开状态导致请求的操作失败 +|`INVALID_MAXLINESIZE` |`FOPEN()` 的 `max_linesize` 取值无效,应在 1 到 32767 之间 +|`INVALID_FILENAME` |`filename` 参数无效 +|`ACCESS_DENIED` |访问文件位置的权限被拒绝 +|`INVALID_OFFSET` |触发原因:`absolute_offset < 0`,或偏移导致定位越过文件末尾 +|`DELETE_FAILED` |请求的文件删除操作失败 +|`RENAME_FAILED` |请求的文件重命名操作失败 +|`NO_DATA_FOUND` |预定义异常;见下文文件末尾行为说明 +|`VALUE_ERROR` |预定义异常;写入数据超过 `max_linesize` 时抛出 +|=== + +`UTL_FILE` 的过程也可能抛出其他预定义 PL/iSQL 异常。 + +文件末尾行为:Oracle 中 `GET_LINE` 读过文件末尾时抛出 `NO_DATA_FOUND`;IvorySQL 改为以 `LOG` 级别记录(`no data found`)并返回 `NULL`,因此 `WHILE line IS NOT NULL` 循环写法可以直接使用: + +[source,sql] +---- +DECLARE + f sys.ora_utl_file_file_type; + line TEXT; +BEGIN + f := UTL_FILE.FOPEN('data_directory', 'regress.txt', 'R'); + UTL_FILE.GET_LINE(f, line); + WHILE line IS NOT NULL LOOP + RAISE NOTICE '>>%<<', line; + UTL_FILE.GET_LINE(f, line); + END LOOP; + UTL_FILE.FCLOSE(f); +END; +/ +---- + +错误处理示例: + +[source,sql] +---- +DECLARE + f sys.ora_utl_file_file_type; +BEGIN + -- 'wrong_directory' 未注册,报 INVALID_PATH + f := UTL_FILE.FOPEN('wrong_directory', 'regress.txt', 'A', 1024); +END; +/ +---- + +[source,text] +---- +ERROR: INVALID_PATH +DETAIL: File location is invalid. +HINT: locality is not found in sys.utl_file_directory table +---- + +== 与 Oracle 的差异 + +与 Oracle 的主要差异如下: + +[cols="2,4",options="header"] +|=== +|方面 |IvorySQL 行为 +|目录对象 |使用 `sys.utl_file_directory` 表替代 Oracle 的 `CREATE DIRECTORY`/`ALL_DIRECTORIES`;同时接受位于已注册目录之下的原始路径 +|文件末尾 |`GET_LINE` 读到 EOF 返回 `NULL`;Oracle 抛出 `NO_DATA_FOUND` +|字节模式 |不支持 `rb`/`wb`/`ab` 打开模式,传入报 `INVALID_MODE`。句柄类型中保留 `byte_mode` 字段供将来使用 +|缺失的子程序 |`GET_RAW`、`PUT_NCHAR`、`PUTF_NCHAR` 尚未实现 +|`FSEEK` 两个偏移均为 `NULL` |重置文件位置为 0;Oracle 抛出 `INVALID_OFFSET` +|`PUTF` 格式串 |支持 `%%` 表示字面量 `%`(IvorySQL 扩展);没有对应参数的 `%s` 替换为空字符串,与 Oracle 一致 +|`FCLOSE_ALL` 与 `IS_OPEN` |`FCLOSE_ALL` 之后 `IS_OPEN` 在 IvorySQL 中返回 `FALSE`;Oracle 对未改动的句柄仍返回 `TRUE` +|异常集合 |实现中未专门识别的异常(`ACCESS_DENIED`、`DELETE_FAILED`、`RENAME_FAILED`、`FILE_OPEN`、`CHARSETMISMATCH`、`INVALID_FILENAME`、`INTERNAL_ERROR`)会以最接近的 Oracle 异常抛出,通常是 `INVALID_PATH`/`INVALID_OPERATION`/`READ_ERROR`/`WRITE_ERROR`,`DETAIL` 中带操作系统错误文本 +|文件属主 |UNIX 上 `FOPEN` 创建的文件属主为数据库服务器运行用户,与 Oracle 一致;权限按 `utl_file.umask` 掩码设置 +|=== + +== 事务与会话生命周期 + +文件句柄在 `COMMIT` 后仍然有效;事务回滚或会话结束时自动关闭,避免缓冲数据静默丢失: + +[source,sql] +---- +BEGIN + f := UTL_FILE.FOPEN('data_directory','regress.txt','A',1024); + RAISE NOTICE 'is_open = %', UTL_FILE.IS_OPEN(f); -- t + COMMIT; + RAISE NOTICE 'is_open = %', UTL_FILE.IS_OPEN(f); -- t + ROLLBACK; + RAISE NOTICE 'is_open = %', UTL_FILE.IS_OPEN(f); -- f +END; +/ +---- + +== 实现说明 + +安全模型、句柄管理与内部实现见 xref:master/compatibility_features_design/utl_file_impl.adoc[UTL_FILE 实现设计]。 diff --git a/EN/modules/ROOT/pages/master/compatibility_features_design/utl_file_impl.adoc b/EN/modules/ROOT/pages/master/compatibility_features_design/utl_file_impl.adoc new file mode 100644 index 00000000..9f0d14fd --- /dev/null +++ b/EN/modules/ROOT/pages/master/compatibility_features_design/utl_file_impl.adoc @@ -0,0 +1,125 @@ +:sectnums: +:sectnumlevels: 5 + += UTL_FILE package implementation + +== 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 xref:master/oracle_compatibility/compat_utl_file.adoc[UTL_FILE package]. + +Two security mechanisms that PostgreSQL's built-in file functions do not provide are added alongside: + +* a `sys.utl_file_directory` registry table that whitelists accessible directories, mirroring Oracle's directory objects; +* a `utl_file.umask` GUC that controls the permission mask of files created by `FOPEN`. + +== Implementation + +=== Code organization and call path + +[cols="3,3",options="header"] +|=== +|Source path |Responsibility +|`contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file--1.0.sql` |Registers the C entry points `sys.ora_utl_file_*`, the composite types (`ORA_UTL_FILE_FILE_TYPE`, `ora_utl_file_fgetattr_result`), the `sys.utl_file_directory` table, and the `UTL_FILE` package specification and body +|`contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c` |C implementation: path security checks, handle slot management, stdio-based I/O, umask GUC hooks +|`contrib/ivorysql_ora/sql/utl_file.sql` |Regression cases +|`contrib/ivorysql_ora/expected/utl_file.out` |Expected results +|`Makefile`, `meson.build`, `ivorysql_ora_merge_sqls` |Build integration and SQL merge for the new directory +|`src/ivorysql_ora.c` |Declares the `utl_file.umask` custom GUC in `_PG_init` +|=== + +[source,text] +---- +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. + +=== Security model + +==== 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 exact `dirname` equality (deliberately not `LIKE`, 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: + +[source,text] +---- +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. + +==== 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_PRIVILEGE` otherwise); +* the assign hook converts the string to an integer used by `FOPEN`. + +=== 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 `ResourceOwner` release callback closes handles on transaction abort or session end; +* a `before_shmem_exit` hook 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. + +=== I/O behavior and exceptions + +* All text I/O goes through stdio with the encoding recorded at open time, so `GET_LINE`/`PUT_LINE` perform conversion between the database encoding and the file encoding. +* `GET_LINE` returns at most the lesser of `len`, the distance to the next line terminator, and `max_linesize` — the Oracle *Operational Notes* rule; the terminator itself is not stored, and blank lines yield empty strings. +* `GET_LINE` reads up to `max_linesize` bytes per call (`len` temporarily lowers it); at EOF it logs `no data found` at `LOG` level and returns `NULL`, so callers can loop on `WHILE line IS NOT NULL`. The `NO_DATA_FOUND` condition is therefore observable in the server log rather than raised as an error. +* `PUTF` implements Oracle's limited-`printf()` format: `\n` becomes the platform line terminator, `%s` consumes the next argument (unmatched formatters render as an empty string, including `NULL` arguments), and `%%` is an IvorySQL extension producing a literal `%`. A `CHECK_LENGTH` guard raises `VALUE_ERROR` ("buffer is too short") as soon as the accumulated output exceeds `max_linesize`. +* `FSEEK` supports absolute (`SEEK_SET`, preceded by a `rewind`) and relative (`SEEK_CUR`, may be negative) offsets; both `NULL` resets the position to 0. Invalid combinations raise `INVALID_OFFSET`. +* `FFLUSH` explicitly `fflush()`es the stream, which is what makes buffered writes visible to a concurrently opened read handle. +* `FGETATTR` returns `(fexists, file_length, block_size)` via a composite type; `file_length` is carried as `numeric` to match Oracle's `NUMBER`. +* `FCOPY` copies line ranges (`start_line` must be positive); `FRENAME` refuses to clobber the destination unless `overwrite = 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. + +== Error Handling Example + +=== Unregistered directory + +[source,sql] +---- +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. + +== 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. diff --git a/EN/modules/ROOT/pages/master/oracle_compatibility/compat_utl_file.adoc b/EN/modules/ROOT/pages/master/oracle_compatibility/compat_utl_file.adoc new file mode 100644 index 00000000..aa5618da --- /dev/null +++ b/EN/modules/ROOT/pages/master/oracle_compatibility/compat_utl_file.adoc @@ -0,0 +1,409 @@ +:sectnums: +:sectnumlevels: 5 + += UTL_FILE package + +== Purpose + +The `UTL_FILE` package reads and writes text files on the server from PL/iSQL. It also provides procedures to inspect, copy, remove, and rename files. `FOPEN` returns a `sys.ORA_UTL_FILE_FILE_TYPE` handle for subsequent read, write, and close operations. + +== Feature Description + +=== Security prerequisites + +`UTL_FILE` uses the `sys.utl_file_directory` table to restrict access to directories. Register a directory in this table before using file operations. + +[source,sql] +---- +CREATE TABLE sys.utl_file_directory( + dirname name PRIMARY KEY, + dir TEXT +); +---- + +* Unprivileged users have `SELECT` on `sys.utl_file_directory` only; adding or deleting registered directories requires superuser privileges. This corresponds to Oracle's `CREATE DIRECTORY` privilege, which is granted only to `SYS` and `SYSTEM` by default. +* Register a directory before use, then reference it by its `dirname`: + +[source,sql] +---- +-- register the data directory as a directory object named 'data_directory' +INSERT INTO sys.utl_file_directory(dirname, dir) +VALUES ('data_directory', current_setting('data_directory')); +---- + +* The `location` parameter may be either a registered `dirname` or a raw path. Raw paths are canonicalized and must fall under one of the registered directories (prefix match); otherwise the operation fails with `INVALID_PATH`. +* As in Oracle, **a subdirectory of an accessible directory is not automatically accessible**; it must be registered with a complete path of its own. +* File permission mask: files created by `FOPEN` are subject to the `utl_file.umask` parameter (default `0077`). Only superusers can change it, and the value must be 3–4 octal digits: + +[source,sql] +---- +SET utl_file.umask = '0022'; +SHOW utl_file.umask; +---- + +=== Functions and procedures + +[cols="4,2,4",options="header"] +|=== +|Call |Return type |Description +|`FOPEN(location, filename, open_mode [, max_linesize])` |`ORA_UTL_FILE_FILE_TYPE` |Open a file for input or output. `open_mode` is one character: `R` (read), `W` (write, truncate), `A` (append). `max_linesize` defaults to 1024, range 1–32767 +|`FOPEN_NCHAR(location, filename, open_mode [, max_linesize])` |`ORA_UTL_FILE_FILE_TYPE` |Open a file in Unicode mode for input or output; the file is read and written in UTF-8 instead of the database character set. Same parameters as `FOPEN` +|`IS_OPEN(file)` |`BOOLEAN` |Determine whether the file handle refers to a file that has been opened but not yet closed +|`FCLOSE(file)` |— |Close an open file identified by a file handle +|`FCLOSE_ALL` |— |Close all open file handles for the session; an emergency cleanup procedure, e.g. when a PL/iSQL program exits on an exception +|`FFLUSH(file)` |— |Physically write all pending output to the file; useful when the file must be read while it is still open (e.g. debug messages) +|`FGETPOS(file)` |`INTEGER` |Return the current relative offset position within the file, in bytes; `0` means the beginning of the file +|`FSEEK(file [, absolute_offset [, relative_offset]])` |— |Adjust the file pointer forward or backward within the file by the number of bytes specified. `absolute_offset` is a byte position counted from the beginning of the file; `relative_offset` seeks forward (positive) or backward (negative) from the current position; with both omitted IvorySQL resets the position to 0 +|`GET_LINE(file, buffer OUT, [len])` |— |Read text up to, but not including, the line terminator, the end of file, or `len` bytes — whichever comes first — into `buffer`. `len` defaults to `max_linesize`; if both are given the lesser value takes precedence. Returns `NULL` at end of file +|`GET_LINE_NCHAR(file, buffer OUT, [len])` |— |Read text in Unicode from a file opened by `FOPEN_NCHAR` +|`NEW_LINE(file [, lines])` |— |Write one or more operating system-specific line terminators (default 1). Separate from `PUT` because the line terminator is a platform-specific character sequence +|`PUT(file, buffer)` |— |Write the string in `buffer` to the file without appending a line terminator; use `NEW_LINE` or `PUT_LINE` to terminate the line +|`PUTF(file, format [, arg1..arg5])` |— |A `PUT` with formatting, like a limited `printf()`. `%s` in `format` is replaced by `arg1`–`arg5` in order, `\n` by the platform line terminator, `%%` by a literal `%` (IvorySQL extension). If there are more `%s` formatters than arguments, an empty string is substituted +|`PUT_LINE(file, buffer [, autoflush])` |— |Write the line to the file and append the platform-specific line terminator; `autoflush = TRUE` flushes the buffer to disk after the write +|`PUT_LINE_NCHAR(file, buffer)` |— |Write a Unicode line to a file opened by `FOPEN_NCHAR`; appends the line terminator +|`PUT_RAW(file, buffer [, autoflush])` |— |Write a `BYTEA` value (the counterpart of Oracle `RAW`) to the file without appending a line terminator; `autoflush = TRUE` flushes after writing +|`FCOPY(src_location, src_filename, dest_location, dest_file [, start_line [, end_line]])` |— |Copy a contiguous portion of a file to a newly created file. By default the whole file is copied; `start_line` (default 1) and `end_line` (default: end of file) select a portion from the source file. The source is opened in read mode, the destination in write mode +|`FREMOVE(location, filename)` |— |Delete a disk file, assuming sufficient privileges; the operating system verifies file and directory permissions +|`FRENAME(src_location, src_filename, dest_location, dest_filename [, overwrite])` |— |Rename a file to a new name, similar to the UNIX `mv` function. `overwrite` defaults to `FALSE`; if the destination exists and `overwrite` is `FALSE`, `WRITE_ERROR` is raised +|`FGETATTR(location, filename, fexists OUT, file_length OUT, block_size OUT)` |— |Read and return the attributes of a disk file: existence, length in bytes (`NULL` if the file does not exist), and file system block size (`NULL` if the file does not exist) +|=== + +Not yet implemented compared with Oracle: `GET_RAW`, `PUT_NCHAR`, `PUTF_NCHAR`, and the byte (`rb`/`wb`/`ab`) open modes. + +The file handle type corresponds field-by-field to Oracle's private `FILE_TYPE` record; its contents should not be referenced or changed by the user: + +[source,sql] +---- +CREATE TYPE sys.ORA_UTL_FILE_FILE_TYPE AS(id INTEGER, datatype INTEGER, byte_mode BOOLEAN); +---- + +=== Syntax + +`UTL_FILE` subprograms are typically called from PL/iSQL anonymous blocks: + +[source,sql] +---- +DECLARE + f sys.ora_utl_file_file_type; + line TEXT; +BEGIN + f := UTL_FILE.FOPEN('data_directory', 'regress.txt', 'W'); + + UTL_FILE.PUT_LINE(f, 'abc'); + UTL_FILE.PUT_LINE(f, '-----'); + UTL_FILE.FCLOSE(f); + + f := UTL_FILE.FOPEN('data_directory', 'regress.txt', 'R'); + UTL_FILE.GET_LINE(f, line); + WHILE line IS NOT NULL LOOP + RAISE NOTICE '>>%<<', line; + UTL_FILE.GET_LINE(f, line); + END LOOP; + UTL_FILE.FCLOSE(f); +END; +/ +---- + +In Oracle compatibility mode (`ivorysql.compatible_mode = oracle`) the package can be used directly. As in Oracle, the file location and file name are supplied as separate strings so the location can be checked against the registry; together they must represent a legal filename on the system. + +=== Open modes + +Following Oracle's `FOPEN` definition: + +[cols="2,4,4",options="header"] +|=== +|Mode |Description |Notes +|`R` |Read text |The file must exist +|`W` |Write text, truncating |Creates the file if it does not exist, otherwise empties it +|`A` |Append text |Writes are added at the end of the file; a missing file is created, which matches Oracle's note that append mode creates the file in write mode +|=== + +The mode is case-insensitive (`'r'`, `'w'`, `'a'` are accepted); any other value raises `INVALID_MODE`. Oracle additionally supports the byte modes `rb`, `wb`, and `ab`; these are not yet supported by IvorySQL. + +=== Operational notes + +The following rules are inherited from Oracle's *Operational Notes* and *Rules and Limits* for `UTL_FILE`: + +* **Bytes returned by GET_LINE** are the lesser of: the `GET_LINE` `len` parameter, the number of bytes until the next line terminator, and the `max_linesize` specified by `FOPEN`. The line terminator itself is not read into the buffer, so reading blank lines returns empty strings. +* **max_linesize** must be in the range 1–32767; if unspecified, a default value of 1024 is supplied. The `GET_LINE` `len` parameter follows the same range; when `max_linesize` and `len` differ, the lesser value takes precedence. +* **Character sets**: files opened by `FOPEN` are expected to be encoded in the database character set, files opened by `FOPEN_NCHAR` in UTF-8. Reading a file in an unexpected character set gives indeterminate results. +* **Sequential `PUT` output** should not exceed the line limit between flushes; exceeding `max_linesize` raises `VALUE_ERROR` ("buffer is too short"). +* **Open-file limit**: a session can have at most 50 files open simultaneously (same as Oracle). Beyond that, `FOPEN` fails with a "program limit exceeded" error. +* Operating system-specific parameters (e.g. environment variables) cannot be used in the file location or file name parameters. + +== Syntax Examples + +Writing and reading a file line by line: + +[source,sql] +---- +DECLARE + f sys.ora_utl_file_file_type; + line TEXT; + i INTEGER; +BEGIN + f := UTL_FILE.FOPEN('data_directory', 'regress.txt', 'W'); + + UTL_FILE.PUT_LINE(f, 'abc'); + UTL_FILE.PUT_LINE(f, '123'::numeric); + UTL_FILE.NEW_LINE(f, 2); + UTL_FILE.PUT(f, 'a'); + UTL_FILE.PUT(f, 'b'); + UTL_FILE.NEW_LINE(f); + UTL_FILE.PUTF(f, '[1=%s, 2=%s]', 'one', 'two'); + UTL_FILE.NEW_LINE(f); + UTL_FILE.FCLOSE(f); + + f := UTL_FILE.FOPEN('data_directory', 'regress.txt', 'R'); + i := 1; + UTL_FILE.GET_LINE(f, line); + WHILE line IS NOT NULL LOOP + RAISE NOTICE '[%] >>%<<', i, line; + UTL_FILE.GET_LINE(f, line); + i := i + 1; + END LOOP; + UTL_FILE.FCLOSE(f); + + EXCEPTION + WHEN OTHERS THEN + RAISE NOTICE 'exception: %', sqlerrm; + UTL_FILE.FCLOSE_ALL(); +END; +/ +---- + +Output: + +[source,text] +---- +NOTICE: [1] >>abc<< +NOTICE: [2] >>123<< +NOTICE: [3] >><< +NOTICE: [4] >>ab<< +NOTICE: [5] >>[1=one, 2=two]<< +---- + +The classic `PUTF` example from the Oracle documentation writes `Hello, world!\nI come from Zork with greetings for all earthlings.`: + +[source,sql] +---- +DECLARE + my_world VARCHAR2 := 'Zork'; + f sys.ora_utl_file_file_type; +BEGIN + f := UTL_FILE.FOPEN('data_directory', 'zork.txt', 'W'); + UTL_FILE.PUTF(f, 'Hello, world!\nI come from %s with %s.\n', + my_world, + 'greetings for all earthlings'); + UTL_FILE.FCLOSE(f); +END; +/ +---- + +File attributes, copy, remove, and rename: + +[source,sql] +---- +DECLARE + fexists BOOLEAN; + file_length NUMBER; + block_size INTEGER; +BEGIN + UTL_FILE.FCOPY('data_directory', 'regress.txt', 'data_directory', 'regress2.txt'); + UTL_FILE.FGETATTR('data_directory', 'regress2.txt', fexists, file_length, block_size); + RAISE NOTICE 'fexists = %, file_length = %, block_size = %', fexists, file_length, block_size; + + UTL_FILE.FREMOVE('data_directory', 'regress2.txt'); + UTL_FILE.FGETATTR('data_directory', 'regress2.txt', fexists, file_length, block_size); + RAISE NOTICE 'fexists = %', fexists; + + UTL_FILE.FRENAME('data_directory', 'regress.txt', 'data_directory', 'regress2.txt', TRUE); +END; +/ +---- + +Output: + +[source,text] +---- +NOTICE: fexists = t, file_length = 24, block_size = 4096 +NOTICE: fexists = f +---- + +The max_linesize/len precedence example from the Oracle documentation — `GET_LINE`'s `len` request exceeds `FOPEN`'s `max_linesize`, so the number of bytes returned is bounded by the smaller value: + +[source,sql] +---- +DECLARE + v1 TEXT; + f1 sys.ora_utl_file_file_type; +BEGIN + -- MAX_LINESIZE (256) is less than GET_LINE's length request (32767), + -- so the number of bytes returned will be 256 or less if a line terminator is seen. + f1 := UTL_FILE.FOPEN('data_directory', 'u12345.tmp', 'R', 256); + UTL_FILE.GET_LINE(f1, v1, 32767); + UTL_FILE.FCLOSE(f1); + + -- FOPEN's MAX_LINESIZE defaults to 1024, + -- so the number of bytes returned will be 1024 or less if a line terminator is seen. + f1 := UTL_FILE.FOPEN('data_directory', 'u12345.tmp', 'R'); + UTL_FILE.GET_LINE(f1, v1, 32767); + UTL_FILE.FCLOSE(f1); + + -- GET_LINE doesn't specify a number of bytes, so it defaults to + -- FOPEN's MAX_LINESIZE, which in turn defaults to 1024. + f1 := UTL_FILE.FOPEN('data_directory', 'u12345.tmp', 'R'); + UTL_FILE.GET_LINE(f1, v1); + UTL_FILE.FCLOSE(f1); +END; +/ +---- + +`FFLUSH`, `FSEEK`, and `FGETPOS` work together for write-then-reread scenarios: writes become visible to other handles only after `FFLUSH`, and `FSEEK` can jump to a saved offset: + +[source,sql] +---- +DECLARE + f sys.ora_utl_file_file_type; + f1 sys.ora_utl_file_file_type; + line TEXT; + line2_pos INTEGER; +BEGIN + f := UTL_FILE.FOPEN('data_directory', 'regressflush.txt', 'W'); + f1 := UTL_FILE.FOPEN('data_directory', 'regressflush.txt', 'R'); + + FOR i IN 1..5 LOOP + UTL_FILE.PUT_LINE(f, 'line ' || i::text); + END LOOP; + + UTL_FILE.FFLUSH(f); -- make buffered writes visible + + UTL_FILE.FSEEK(f1); -- reset read position to 0 + UTL_FILE.GET_LINE(f1, line); + line2_pos := UTL_FILE.FGETPOS(f1); -- remember the offset of line 2 + + WHILE line IS NOT NULL LOOP + RAISE NOTICE '>>%<<', line; + UTL_FILE.GET_LINE(f1, line); + END LOOP; + + UTL_FILE.FSEEK(f1, line2_pos, NULL); -- jump back to line 2 (absolute) + UTL_FILE.GET_LINE(f1, line); + RAISE NOTICE '>>%<<', line; + + UTL_FILE.FSEEK(f1, NULL, -7); -- move back one record (relative) + UTL_FILE.GET_LINE(f1, line); + RAISE NOTICE '>>%<<', line; + + UTL_FILE.FCLOSE_ALL(); +END; +/ +---- + +`FSEEK` makes it possible to read previous lines without first closing and reopening the file — you must know the number of bytes by which to navigate. If the beginning of the file is reached before the requested number of bytes, the file pointer is placed at the beginning of the file; if the end of the file is reached first, `INVALID_OFFSET` is raised. + +== Exceptions + +`UTL_FILE` raises Oracle-style exceptions, which can be caught with `WHEN OTHERS` and inspected via `SQLERRM`. The exception set follows Oracle's *UTL_FILE Exceptions* table: + +[cols="3,5",options="header"] +|=== +|Exception |Description +|`INVALID_PATH` |File location is invalid +|`INVALID_MODE` |The `open_mode` parameter in `FOPEN` is invalid +|`INVALID_FILEHANDLE` |File handle is invalid +|`INVALID_OPERATION` |File could not be opened or operated on as requested, e.g. reading from a handle opened in `W`/`A` mode +|`READ_ERROR` |Destination buffer too small, or an operating system error occurred during the read operation +|`WRITE_ERROR` |An operating system error occurred during the write operation; also raised when `FRENAME` finds the destination file exists and `overwrite` is `FALSE` +|`INTERNAL_ERROR` |Unspecified PL/iSQL error +|`CHARSETMISMATCH` |A file is opened using `FOPEN_NCHAR`, but later I/O operations use nonchar functions such as `PUTF` or `GET_LINE` +|`FILE_OPEN` |The requested operation failed because the file is open +|`INVALID_MAXLINESIZE` |The `max_linesize` value for `FOPEN()` is invalid; it should be within the range 1 to 32767 +|`INVALID_FILENAME` |The `filename` parameter is invalid +|`ACCESS_DENIED` |Permission to access the file location is denied +|`INVALID_OFFSET` |`absolute_offset < 0`, or an offset causes a seek past the end of the file +|`DELETE_FAILED` |The requested file delete operation failed +|`RENAME_FAILED` |The requested file rename operation failed +|`NO_DATA_FOUND` |Predefined exception; see the note on end-of-file behavior below +|`VALUE_ERROR` |Predefined exception; raised when written data exceeds `max_linesize` +|=== + +Procedures in `UTL_FILE` can also raise other predefined PL/iSQL exceptions. + +End-of-file behavior: when `GET_LINE` reads past the end of the file, Oracle raises `NO_DATA_FOUND`. IvorySQL instead logs the condition at `LOG` level (`no data found`) and returns `NULL`, so the `WHILE line IS NOT NULL` loop pattern works naturally: + +[source,sql] +---- +DECLARE + f sys.ora_utl_file_file_type; + line TEXT; +BEGIN + f := UTL_FILE.FOPEN('data_directory', 'regress.txt', 'R'); + UTL_FILE.GET_LINE(f, line); + WHILE line IS NOT NULL LOOP + RAISE NOTICE '>>%<<', line; + UTL_FILE.GET_LINE(f, line); + END LOOP; + UTL_FILE.FCLOSE(f); +END; +/ +---- + +Error handling example: + +[source,sql] +---- +DECLARE + f sys.ora_utl_file_file_type; +BEGIN + -- 'wrong_directory' is not registered, raises INVALID_PATH + f := UTL_FILE.FOPEN('wrong_directory', 'regress.txt', 'A', 1024); +END; +/ +---- + +[source,text] +---- +ERROR: INVALID_PATH +DETAIL: File location is invalid. +HINT: locality is not found in sys.utl_file_directory table +---- + +== Differences from Oracle + +The API is aligned with Oracle, with the following known differences: + +[cols="2,4",options="header"] +|=== +|Area |IvorySQL behavior +|Directory objects |Uses the `sys.utl_file_directory` table instead of Oracle's `CREATE DIRECTORY`/`ALL_DIRECTORIES`. A raw path under a registered directory is also accepted +|End of file |`GET_LINE` returns `NULL` at EOF; Oracle raises `NO_DATA_FOUND` +|Byte modes |`rb`/`wb`/`ab` open modes are not supported; `INVALID_MODE` is raised. The `byte_mode` field exists in the handle type for future use +|Missing subprograms |`GET_RAW`, `PUT_NCHAR`, `PUTF_NCHAR` are not yet implemented +|`FSEEK` with both offsets `NULL` |Resets the file position to 0; Oracle raises `INVALID_OFFSET` +|`PUTF` format strings |`%%` is supported as a literal `%` (an IvorySQL extension); unmatched `%s` formatters are replaced by an empty string, same as Oracle +|`FCLOSE_ALL` and `IS_OPEN` |After `FCLOSE_ALL`, `IS_OPEN` returns `FALSE` in IvorySQL; Oracle keeps reporting `TRUE` for the untouched handle +|Exception set |Exceptions not specifically detected by the implementation (`ACCESS_DENIED`, `DELETE_FAILED`, `RENAME_FAILED`, `FILE_OPEN`, `CHARSETMISMATCH`, `INVALID_FILENAME`, `INTERNAL_ERROR`) surface as the closest Oracle exception, typically `INVALID_PATH`/`INVALID_OPERATION`/`READ_ERROR`/`WRITE_ERROR` with the operating system error text as `DETAIL` +|File ownership |On UNIX, files created by `FOPEN` are owned by the user running the database server, as in Oracle; their permissions are masked by `utl_file.umask` +|=== + +== Transaction and session lifecycle + +File handles survive `COMMIT` but are automatically closed when the transaction rolls back or the session terminates, so buffered data is not silently lost: + +[source,sql] +---- +BEGIN + f := UTL_FILE.FOPEN('data_directory','regress.txt','A',1024); + RAISE NOTICE 'is_open = %', UTL_FILE.IS_OPEN(f); -- t + COMMIT; + RAISE NOTICE 'is_open = %', UTL_FILE.IS_OPEN(f); -- t + ROLLBACK; + RAISE NOTICE 'is_open = %', UTL_FILE.IS_OPEN(f); -- f +END; +/ +---- + +== Implementation notes + +For the security model, handle management, and internal design, see xref:master/compatibility_features_design/utl_file_impl.adoc[UTL_FILE implementation design].