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/compatibility_features_design/utl_match_impl.adoc b/CN/modules/ROOT/pages/master/compatibility_features_design/utl_match_impl.adoc new file mode 100644 index 00000000..791d4568 --- /dev/null +++ b/CN/modules/ROOT/pages/master/compatibility_features_design/utl_match_impl.adoc @@ -0,0 +1,130 @@ +:sectnums: +:sectnumlevels: 5 + += UTL_MATCH 包实现说明 + +== 目的 + +IvorySQL 实现 Oracle `UTL_MATCH` 包的四个函数:`EDIT_DISTANCE`、`EDIT_DISTANCE_SIMILARITY`、`JARO_WINKLER` 和 `JARO_WINKLER_SIMILARITY`,包括 NULL 语义、字节级比较、换位取整及前缀加权条件等行为均与 Oracle 保持一致。用户示例见 xref:master/oracle_compatibility/compat_utl_match.adoc[UTL_MATCH 包]。 + +== 实现说明 + +=== 代码组织与调用关系 + +[cols="3,3",options="header"] +|=== +|源码路径 |职责 +|`contrib/ivorysql_ora/src/builtin_packages/utl_match/utl_match--1.0.sql` |注册 C 入口 `sys.ora_utl_match_*`,并定义 `UTL_MATCH` 包规格与包体 +|`contrib/ivorysql_ora/src/builtin_packages/utl_match/utl_match.c` |四个函数的 C 实现(编辑距离、Jaro、Jaro-Winkler) +|`contrib/ivorysql_ora/sql/utl_match.sql` |回归用例 +|`contrib/ivorysql_ora/expected/utl_match.out` |期望的结果与注释 +|`Makefile`、`meson.build`、`ivorysql_ora_merge_sqls` |将新目录纳入构建与 SQL 合并流程 +|=== + +[source,text] +---- +UTL_MATCH.EDIT_DISTANCE(s1, s2) + → sys.ora_utl_match_edit_distance(s1 text, s2 text) RETURNS integer + → edit_distance() +UTL_MATCH.EDIT_DISTANCE_SIMILARITY(s1, s2) + → sys.ora_utl_match_edit_distance_similarity(s1 text, s2 text) RETURNS integer + → edit_distance_similarity() +UTL_MATCH.JARO_WINKLER(s1, s2) + → sys.ora_utl_match_jaro_winkler(s1 text, s2 text) RETURNS float8 + → jaro_winkler() → jaro() +UTL_MATCH.JARO_WINKLER_SIMILARITY(s1, s2) + → sys.ora_utl_match_jaro_winkler_similarity(s1 text, s2 text) RETURNS integer + → jaro_winkler() → jaro() +---- + +包体中的 `UTL_MATCH.*` 仅作参数转发,四个 C 入口声明为 `IMMUTABLE`,且不声明为 `STRICT`,因为 Oracle 对 NULL 输入不传播 NULL,而是按函数返回固定哨兵值(见下文)。 + +=== 编辑距离(Levenshtein) + +`edit_distance()` 计算将 s1 变换为 s2 所需的最少单字符编辑次数(插入、删除、替换各计 1): + +* 使用两行动态规划矩阵逐行填表,转移方程为:字符相同取对角线值,字符不同取 `min(上+1, 左+1, 左上+1)`。 +* 利用编辑距离的对称性,先将较短的字符串交换为列维度,内存占用为 `O(min(n1, n2))`。 +* 内层循环每累计 1024 次迭代调用一次 `CHECK_FOR_INTERRUPTS()`,保证大输入(O(n1×n2) 的比较)仍可被取消或遵守 `statement_timeout`。 +* 比较以字节为单位,与 Oracle 一致;空串与任意串的距离为另一串的字节长度。 + +`edit_distance_similarity()` 的计算公式为: + +[source,text] +---- +similarity = ROUND((1 - ED / MAX(LEN1, LEN2)) * 100) -- 结果下限为 0 +---- + +其中 `ED` 为编辑距离,`LEN1`、`LEN2` 为字节长度,两个空串视为 100% 相似。四舍五入采用 half-up(`floor(v + 0.5)`),与 Oracle 一致,例如 `(1 - 3/8) * 100 = 62.5` 进位为 `63`。 + +=== Jaro-Winkler + +Jaro 相似度基于匹配字符数 `m` 和换位数 `t`: + +[source,text] +---- + | 0 若 m = 0 +sim_jaro = | + | (m/|s1| + m/|s2| + (m - t)/m) / 3 其他情况 +---- + +* 匹配窗口为 `floor(max(len1, len2) / 2) - 1`:s1 的第 i 个字节只与 s2 中距离不超过窗口的同名字节配对。 +* `t` 为换位数(失配的匹配字符对数的一半)。与教科书的小数换位不同,Oracle 将半换位**截断取整**(整数除法 `t/2`),例如 `JARO_WINKLER_SIMILARITY('ABCDEF', 'BCADEF')` 返回 `94` 而非教科书的 `92`。 +* 以 MARTHA / MARHTA 为例:窗口为 `6/2 - 1 = 2`,六个字符全部配上对,`m = 6`;失配字符为 H、T,一次交换即可复原,`t = 1`;`sim_jaro = (6/6 + 6/6 + 5/6) / 3 = 0.9444`。 + +Winkler 前缀加权在 Jaro 相似度基础上提升共同前缀的权重: + +[source,text] +---- +sim_jw = sim_jaro + l * 0.1 * (1 - sim_jaro) +---- + +* `l` 为共同前缀的字节数,**上限为 4**。 +* 与经典算法不同,Oracle **无条件**应用前缀提升(没有 0.7 的提升阈值),例如 `JARO_WINKLER('ABCCCCCCCCCC', 'ABDDDDDDDDDD')` 从 0.4444 提升到 0.5556。 + +`JARO_WINKLER_SIMILARITY` 返回 `ROUND(jaro_winkler * 100)`,同样采用 half-up 取整。 + +=== NULL、空串与长度边界 + +C 层即实现 Oracle 的哨兵值语义,不依赖 `STRICT`: + +[cols="4,3",options="header"] +|=== +|函数 |NULL 输入的返回值 +|`ora_utl_match_edit_distance` |`-1` +|`ora_utl_match_edit_distance_similarity` |单侧 NULL 返回 `0`,双侧 NULL 返回 `100` +|`ora_utl_match_jaro_winkler` |`0` +|`ora_utl_match_jaro_winkler_similarity` |`0` +|=== + +实现不设 PostgreSQL `fuzzystrmatch` 中 `levenshtein` 的 `MAX_LEVENSHTEIN_STRLEN`(255 字节)上限,输入长度上限即 `VARCHAR2` 的 32767 字节,与 Oracle 一致;回归用例包含长度 3000 的输入。 + +== 实现示例 + +=== 编辑距离与相似度 + +[source,sql] +---- +SELECT UTL_MATCH.EDIT_DISTANCE('shackleford', 'shackelford') FROM dual; +-- 2 +SELECT UTL_MATCH.EDIT_DISTANCE_SIMILARITY('shackleford', 'shackelford') FROM dual; +-- 82 +---- + +包函数把参数传给对应的 `sys.ora_utl_match_*` 入口。编辑距离为 2,较长字符串为 11 字节,相似度按公式计算并取整。 + +=== NULL 输入 + +[source,sql] +---- +SELECT UTL_MATCH.EDIT_DISTANCE(NULL, 'abc') FROM dual; -- -1 +SELECT UTL_MATCH.EDIT_DISTANCE_SIMILARITY(NULL, NULL) FROM dual; -- 100 +---- + +C 入口没有声明 `STRICT`,因此能够分别处理 NULL 参数,而不是由 PostgreSQL 直接返回 NULL。 + +== 回归验证 + +`utl_match` 回归组覆盖常见示例值(shackleford/shackelford、kitten/sitting、MARTHA/MARHTA、DWAYNE/DUANE、DIXON/DICKSONX、JELLYFISH/SMELLYFISH)、大小写敏感、空格、多字节字符的字节级行为、空串、NULL 哨兵值、半换位截断、无条件前缀提升及其 4 字节上限、匹配窗口边界、half-up 取整边界,以及直接调用 C 入口和 PL/iSQL 包接口的用例。 + +在已配置并编译的 IvorySQL 源码目录中,可运行 `make -C contrib/ivorysql_ora oracle-installcheck ORA_REGRESS=utl_match` 验证该测试组;目标实例需已安装相应版本的 `ivorysql_ora` 扩展。 diff --git a/CN/modules/ROOT/pages/master/oracle_compatibility/builtin_types_functions.adoc b/CN/modules/ROOT/pages/master/oracle_compatibility/builtin_types_functions.adoc index 9c3d170d..70ee8675 100644 --- a/CN/modules/ROOT/pages/master/oracle_compatibility/builtin_types_functions.adoc +++ b/CN/modules/ROOT/pages/master/oracle_compatibility/builtin_types_functions.adoc @@ -1150,4 +1150,35 @@ ivorysql=# select sys_context('USERENV','DB_NAME'); ivorysql (1 row) -``` \ No newline at end of file +``` +=== `UTL_MATCH` 包 + +功能:提供 Oracle 兼容的字符串匹配与相似度计算,包含 `EDIT_DISTANCE`、`EDIT_DISTANCE_SIMILARITY`、`JARO_WINKLER`、`JARO_WINKLER_SIMILARITY` 四个函数,用于拼写检查、错别字纠正以及姓名、地址等短文本的模糊匹配与去重。测试用例如下: + +``` +SELECT UTL_MATCH.EDIT_DISTANCE('shackleford','shackelford'); + edit_distance +--------------- + 2 +(1 row) + +SELECT UTL_MATCH.EDIT_DISTANCE_SIMILARITY('shackleford','shackelford'); + edit_distance_similarity +-------------------------- + 82 +(1 row) + +SELECT ROUND(UTL_MATCH.JARO_WINKLER('shackleford','shackelford'),4); + round +--------- + 0.9818 +(1 row) + +SELECT UTL_MATCH.JARO_WINKLER_SIMILARITY('shackleford','shackelford'); + jaro_winkler_similarity +------------------------- + 98 +(1 row) +``` + +详见 xref:master/oracle_compatibility/compat_utl_match.adoc[UTL_MATCH 包]。 \ No newline at end of file diff --git a/CN/modules/ROOT/pages/master/oracle_compatibility/compat_ascii_function.adoc b/CN/modules/ROOT/pages/master/oracle_compatibility/compat_ascii_function.adoc new file mode 100644 index 00000000..f3e08134 --- /dev/null +++ b/CN/modules/ROOT/pages/master/oracle_compatibility/compat_ascii_function.adoc @@ -0,0 +1,32 @@ +:sectnums: +:sectnumlevels: 5 + += ASCII 函数 + +== 功能说明 + +`ASCII` 返回输入值转换为字符串后第一个字节的无符号整数值,返回类型为 `integer`。对于以 ASCII 字符开头的字符串,该值是首字符的 ASCII 码;后续字符不影响结果。 + +== 语法 + +[source,sql] +---- +ASCII(value) +---- + +支持 Oracle 兼容的 `VARCHAR2`、`NUMBER`、`BINARY_FLOAT`、`BINARY_DOUBLE`、`DATE`、`TIMESTAMP` 和 `TIMESTAMP WITH TIME ZONE` 输入。数值先转换为字符串;日期和时间类型分别使用会话的 `nls_date_format`、`nls_timestamp_format` 和 `nls_timestamp_tz_format` 格式化,因此结果可能随格式设置改变。输入为 `NULL` 或转换后的字符串为空时返回 `NULL`。 + +== 示例 + +[source,sql] +---- +SELECT ascii('abc') FROM dual; -- 97,即小写字母 a +SELECT ascii('xyz') FROM dual; -- 120,即小写字母 x +SELECT ascii(321) FROM dual; -- 51,即数字字符 3 +SELECT ascii('') IS NULL FROM dual; -- true +SELECT ascii(to_char('2026-01-01'::date, 'DD-MON-YYYY HH24:MI:SS')) FROM dual; -- 48 +---- + +== 注意事项 + +对于上述 Oracle 兼容类型的实现,非 ASCII 字符返回其在数据库编码中第一个字节的值,而不是 Unicode 码点或完整多字节字符的数值。例如,在 UTF8 数据库中,`中` 的首字节为十六进制 `E4`,对应十进制 228。结果取决于编码及调用时选择的函数重载;不要将其用于取得非 ASCII 字符的 Unicode 码点。 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/CN/modules/ROOT/pages/master/oracle_compatibility/compat_utl_match.adoc b/CN/modules/ROOT/pages/master/oracle_compatibility/compat_utl_match.adoc new file mode 100644 index 00000000..999ced5e --- /dev/null +++ b/CN/modules/ROOT/pages/master/oracle_compatibility/compat_utl_match.adoc @@ -0,0 +1,115 @@ +:sectnums: +:sectnumlevels: 5 + += UTL_MATCH 包 + +== 目的 + +`UTL_MATCH` 包用于计算两个字符串的编辑距离和相似度,包含 `EDIT_DISTANCE`、`EDIT_DISTANCE_SIMILARITY`、`JARO_WINKLER` 和 `JARO_WINKLER_SIMILARITY` 四个函数。 + +== 功能说明 + +=== 函数一览 + +[cols="4,2,4",options="header"] +|=== +|函数 |返回类型 |说明 +|`EDIT_DISTANCE(s1, s2)` |`INTEGER` |将 s1 转换为 s2 所需的最少编辑次数(插入、删除、替换一个字符各记 1 次) +|`EDIT_DISTANCE_SIMILARITY(s1, s2)` |`INTEGER` |基于编辑距离的相似度分数,范围 0–100,0 表示完全不同,100 表示完全相同 +|`JARO_WINKLER(s1, s2)` |`BINARY_DOUBLE` |Jaro-Winkler 相似度,范围 0–1 +|`JARO_WINKLER_SIMILARITY(s1, s2)` |`INTEGER` |`JARO_WINKLER` 结果乘以 100 并四舍五入,范围 0–100 +|=== + +=== 调用方式 + +[source,sql] +---- +SELECT UTL_MATCH.EDIT_DISTANCE(s1, s2) FROM dual; +SELECT UTL_MATCH.EDIT_DISTANCE_SIMILARITY(s1, s2) FROM dual; +SELECT UTL_MATCH.JARO_WINKLER(s1, s2) FROM dual; +SELECT UTL_MATCH.JARO_WINKLER_SIMILARITY(s1, s2) FROM dual; +---- + +`s1`、`s2` 为待比较的字符串(`VARCHAR2`)。在 Oracle 兼容模式(`ivorysql.compatible_mode = oracle`)下可直接使用。 + +== 语法示例 + +`EDIT_DISTANCE_SIMILARITY` 按编辑距离给出 0–100 的整数分数: + +[source,sql] +---- +-- 完全不同的字符串,返回 0 +SELECT UTL_MATCH.EDIT_DISTANCE_SIMILARITY('123456', '456789') AS similarity FROM dual; + +-- 仅一个字符不同,返回 83 +SELECT UTL_MATCH.EDIT_DISTANCE_SIMILARITY('123456', '123956') AS similarity FROM dual; + +-- 完全相同的字符串,返回 100 +SELECT UTL_MATCH.EDIT_DISTANCE_SIMILARITY('123456', '123456') AS similarity FROM dual; +---- + +`JARO_WINKLER_SIMILARITY` 计算 Jaro-Winkler 相似度: + +[source,sql] +---- +-- 完全不同的字符串,返回 0 +SELECT UTL_MATCH.JARO_WINKLER_SIMILARITY('123456', '456789') AS similarity FROM dual; + +-- 仅一个字符不同,返回 92 +SELECT UTL_MATCH.JARO_WINKLER_SIMILARITY('123456', '123956') AS similarity FROM dual; + +-- 完全相同的字符串,返回 100 +SELECT UTL_MATCH.JARO_WINKLER_SIMILARITY('123456', '123456') AS similarity FROM dual; +---- + +以下示例比较几组字符串: + +[cols="5,2",options="header"] +|=== +|调用 |结果 +|`EDIT_DISTANCE('shackleford', 'shackelford')` |`2` +|`EDIT_DISTANCE_SIMILARITY('shackleford', 'shackelford')` |`82` +|`JARO_WINKLER('shackleford', 'shackelford')` |`0.9818` +|`JARO_WINKLER_SIMILARITY('shackleford', 'shackelford')` |`98` +|`EDIT_DISTANCE('kitten', 'sitting')` |`3` +|`EDIT_DISTANCE_SIMILARITY('kitten', 'sitting')` |`57` +|`JARO_WINKLER_SIMILARITY('MARTHA', 'MARHTA')` |`96` +|`JARO_WINKLER_SIMILARITY('DWAYNE', 'DUANE')` |`84` +|`JARO_WINKLER_SIMILARITY('DIXON', 'DICKSONX')` |`81` +|`JARO_WINKLER_SIMILARITY('JELLYFISH', 'SMELLYFISH')` |`90` +|=== + +[source,sql] +---- +SELECT UTL_MATCH.EDIT_DISTANCE('shackleford', 'shackelford') AS edit_distance, + UTL_MATCH.EDIT_DISTANCE_SIMILARITY('shackleford', 'shackelford') AS similarity, + ROUND(UTL_MATCH.JARO_WINKLER('shackleford', 'shackelford'), 4) AS jaro_winkler, + UTL_MATCH.JARO_WINKLER_SIMILARITY('shackleford', 'shackelford') AS jw_similarity + FROM dual; +---- + +== 匹配规则 + +* 大小写敏感:`EDIT_DISTANCE('abc', 'ABC')` 返回 `3`,与 Oracle 一致。 +* 空格作为普通字符参与计算:`EDIT_DISTANCE('a b', 'ab')` 返回 `1`。 +* 按字节比较,而非按字符比较(与 Oracle 一致)。例如 UTF-8 编码下 `EDIT_DISTANCE('中文测试', '中文测A')` 返回 `3`(最后一个多字节字符与 `A` 的 3 个字节完全不同:1 次替换加 2 次删除),`EDIT_DISTANCE_SIMILARITY('中文测试', '中文测A')` 返回 `75`(分母取字节长度 12)。 +* 输入长度上限为 32767 字节(`VARCHAR2` 上限),与 Oracle 相同。IvorySQL 的实现不经过 PostgreSQL `fuzzystrmatch` 扩展,因此不受其 `levenshtein` 函数 255 字节长度限制的约束。 + +== NULL 与空字符串 + +`UTL_MATCH` 的 NULL 处理按函数分别处理 NULL: + +[cols="4,3",options="header"] +|=== +|函数 |任一参数为 NULL 时的返回值 +|`EDIT_DISTANCE(s1, s2)` |`-1` +|`EDIT_DISTANCE_SIMILARITY(s1, s2)` |一个为 NULL 返回 `0`;两个都为 NULL 返回 `100` +|`JARO_WINKLER(s1, s2)` |`0` +|`JARO_WINKLER_SIMILARITY(s1, s2)` |`0` +|=== + +Oracle 中空字符串即 `NULL`。IvorySQL 默认开启空字符串转 `NULL`(`ivorysql.enable_emptystring_to_NULL = on`),此时 `''` 的行为与 `NULL` 相同;关闭该参数后可以观察空字符串本身的算法行为,例如 `EDIT_DISTANCE('', '')` 返回 `0`,`EDIT_DISTANCE_SIMILARITY('', '')` 返回 `100`。 + +== 实现说明 + +算法细节与内部实现见 xref:master/compatibility_features_design/utl_match_impl.adoc[UTL_MATCH 实现设计]。 diff --git a/CN/modules/ROOT/pages/master/oracle_compatibility/compat_utl_url.adoc b/CN/modules/ROOT/pages/master/oracle_compatibility/compat_utl_url.adoc new file mode 100644 index 00000000..8c3e14ed --- /dev/null +++ b/CN/modules/ROOT/pages/master/oracle_compatibility/compat_utl_url.adoc @@ -0,0 +1,54 @@ +:sectnums: +:sectnumlevels: 5 + += UTL_URL 包 + +== 目的 + +`UTL_URL` 包用于对 URL 进行百分号编码和解码。 + +== 功能说明 + +=== ESCAPE + +[source,sql] +---- +UTL_URL.ESCAPE(url IN VARCHAR2, + escape_reserved_chars IN BOOLEAN DEFAULT FALSE, + url_charset IN VARCHAR2 DEFAULT NULL) RETURN VARCHAR2 +---- + +`ESCAPE` 将 URL 中需要转义的字节转换为 `%XX` 格式。字母、数字及 `- _ . ! ~ * ' ( )` 始终保持原样。保留字符 `; / ? : @ & = + $ ,` 仅在 `escape_reserved_chars` 为 `TRUE` 时转义;`FALSE` 或 `NULL` 时保留。空格、`#`、`%`、其他非法 ASCII 字符和非 ASCII 字节始终转义,已有的 `%XX` 也会再次转义。 + +`url_charset` 指定转义前转换使用的字符集,可使用 PostgreSQL 编码名或支持的字符集别名。省略或传入 `NULL` 均使用数据库编码。`url` 为 `NULL` 时返回 `NULL`。 + +[source,sql] +---- +SELECT utl_url.escape('a b/c?d=e&f'); -- a%20b/c?d=e&f +SELECT utl_url.escape('a b/c?d=e&f', TRUE); -- a%20b%2Fc%3Fd%3De%26f +SELECT utl_url.escape('中文', FALSE, 'UTF8'); -- %E4%B8%AD%E6%96%87 +SELECT utl_url.escape('a%20b'); -- a%2520b +---- + +=== UNESCAPE + +[source,sql] +---- +UTL_URL.UNESCAPE(url IN VARCHAR2, + url_charset IN VARCHAR2 DEFAULT NULL) RETURN VARCHAR2 +---- + +`UNESCAPE` 将 `%XX` 序列解码为字节,再按 `url_charset` 指定的编码转换为数据库编码;连续的转义字节可以组成多字节字符。省略字符集或传入 `NULL` 均使用数据库编码。未转义的文字保持原样,`+` 不会转换为空格。函数只解码一层;`url` 为 `NULL` 时返回 `NULL`。 + +[source,sql] +---- +SELECT utl_url.unescape('a%20b%2Fc'); -- a b/c +SELECT utl_url.unescape('%E4%B8%AD%E6%96%87', 'UTF8'); -- 中文 +SELECT utl_url.unescape('a%2520b'); -- a%20b +---- + +百分号后缺少两个十六进制数字、包含 `%00`、字符集不受支持或字节序列无法按指定编码转换时会报错。编码和解码时应使用相同的字符集。 + +== Oracle 兼容性 + +与 Oracle 省略字符集时使用 `utl_http.body_charset` 的行为不同,IvorySQL 在省略字符集或显式传入 `NULL` 时均使用数据库编码。非法百分号序列会报错,但不保证使用 Oracle 的 `UTL_URL.BAD_URL` 异常;`%00` 也会被拒绝,因为数据库文本不能包含 NUL 字节。 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/compatibility_features_design/utl_match_impl.adoc b/EN/modules/ROOT/pages/master/compatibility_features_design/utl_match_impl.adoc new file mode 100644 index 00000000..e65bca78 --- /dev/null +++ b/EN/modules/ROOT/pages/master/compatibility_features_design/utl_match_impl.adoc @@ -0,0 +1,128 @@ +:sectnums: +:sectnumlevels: 5 + += UTL_MATCH package implementation + +== Purpose + +IvorySQL implements the four functions of Oracle's `UTL_MATCH` package: `EDIT_DISTANCE`, `EDIT_DISTANCE_SIMILARITY`, `JARO_WINKLER`, and `JARO_WINKLER_SIMILARITY`. Behaviors including NULL semantics, byte-based comparison, transposition truncation, and prefix-boost conditions match Oracle. For user examples, see xref:master/oracle_compatibility/compat_utl_match.adoc[UTL_MATCH package]. + +== Implementation + +=== Code organization and call path + +[cols="3,3",options="header"] +|=== +|Source path |Responsibility +|`contrib/ivorysql_ora/src/builtin_packages/utl_match/utl_match--1.0.sql` |Registers the C entry points `sys.ora_utl_match_*` and defines the `UTL_MATCH` package specification and body +|`contrib/ivorysql_ora/src/builtin_packages/utl_match/utl_match.c` |C implementation of the four functions (edit distance, Jaro, Jaro-Winkler) +|`contrib/ivorysql_ora/sql/utl_match.sql` |Regression cases +|`contrib/ivorysql_ora/expected/utl_match.out` |Expected results and comments +|`Makefile`, `meson.build`, `ivorysql_ora_merge_sqls` |Build integration and SQL merge for the new directory +|=== + +[source,text] +---- +UTL_MATCH.EDIT_DISTANCE(s1, s2) + → sys.ora_utl_match_edit_distance(s1 text, s2 text) RETURNS integer + → edit_distance() +UTL_MATCH.EDIT_DISTANCE_SIMILARITY(s1, s2) + → sys.ora_utl_match_edit_distance_similarity(s1 text, s2 text) RETURNS integer + → edit_distance_similarity() +UTL_MATCH.JARO_WINKLER(s1, s2) + → sys.ora_utl_match_jaro_winkler(s1 text, s2 text) RETURNS float8 + → jaro_winkler() → jaro() +UTL_MATCH.JARO_WINKLER_SIMILARITY(s1, s2) + → sys.ora_utl_match_jaro_winkler_similarity(s1 text, s2 text) RETURNS integer + → jaro_winkler() → jaro() +---- + +The `UTL_MATCH.*` functions in the package body only forward arguments. The four C entry points are declared `IMMUTABLE` and are not declared `STRICT`, because Oracle does not propagate NULL but returns a fixed sentinel value per function (see below). + +=== Edit distance (Levenshtein) + +`edit_distance()` computes the minimum number of single-character edits (each insertion, deletion, or substitution counts as 1) needed to transform s1 into s2: + +* It fills a two-row dynamic-programming matrix row by row. The transition is: take the diagonal value when the characters match, otherwise `min(above + 1, left + 1, diagonal + 1)`. +* Exploiting the symmetry of the Levenshtein distance, the shorter string is swapped into the column dimension first, keeping memory at `O(min(n1, n2))`. +* `CHECK_FOR_INTERRUPTS()` is called every 1024 inner-loop iterations, so even large quadratic comparisons remain cancellable and honor `statement_timeout`. +* Comparison is byte-based, consistent with Oracle; the distance between an empty string and any string is the other string's length in bytes. + +`edit_distance_similarity()` is computed as: + +[source,text] +---- +similarity = ROUND((1 - ED / MAX(LEN1, LEN2)) * 100) -- floored at 0 +---- + +where `ED` is the edit distance and `LEN1`, `LEN2` are the lengths in bytes. Two empty strings are considered 100% similar. Rounding is half-up (`floor(v + 0.5)`), consistent with Oracle: `(1 - 3/8) * 100 = 62.5` rounds to `63`. + +=== Jaro-Winkler + +The Jaro similarity is based on the number of matching characters `m` and the number of transpositions `t`: + +[source,text] +---- + | 0 if m = 0 +sim_jaro = | + | (m/|s1| + m/|s2| + (m - t)/m) / 3 otherwise +---- + +* The match window is `floor(max(len1, len2) / 2) - 1`: byte i of s1 can only pair with an identical, not-yet-used byte of s2 within the window. +* `t` is the number of transpositions (half the number of out-of-order matched pairs). Unlike the textbook fractional value, Oracle **truncates** half-transpositions (integer division `t/2`), so `JARO_WINKLER_SIMILARITY('ABCDEF', 'BCADEF')` returns `94` rather than the textbook `92`. +* Example with MARTHA / MARHTA: the window is `6/2 - 1 = 2`; all six characters pair up, so `m = 6`; the displaced characters are H and T, and one swap restores the order, so `t = 1`; `sim_jaro = (6/6 + 6/6 + 5/6) / 3 = 0.9444`. + +The Winkler prefix boost amplifies the Jaro similarity for strings that share a common prefix: + +[source,text] +---- +sim_jw = sim_jaro + l * 0.1 * (1 - sim_jaro) +---- + +* `l` is the common-prefix length in bytes, **capped at 4**. +* Unlike the classic algorithm, Oracle applies the boost **unconditionally** (there is no 0.7 boost threshold): `JARO_WINKLER('ABCCCCCCCCCC', 'ABDDDDDDDDDD')` is boosted from 0.4444 to 0.5556. + +`JARO_WINKLER_SIMILARITY` returns `ROUND(jaro_winkler * 100)`, also rounded half-up. + +=== NULL, empty strings, and length boundaries + +The sentinel-value semantics of Oracle are implemented at the C level and do not rely on `STRICT`: + +[cols="4,3",options="header"] +|=== +|Function |Return value for NULL input +|`ora_utl_match_edit_distance` |`-1` +|`ora_utl_match_edit_distance_similarity` |`0` if exactly one input is NULL, `100` if both are +|`ora_utl_match_jaro_winkler` |`0` +|`ora_utl_match_jaro_winkler_similarity` |`0` +|=== + +There is no equivalent of `fuzzystrmatch`'s `MAX_LEVENSHTEIN_STRLEN` (255 bytes) limit from PostgreSQL. The input length limit is the `VARCHAR2` maximum of 32767 bytes, consistent with Oracle; the regression cases include an input of length 3000. + +== Implementation Examples + +=== Edit distance and similarity + +[source,sql] +---- +SELECT UTL_MATCH.EDIT_DISTANCE('shackleford', 'shackelford') FROM dual; -- 2 +SELECT UTL_MATCH.EDIT_DISTANCE_SIMILARITY('shackleford', 'shackelford') FROM dual; -- 82 +---- + +The package forwards the arguments to the corresponding `sys.ora_utl_match_*` entry point. The distance is 2, and the longer string is 11 bytes; the similarity is calculated from these values and rounded. + +=== NULL input + +[source,sql] +---- +SELECT UTL_MATCH.EDIT_DISTANCE(NULL, 'abc') FROM dual; -- -1 +SELECT UTL_MATCH.EDIT_DISTANCE_SIMILARITY(NULL, NULL) FROM dual; -- 100 +---- + +The C entry points are not `STRICT`, so they can handle NULL arguments instead of PostgreSQL returning NULL automatically. + +== Regression verification + +The `utl_match` regression group covers common example values (shackleford/shackelford, kitten/sitting, MARTHA/MARHTA, DWAYNE/DUANE, DIXON/DICKSONX, JELLYFISH/SMELLYFISH), case sensitivity, spaces, byte-level behavior of multi-byte characters, empty strings, NULL sentinel values, half-transposition truncation, the unconditional prefix boost and its 4-byte cap, match-window boundaries, half-up rounding boundaries, plus direct C entry-point calls and PL/iSQL package interface cases. + +From a configured and built IvorySQL source tree, run `make -C contrib/ivorysql_ora oracle-installcheck ORA_REGRESS=utl_match` 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/builtin_types_functions.adoc b/EN/modules/ROOT/pages/master/oracle_compatibility/builtin_types_functions.adoc index 8150dedf..0f0441c2 100644 --- a/EN/modules/ROOT/pages/master/oracle_compatibility/builtin_types_functions.adoc +++ b/EN/modules/ROOT/pages/master/oracle_compatibility/builtin_types_functions.adoc @@ -1149,3 +1149,34 @@ ivorysql=# select sys_context('USERENV','DB_NAME'); (1 row) ``` +=== `UTL_MATCH` package + +function: provides Oracle-compatible string matching and similarity computation. It contains four functions — `EDIT_DISTANCE`, `EDIT_DISTANCE_SIMILARITY`, `JARO_WINKLER`, and `JARO_WINKLER_SIMILARITY` — for spell checking, typo correction, and fuzzy matching or deduplication of short text such as names and addresses. Test cases are as follows: + +``` +SELECT UTL_MATCH.EDIT_DISTANCE('shackleford','shackelford'); + edit_distance +--------------- + 2 +(1 row) + +SELECT UTL_MATCH.EDIT_DISTANCE_SIMILARITY('shackleford','shackelford'); + edit_distance_similarity +-------------------------- + 82 +(1 row) + +SELECT ROUND(UTL_MATCH.JARO_WINKLER('shackleford','shackelford'),4); + round +--------- + 0.9818 +(1 row) + +SELECT UTL_MATCH.JARO_WINKLER_SIMILARITY('shackleford','shackelford'); + jaro_winkler_similarity +------------------------- + 98 +(1 row) +``` + +See xref:master/oracle_compatibility/compat_utl_match.adoc[UTL_MATCH package] for details. diff --git a/EN/modules/ROOT/pages/master/oracle_compatibility/compat_ascii_function.adoc b/EN/modules/ROOT/pages/master/oracle_compatibility/compat_ascii_function.adoc new file mode 100644 index 00000000..71ae6bec --- /dev/null +++ b/EN/modules/ROOT/pages/master/oracle_compatibility/compat_ascii_function.adoc @@ -0,0 +1,32 @@ +:sectnums: +:sectnumlevels: 5 + += ASCII function + +== Description + +`ASCII` returns the unsigned integer value of the first byte of the input converted to a string, as an `integer`. For a string beginning with an ASCII character, this is its ASCII code; subsequent characters do not affect the result. + +== Syntax + +[source,sql] +---- +ASCII(value) +---- + +The Oracle-compatible overloads accept `VARCHAR2`, `NUMBER`, `BINARY_FLOAT`, `BINARY_DOUBLE`, `DATE`, `TIMESTAMP`, and `TIMESTAMP WITH TIME ZONE`. Numbers are converted to strings first. Date and time values are formatted using the session's `nls_date_format`, `nls_timestamp_format`, and `nls_timestamp_tz_format`, respectively, so the result can depend on those settings. A NULL input or an empty converted string returns NULL. + +== Examples + +[source,sql] +---- +SELECT ascii('abc') FROM dual; -- 97, lowercase a +SELECT ascii('xyz') FROM dual; -- 120, lowercase x +SELECT ascii(321) FROM dual; -- 51, digit character 3 +SELECT ascii('') IS NULL FROM dual; -- true +SELECT ascii(to_char('2026-01-01'::date, 'DD-MON-YYYY HH24:MI:SS')) FROM dual; -- 48 +---- + +== Non-ASCII characters + +For the Oracle-compatible overloads, a non-ASCII character yields the value of its first byte in the database encoding, not its Unicode code point or the value of the complete multibyte character. For example, in a UTF8 database, the first byte of `中` is hexadecimal `E4`, or decimal 228. The result depends on the encoding and the overload selected for the call; do not use it to obtain Unicode code points for non-ASCII characters. 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]. diff --git a/EN/modules/ROOT/pages/master/oracle_compatibility/compat_utl_match.adoc b/EN/modules/ROOT/pages/master/oracle_compatibility/compat_utl_match.adoc new file mode 100644 index 00000000..36ebcb20 --- /dev/null +++ b/EN/modules/ROOT/pages/master/oracle_compatibility/compat_utl_match.adoc @@ -0,0 +1,115 @@ +:sectnums: +:sectnumlevels: 5 + += UTL_MATCH package + +== Purpose + +The Oracle-compatible `UTL_MATCH` package provides string matching and similarity computation. It contains four functions: `EDIT_DISTANCE`, `EDIT_DISTANCE_SIMILARITY`, `JARO_WINKLER`, and `JARO_WINKLER_SIMILARITY`, with behavior matching Oracle. It can be used for spell checking, fuzzy matching and deduplication of short text such as names or addresses, and external data cleansing. + +== Feature Description + +=== Functions + +[cols="4,2,4",options="header"] +|=== +|Function |Return type |Description +|`EDIT_DISTANCE(s1, s2)` |`INTEGER` |Minimum number of edits (each insertion, deletion, or substitution of one character counts as 1) needed to transform s1 into s2 +|`EDIT_DISTANCE_SIMILARITY(s1, s2)` |`INTEGER` |Edit-distance-based similarity score, 0–100. 0 means completely different, 100 means identical +|`JARO_WINKLER(s1, s2)` |`BINARY_DOUBLE` |Jaro-Winkler similarity, 0–1 +|`JARO_WINKLER_SIMILARITY(s1, s2)` |`INTEGER` |`JARO_WINKLER` multiplied by 100 and rounded, 0–100 +|=== + +=== Syntax + +[source,sql] +---- +SELECT UTL_MATCH.EDIT_DISTANCE(s1, s2) FROM dual; +SELECT UTL_MATCH.EDIT_DISTANCE_SIMILARITY(s1, s2) FROM dual; +SELECT UTL_MATCH.JARO_WINKLER(s1, s2) FROM dual; +SELECT UTL_MATCH.JARO_WINKLER_SIMILARITY(s1, s2) FROM dual; +---- + +`s1` and `s2` are the strings to compare (`VARCHAR2`). In Oracle compatibility mode (`ivorysql.compatible_mode = oracle`), call them directly. + +== Syntax Examples + +`EDIT_DISTANCE_SIMILARITY` produces an integer score from 0 to 100 based on edit distance: + +[source,sql] +---- +-- completely different strings, returns 0 +SELECT UTL_MATCH.EDIT_DISTANCE_SIMILARITY('123456', '456789') AS similarity FROM dual; + +-- one character differs, returns 83 +SELECT UTL_MATCH.EDIT_DISTANCE_SIMILARITY('123456', '123956') AS similarity FROM dual; + +-- identical strings, returns 100 +SELECT UTL_MATCH.EDIT_DISTANCE_SIMILARITY('123456', '123456') AS similarity FROM dual; +---- + +`JARO_WINKLER_SIMILARITY` boosts common prefixes and scores the same inputs higher: + +[source,sql] +---- +-- completely different strings, returns 0 +SELECT UTL_MATCH.JARO_WINKLER_SIMILARITY('123456', '456789') AS similarity FROM dual; + +-- one character differs, returns 92 +SELECT UTL_MATCH.JARO_WINKLER_SIMILARITY('123456', '123956') AS similarity FROM dual; + +-- identical strings, returns 100 +SELECT UTL_MATCH.JARO_WINKLER_SIMILARITY('123456', '123456') AS similarity FROM dual; +---- + +The following examples compare several pairs of strings: + +[cols="5,2",options="header"] +|=== +|Call |Result +|`EDIT_DISTANCE('shackleford', 'shackelford')` |`2` +|`EDIT_DISTANCE_SIMILARITY('shackleford', 'shackelford')` |`82` +|`JARO_WINKLER('shackleford', 'shackelford')` |`0.9818` +|`JARO_WINKLER_SIMILARITY('shackleford', 'shackelford')` |`98` +|`EDIT_DISTANCE('kitten', 'sitting')` |`3` +|`EDIT_DISTANCE_SIMILARITY('kitten', 'sitting')` |`57` +|`JARO_WINKLER_SIMILARITY('MARTHA', 'MARHTA')` |`96` +|`JARO_WINKLER_SIMILARITY('DWAYNE', 'DUANE')` |`84` +|`JARO_WINKLER_SIMILARITY('DIXON', 'DICKSONX')` |`81` +|`JARO_WINKLER_SIMILARITY('JELLYFISH', 'SMELLYFISH')` |`90` +|=== + +[source,sql] +---- +SELECT UTL_MATCH.EDIT_DISTANCE('shackleford', 'shackelford') AS edit_distance, + UTL_MATCH.EDIT_DISTANCE_SIMILARITY('shackleford', 'shackelford') AS similarity, + ROUND(UTL_MATCH.JARO_WINKLER('shackleford', 'shackelford'), 4) AS jaro_winkler, + UTL_MATCH.JARO_WINKLER_SIMILARITY('shackleford', 'shackelford') AS jw_similarity + FROM dual; +---- + +== Matching rules + +* Case-sensitive: `EDIT_DISTANCE('abc', 'ABC')` returns `3`, consistent with Oracle. +* Spaces are treated as ordinary characters: `EDIT_DISTANCE('a b', 'ab')` returns `1`. +* Byte-based comparison: strings are compared byte by byte rather than character by character (consistent with Oracle). For example, under UTF-8, `EDIT_DISTANCE('中文测试', '中文测A')` returns `3` (the final multi-byte character differs from `A` in all 3 of its UTF-8 bytes: 1 substitution plus 2 deletions), and `EDIT_DISTANCE_SIMILARITY('中文测试', '中文测A')` returns `75` (the maximum length in the formula is 12 bytes). +* Length limit: the input length limit is 32767 bytes, the same as Oracle's `VARCHAR2` limit. IvorySQL's implementation does not go through the PostgreSQL `fuzzystrmatch` extension, so it is not subject to the 255-byte limit of its `levenshtein` function. + +== NULL and empty strings + +`UTL_MATCH` handles NULL the way Oracle does: it does not propagate NULL but returns a fixed value per function: + +[cols="4,3",options="header"] +|=== +|Function |Return value when an input is NULL +|`EDIT_DISTANCE(s1, s2)` |`-1` +|`EDIT_DISTANCE_SIMILARITY(s1, s2)` |`0` if exactly one input is NULL; `100` if both are NULL +|`JARO_WINKLER(s1, s2)` |`0` +|`JARO_WINKLER_SIMILARITY(s1, s2)` |`0` +|=== + +In Oracle, an empty string is NULL. IvorySQL enables empty-string-to-NULL conversion by default (`ivorysql.enable_emptystring_to_NULL = on`), so `''` behaves like NULL. With that setting disabled, the algorithmic behavior of empty strings becomes observable: `EDIT_DISTANCE('', '')` returns `0`, and `EDIT_DISTANCE_SIMILARITY('', '')` returns `100`. + +== Implementation notes + +For algorithm details and the internal design, see xref:master/compatibility_features_design/utl_match_impl.adoc[UTL_MATCH implementation design]. diff --git a/EN/modules/ROOT/pages/master/oracle_compatibility/compat_utl_url.adoc b/EN/modules/ROOT/pages/master/oracle_compatibility/compat_utl_url.adoc new file mode 100644 index 00000000..e8bd74f3 --- /dev/null +++ b/EN/modules/ROOT/pages/master/oracle_compatibility/compat_utl_url.adoc @@ -0,0 +1,52 @@ +:sectnums: +:sectnumlevels: 5 + += UTL_URL package + +The `UTL_URL` package encodes and decodes URLs using percent escapes. + +== Feature Description + +=== ESCAPE + +[source,sql] +---- +UTL_URL.ESCAPE(url IN VARCHAR2, + escape_reserved_chars IN BOOLEAN DEFAULT FALSE, + url_charset IN VARCHAR2 DEFAULT NULL) RETURN VARCHAR2 +---- + +Converts bytes requiring escaping to `%XX`. Letters, digits and `- _ . ! ~ * ' ( )` are never escaped. Reserved characters `; / ? : @ & = + $ ,` are escaped only when `escape_reserved_chars` is `TRUE`; `FALSE` and `NULL` leave them unchanged. Spaces, `#`, `%`, other illegal ASCII characters and non-ASCII bytes are always escaped. Existing `%XX` sequences are escaped again. + +`url_charset` specifies the encoding used before escaping; PostgreSQL encoding names and supported charset aliases are accepted. An omitted or NULL charset selects the database encoding. A NULL `url` returns NULL. + +[source,sql] +---- +SELECT utl_url.escape('a b/c?d=e&f'); -- a%20b/c?d=e&f +SELECT utl_url.escape('a b/c?d=e&f', TRUE); -- a%20b%2Fc%3Fd%3De%26f +SELECT utl_url.escape('中文', FALSE, 'UTF8'); -- %E4%B8%AD%E6%96%87 +SELECT utl_url.escape('a%20b'); -- a%2520b +---- + +=== UNESCAPE + +[source,sql] +---- +UTL_URL.UNESCAPE(url IN VARCHAR2, + url_charset IN VARCHAR2 DEFAULT NULL) RETURN VARCHAR2 +---- + +Decodes `%XX` sequences into bytes and converts them from `url_charset` to the database encoding. Consecutive escaped bytes can form multibyte characters. An omitted or NULL charset selects the database encoding. Literal characters remain unchanged and `+` is not converted to a space. Only one layer is decoded; a NULL `url` returns NULL. + +[source,sql] +---- +SELECT utl_url.unescape('a%20b%2Fc'); -- a b/c +SELECT utl_url.unescape('%E4%B8%AD%E6%96%87', 'UTF8'); -- 中文 +SELECT utl_url.unescape('a%2520b'); -- a%20b +---- + +An incomplete or non-hexadecimal percent escape, `%00`, an unsupported charset, or bytes invalid for the specified encoding cause an error. Use the same charset for encoding and decoding. + +== Oracle compatibility + +Unlike Oracle, which uses `utl_http.body_charset` when the charset is omitted, IvorySQL uses the database encoding both for an omitted charset and an explicit NULL. Malformed escapes raise an error, but the Oracle `UTL_URL.BAD_URL` exception is not guaranteed. `%00` is rejected because database text cannot contain a NUL byte.