diff --git a/CN/modules/ROOT/pages/master/compatibility_features_design/dbms_output_impl.adoc b/CN/modules/ROOT/pages/master/compatibility_features_design/dbms_output_impl.adoc new file mode 100644 index 00000000..c4a9da36 --- /dev/null +++ b/CN/modules/ROOT/pages/master/compatibility_features_design/dbms_output_impl.adoc @@ -0,0 +1,137 @@ +:sectnums: +:sectnumlevels: 5 + += DBMS_OUTPUT 实现说明 + +== 目的 + +在 `ivorysql_ora` 扩展中提供 Oracle 风格的 DBMS_OUTPUT 包,支持会话级文本缓冲、逐行或批量读取,以及容量和行长检查。实现复用现有包机制、PL/iSQL 和 PostgreSQL C 函数接口,不新增专用语法或执行计划节点。 + +== 实现说明 + +=== 调用层次 + +[listing] +---- +DBMS_OUTPUT 包过程(PL/iSQL) + → sys.ora_dbms_output_*(LANGUAGE C VOLATILE) + → 当前 backend 的 output_buffer + ├── current_line:尚未结束的一行 + └── head → ... → tail:已完成行的单链表 +---- + +包提供 `ENABLE`、`DISABLE`、`PUT`、`PUT_LINE`、`NEW_LINE`、`GET_LINE` 和 `GET_LINES`。读取接口分别具有 `TEXT` / `VARCHAR2`、`TEXT[]` / `VARCHAR2[]` 重载,各重载调用同一个 C 实现。 + +C 层通过复合类型返回读取结果:`sys.dbms_output_line(line TEXT, status INTEGER)` 和 `sys.dbms_output_lines(lines TEXT[], numlines INTEGER)`。包体取出各字段并赋给 `OUT` / `IN OUT` 参数。 + +=== 缓冲区结构 + +`output_buffer` 是 backend 内的静态指针,不使用共享内存,各连接独立维护状态。 + +[cols="2,3", options="header"] +|=== +|结构 / 字段 +|用途 + +|`DbmsOutputBuffer.head / tail` +|已完成行链表的头、尾指针,支持尾部追加和头部消费。 + +|`buffer_size / buffer_used` +|`int64` 类型的容量限制和已完成行的内容字节数;容量为 -1 表示不限。 + +|`line_count / enabled` +|可读行数和启用状态。 + +|`current_line` +|`StringInfo`,累积 `PUT` 写入的未完成行。 + +|`buffer_mcxt` +|缓冲内容专用的 `AllocSet` 内存上下文。 + +|`DbmsOutputLine.next / len / data[]` +|下一行指针、字节长度和内嵌行数据;`len=-1` 表示 SQL NULL。 + +|=== + +每行按需分配一个节点,追加和摘取节点均为 O(1),避免连续缓冲区扩容时搬迁全部已有内容。数据复制成本仍随文本长度增长。 + +=== 写入与读取 + +. **启用**:`ora_dbms_output_enable()` 将 NULL 容量转换为 -1,将小于 2000 的容量提升到 2000,再调用 `init_output_buffer()`。SQL 层提供默认值 20000。缓冲区已启用时,`init_output_buffer()` 只更新容量上限,保留未读行和 `current_line`。 +. **写入**:`PUT` 只追加到 `current_line`;`PUT_LINE` 将待写文本与参数合并成完整行;`NEW_LINE` 将待写文本结束为一行。完整行通过 `add_line_to_buffer()` 追加至队尾。未启用时,三种写入操作直接返回。 +. **单行读取**:`GET_LINE` 调用 `pop_line_from_buffer()` 摘取队首,更新行数和容量计数,构造返回值后 `pfree()` 节点。成功返回 `status=0`;无行可读时返回 `(NULL, 1)`。 +. **批量读取**:`GET_LINES` 取请求行数与可读行数的较小值,逐行消费并构造下标从 1 开始的 `TEXT[]`。请求为负数时按 0 处理;无可读行或请求为 0 时返回空数组及行数 0。 + +读取只处理已完成行,不隐式结束 `current_line`。SQL NULL 行使用 `len=-1` 保存,并在返回元组或数组时设置 NULL 标志;空字符串行 `len=0` 与该标记不同,SQL 输入是否将空字符串转为 NULL 由上层兼容行为决定。 + +=== 容量和错误处理 + +[cols="2,3,1", options="header"] +|=== +|检查 +|实现位置 +|超限结果 + +|单行不超过 32767 字节 +|`PUT` 追加前、`PUT_LINE` 合并或直接入队前 +|`ORU-10028` + +|已完成行的内容不超过 `buffer_size` +|`add_line_to_buffer()` 分配节点前 +|`ORU-10027` + +|=== + +两类错误均通过 `ereport(ERROR)` 报出,SQLSTATE 为 `ERRCODE_PROGRAM_LIMIT_EXCEEDED`(54000)。容量检查采用 `line_len > buffer_size - buffer_used`,避免加法溢出。 + +`buffer_used` 不包括链表节点、分配器开销和未完成的 `current_line`;未完成行在入队时才接受总容量检查。读取后相应内容字节数从计数中扣除,因此容量可以复用。`ENABLE(NULL)` 仅取消内容容量检查,仍受单行长度和可用内存限制。 + +如果重复调用 `ENABLE` 将上限降到低于已缓冲的字节数,已有行仍可读取。新行若会超过上限,入队时会报 `ORU-10027`,读出足够的内容后即可继续写入。 + +=== 内存生命周期与会话清理 + +`DbmsOutputBuffer` 分配在 `TopMemoryContext` 中;行节点和 `current_line` 分配在其下的专用 `AllocSet` 中。因此缓冲内容不随语句、事务或子事务结束而释放,写入和读取也不会随事务回滚而撤销。 + +`cleanup_output_buffer()` 删除专用上下文、释放控制结构并将静态指针置空。触发清理的路径包括: + +- `DISABLE`:清理后保持禁用,直到再次启用。 +- `DISCARD ALL` / `DISCARD PACKAGE`(实际 SQL 语法为单数,命令标签显示为 `DISCARD PACKAGES`,且仅 Oracle 解析器支持):`ivorysql_ora_ProcessUtility()` 先调用前一个 hook 或 `standard_ProcessUtility()`,命令成功执行后调用 `ora_dbms_output_reset()` 清理,避免连接复用时残留输出。 +- backend 退出:会话内存随进程结束释放。 + +扩展通过 `_PG_init()` 安装 `ProcessUtility_hook`,并在 `_PG_fini()` 恢复原 hook。普通行读取仅释放被消费的节点,分配器可复用空间;这不等同于立即向操作系统归还内存。 + +=== 兼容边界 + +- 批量读取使用 `TEXT[]` / `VARCHAR2[]`,当前包未声明 Oracle 的 `CHARARR`、`DBMSOUTPUT_LINESARRAY` 集合类型。 +- 写入只更新会话缓冲区。IvorySQL 的 `psql` 通过顶层 `CALL` 显示读取过程的输出参数。示例见 xref:master/oracle_compatibility/compat_dbms_output.adoc[DBMS_OUTPUT 包]。 + +== 相关文件与验证 + +以下路径均相对于 `contrib/ivorysql_ora/`: + +[cols="2,3", options="header"] +|=== +|文件 +|职责 + +|`src/builtin_packages/dbms_output/dbms_output.c` +|缓冲管理、7 个 SQL 可调用 C 函数及重置函数。 + +|`src/builtin_packages/dbms_output/dbms_output--1.0.sql` +|C 函数注册、复合返回类型、包规范和包体。 + +|`src/ivorysql_ora.c`、`src/include/ivorysql_ora.h` +|Utility hook 集成及重置函数声明。 + +|`ivorysql_ora_merge_sqls`、`gensql.pl` +|将包 SQL 合并到扩展安装脚本。 + +|`Makefile`、`meson.build` +|将 C 实现编入 `ivorysql_ora` 动态库。 + +|`sql/ora_dbms_output.sql`、`expected/ora_dbms_output.out` +|回归用例与预期输出,Makefile 中以 `ora_dbms_output` 注册。 + +|=== + +回归用例 1.1 和 1.2 在 PL/iSQL 块内使用 `RAISE NOTICE` 输出读取结果,供测试框架与预期文件比对。用例 3.2 验证 `DISABLE` 清空缓冲区,用例 3.3 验证重复 `ENABLE` 保留内容并应用新容量。用例 10.1 验证同一会话可以跨事务读取,用例 13.1 验证 `DISCARD ALL` 清理缓冲区。其他用例覆盖行长限制、`VARCHAR2` 重载和读取后的空间复用。 diff --git a/CN/modules/ROOT/pages/master/compatibility_features_design/dbms_scheduler_impl.adoc b/CN/modules/ROOT/pages/master/compatibility_features_design/dbms_scheduler_impl.adoc new file mode 100644 index 00000000..20fe6af1 --- /dev/null +++ b/CN/modules/ROOT/pages/master/compatibility_features_design/dbms_scheduler_impl.adoc @@ -0,0 +1,238 @@ +:sectnums: +:sectnumlevels: 5 + += DBMS_SCHEDULER 实现说明 + +== 目的 + +`ivorysql_ora` 中的 `DBMS_SCHEDULER` 包提供作业管理、日历计算、同步执行和后台调度。配置和调用示例见 xref:master/oracle_compatibility/compat_dbms_scheduler.adoc[DBMS_SCHEDULER 包]。 + +== 实现说明 + +=== 元数据设计 + +PL/iSQL 包过程调用 `sys.ora_dbms_scheduler_*` C 函数,通过 SPI 访问当前数据库的 `sys` 模式。作业、程序和调度计划分别以所有者和对象名为主键,在同一所有者下共用命名空间。未加双引号的对象名转换为大写。 + +字段类型以 Oracle 兼容模式实例的系统目录为准。安装 SQL 将带时区的时间字段声明为 `timestamptz`,在该模式下对应 `oratimestamptz`。 + +包过程检查对象所有权,并负责维护作业对程序和计划的引用。强制删除被引用的程序或计划会禁用相关作业。基表不向 `PUBLIC` 授权,查询通过使用说明所列的字典视图进行。 + +==== `scheduler_jobs` + +保存直接定义的作业或引用命名程序和计划的作业。表约束要求两种定义方式二选一。`job_id` 有唯一索引,已启用的作业按 `next_run_date` 建有部分索引。 + +[cols="2,1,4", options="header"] +|=== +|字段 |类型 |说明 + +|`job_owner` |`name` |作业所有者角色,与 `job_name` 组成主键。 +|`job_name` |`name` |作业名。 +|`job_id` |`bigint` |作业唯一标识,由 `scheduler_job_id_seq` 生成。 +|`job_type` |`text` |直接定义的作业类型,取 `PLSQL_BLOCK` 或 `STORED_PROCEDURE`。 +|`job_action` |`text` |直接定义的作业执行文本或存储过程名。 +|`number_of_arguments` |`integer` |直接定义的作业参数数量,范围为 0–255,默认 0。命名程序作业的参数数量取自程序。 +|`program_owner` |`name` |引用的程序所有者角色。 +|`program_name` |`name` |引用的程序名。 +|`schedule_owner` |`name` |引用的计划所有者角色。 +|`schedule_name` |`name` |引用的计划名。 +|`start_date` |`oratimestamptz` |直接定义的作业开始时间。 +|`repeat_interval` |`text` |直接定义的作业重复规则。 +|`end_date` |`oratimestamptz` |直接定义的作业结束时间。 +|`next_run_date` |`oratimestamptz` |下一次计划运行时间。 +|`job_class` |`text` |为 Oracle 兼容保留的作业类参数。 +|`auto_drop` |`boolean` |为 Oracle 兼容保留的自动删除标志,默认 `TRUE`。 +|`comments` |`text` |作业备注。 +|`enabled` |`boolean` |作业是否参与后台调度,默认 `FALSE`。 +|`state` |`text` |作业状态,可取 `DISABLED`、`SCHEDULED`、`RUNNING`、`SUCCEEDED`、`FAILED`、`COMPLETED`。默认 `DISABLED`。 +|`run_count` |`bigint` |运行次数,初始为 0。 +|`failure_count` |`bigint` |失败计数,供后台连续失败上限判断。初始为 0。 +|`last_start_date` |`oratimestamptz` |最近一次计入统计的运行开始时间。 +|`last_end_date` |`oratimestamptz` |最近一次计入统计的运行结束时间。 +|=== + +==== `scheduler_programs` + +保存可供多个作业引用的执行内容。 + +[cols="2,1,4", options="header"] +|=== +|字段 |类型 |说明 + +|`program_owner` |`name` |程序所有者角色,与 `program_name` 组成主键。 +|`program_name` |`name` |程序名。 +|`program_type` |`text` |程序类型,取 `PLSQL_BLOCK` 或 `STORED_PROCEDURE`。 +|`program_action` |`text` |程序的执行文本或存储过程名。 +|`number_of_arguments` |`integer` |程序参数数量,范围为 0–255,默认 0。 +|`enabled` |`boolean` |程序是否可供作业执行,默认 `FALSE`。 +|`comments` |`text` |程序备注。 +|=== + +==== `scheduler_program_args` + +保存程序参数定义。主键由程序所有者、程序名和参数位置组成。删除程序时级联删除参数。同一程序的非空参数名有唯一索引。 + +[cols="2,1,4", options="header"] +|=== +|字段 |类型 |说明 + +|`program_owner` |`name` |所属程序的所有者角色。 +|`program_name` |`name` |所属程序名。 +|`argument_position` |`integer` |从 1 开始的参数位置,表允许 1–255,包还按程序声明的参数数量检查。 +|`argument_name` |`name` |可选的参数名。 +|`argument_type` |`text` |参数声明的 SQL 类型名。 +|`default_value` |`text` |参数默认值的文本表示。 +|`has_default` |`boolean` |是否定义了默认值,默认 `FALSE`。用于区分未设默认值和显式默认 `NULL`。 +|`out_argument` |`boolean` |输出参数标志,默认 `FALSE`。包只接受输入参数。 +|=== + +==== `scheduler_schedules` + +保存可供多个作业引用的调度时间和重复规则。 + +[cols="2,1,4", options="header"] +|=== +|字段 |类型 |说明 + +|`schedule_owner` |`name` |计划所有者角色,与 `schedule_name` 组成主键。 +|`schedule_name` |`name` |计划名。 +|`start_date` |`oratimestamptz` |计划开始时间和日历计算的起点。 +|`repeat_interval` |`text` |重复规则的日历表达式。 +|`end_date` |`oratimestamptz` |计划允许的最晚运行时间。 +|`comments` |`text` |计划备注。 +|=== + +==== `scheduler_job_args` + +保存作业显式设置的参数值。主键由作业所有者、作业名和参数位置组成。删除作业时级联删除参数。 + +[cols="2,1,4", options="header"] +|=== +|字段 |类型 |说明 + +|`job_owner` |`name` |所属作业的所有者角色。 +|`job_name` |`name` |所属作业名。 +|`argument_position` |`integer` |从 1 开始的参数位置,表允许 1–255。 +|`argument_value` |`text` |作业参数值的文本表示,可为 `NULL`。 +|=== + +==== `scheduler_job_run_details` + +每次运行保存一条记录。该表通过作业所有者和作业名建立索引,并保留没有外键约束的作业标识,删除作业后仍可查询历史。 + +[cols="2,1,4", options="header"] +|=== +|字段 |类型 |说明 + +|`log_id` |`bigint` |日志主键,由 `scheduler_log_id_seq` 生成。 +|`log_date` |`oratimestamptz` |日志创建时间,默认 `now()`,用于计算保留期限。 +|`job_owner` |`name` |运行时记录的作业所有者角色。 +|`job_name` |`name` |运行时记录的作业名。 +|`job_id` |`bigint` |本次运行对应的作业标识。 +|`status` |`text` |`r` 表示已领取或运行中,`s` 表示成功,`f` 表示失败。 +|`error_no` |`integer` |整数错误码。成功时记录 0,执行异常通常记录 PostgreSQL 编码后的 SQLSTATE。 +|`error_message` |`text` |失败或中断的诊断信息。 +|`req_start_date` |`oratimestamptz` |请求的开始时间,后台调度时为本次运行原定到期时间。 +|`actual_start_date` |`oratimestamptz` |记录的实际开始时间。 +|`worker_pid` |`integer` |执行本次运行的进程 PID,在字典视图中显示为 `SLAVE_PID`。 +|`worker_backend_start` |`oratimestamptz` |执行进程的启动时间。`STOP_JOB` 同时校验 PID 和启动时间,以识别 PID 复用。 +|`run_duration` |`pg_catalog.interval` |本次运行的耗时。 +|=== + +=== GUC 参数设计 + +`ivorysql_ora` 初始化时通过 `IvorysqlOraDefineGucs()` 注册 8 个调度器参数。`PGC_POSTMASTER` 参数在实例启动时生效,`PGC_SIGHUP` 参数可随配置重载生效。默认值与取值范围见使用文档。 + +==== 实例主进程与启动器参数 + +`ivorysql.scheduler`(`PGC_POSTMASTER`):: +实例主进程预加载扩展时用它决定是否注册启动器。启用作业的会话后端也读取该参数,以便在后台调度未开启时发出提示。 + +`ivorysql.scheduler_databases`(`PGC_SIGHUP`):: +启动器按数据库名单启动或停止数据库调度进程。启用作业的会话后端也读取该参数,检查当前数据库是否在名单内。 + +==== 数据库调度进程参数 + +`ivorysql.scheduler_poll_interval`(`PGC_SIGHUP`):: +设置调度循环的最长等待时间。作业或清理计划先到期时可提前唤醒。 + +`ivorysql.scheduler_max_job_workers`(`PGC_POSTMASTER`):: +决定每个数据库分配多少作业进程槽位,并限制并发派发数。 + +`ivorysql.scheduler_log_history`(`PGC_SIGHUP`):: +设置已结束运行记录的保留天数。0 表示在自动清理时删除全部已结束记录。 + +`ivorysql.scheduler_purge_schedule`(`PGC_SIGHUP`):: +用日历表达式计算下一次自动清理时间。空字符串关闭自动清理。表达式无效时记录日志并使用默认计划。 + +==== 作业执行进程参数 + +`ivorysql.scheduler_job_timeout`(`PGC_SIGHUP`):: +在作业动作开始前设置超时,到期后取消当前执行。0 表示不限时。 + +`ivorysql.scheduler_max_failures`(`PGC_SIGHUP`):: +回写后台作业统计时检查连续失败次数,达到上限时禁用作业。0 表示不设上限。 + +=== 三层后台进程架构 + +调度器使用 PostgreSQL 后台工作进程。下图表示注册和派发关系。 + +[listing] +---- +实例级启动器 SchedulerLauncherMain +└─ 数据库调度进程 SchedulerDatabaseWorkerMain + └─ 作业执行进程 SchedulerJobWorkerMain +---- + +==== 实例级启动器 + +启动器会轮询进程状态。它不连接具体数据库。 + +. 预加载 `ivorysql_ora` 且启用调度器时,实例注册一个启动器,待恢复完成后启动。 +. 每轮按 `ivorysql.scheduler_databases` 为名单内的数据库启动或管理调度进程,并停止已移出名单的进程。数据库调度进程自行退出后,启动器记录异常,待配置重载时重试。 +. 等待进程通知、配置重载信号或至多 10 秒的超时,再开始下一轮。 + +==== 数据库调度进程 + +每个数据库一个调度进程,采用轮询与事件唤醒相结合的方式。 + +. 以初始化超级用户身份连接数据库,确认已安装 `ivorysql_ora`,启动后收尾历史遗留的运行记录。 +. 每轮按清理计划删除过期的已结束记录,再回收已退出的作业进程并处理尚未收尾的运行记录。 +. 有空闲作业进程名额时,按 `next_run_date` 选取已启用、已到期且状态不是 `RUNNING` 的作业。更新下次运行时间,将作业标记为 `RUNNING`,插入状态为 `r` 的日志。提交后,为本次运行启动作业执行进程。 +. 等待上限为 `ivorysql.scheduler_poll_interval`,默认 5 秒。有空闲名额时可以等到最近的作业到期时间,日志清理到期或收到唤醒信号也可以提前结束等待。`ENABLE` 成功提交后会尝试唤醒该进程。 + +每库并发由 `ivorysql.scheduler_max_job_workers` 限制。同一作业的后台运行不会重叠,长时间运行期间错过的触发合并为一次后续运行。 + +==== 作业执行进程 + +每次派发启动一个作业执行进程。它以作业所有者身份连接目标数据库,在 Oracle 兼容模式下执行一次后退出,不进行轮询。 + +. 在第一个事务中把进程 PID 及启动时间写入运行日志,并读取作业定义和参数。 +. 在第二个事务中通过 SPI 执行作业动作。`ivorysql.scheduler_job_timeout` 大于 0 时启用超时。成功时提交,失败时回滚。 +. 在独立事务中写入运行结果并更新作业统计,然后退出。 + +== 相关文件与验证 + +以下路径相对于 `contrib/ivorysql_ora/`。 + +[cols="2,3", options="header"] +|=== +|文件 |职责 + +|`src/builtin_packages/dbms_scheduler/dbms_scheduler--1.0.sql` +|包规范、包体、元数据表和数据字典视图。 + +|`src/builtin_packages/dbms_scheduler/dbms_scheduler.c` 及同目录下的 `scheduler_calendar.c` +|包过程的 C 实现,以及日历表达式的解析和下一次运行时间计算。 + +|`src/builtin_packages/dbms_scheduler/scheduler_launcher.c` 及同目录下的 `scheduler_worker.c` +|启动器、数据库调度进程和作业工作进程。 + +|`src/guc/guc.c` +|调度器参数定义、默认值和生效方式。 + +|`sql/dbms_scheduler.sql`、`expected/dbms_scheduler.out` +|SQL 回归用例及预期输出,覆盖接口、日历、同步运行、所有权和日志清理。 + +|`t/001_dbms_scheduler.pl` +|后台调度 TAP 测试,覆盖重复运行、防止重叠、超时、停止、重启恢复和自动清理。 +|=== diff --git a/CN/modules/ROOT/pages/master/compatibility_features_design/lengthc_function_impl.adoc b/CN/modules/ROOT/pages/master/compatibility_features_design/lengthc_function_impl.adoc new file mode 100644 index 00000000..58326637 --- /dev/null +++ b/CN/modules/ROOT/pages/master/compatibility_features_design/lengthc_function_impl.adoc @@ -0,0 +1,71 @@ +:sectnums: +:sectnumlevels: 5 + += 字符长度函数实现说明 + +== 目的 + +`ivorysql_ora` 提供 Oracle 兼容的 `LENGTHC`,在 `UTF8` 下统计 Unicode NFC 规范化后的码点数。调用示例见 xref:master/oracle_compatibility/compat_lengthc_function.adoc[字符长度函数]。 + +== 实现说明 + +=== 字符输入与编码路径 + +`sys.lengthc(text)` 和 Oracle 兼容的 `CHAR`、`VARCHAR2` 字节及字符长度重载都直接调用 `ora_lengthc()`。C 函数读取字符串的变长数据,保留定长类型的尾随空格。先转为 `text` 会丢掉 `CHAR` 的补齐空格,因此这些重载直接处理原值。 + +核心入口是 `contrib/ivorysql_ora/src/builtin_functions/character_datatype_functions.c` 中的 `ora_lengthc(PG_FUNCTION_ARGS)`。UTF8 路径复用 PostgreSQL 的 `src/common/unicode_norm.c`,按 Unicode NFC 规则进行规范分解、排序和组合,再统计结果码点。非 UTF8 路径直接按数据库编码计数。 + +. 单字节数据库编码直接返回字节数。 +. 多字节的非 `UTF8` 编码调用 `pg_mbstrlen_with_len()` 统计字符。 +. `UTF8` 的纯 ASCII 输入直接返回字节数。对其他 `UTF8` 输入,先统计码点并检查分配上限,再解码为 `char32_t` 数组。 +. 调用 `unicode_is_normalized_quickcheck(UNICODE_NFC, ...)`。已确定为 NFC 时直接返回原码点数。 +. 其余情况调用 `unicode_normalize(UNICODE_NFC, ...)`,返回规范化后的码点数。 + +NFC 也可能增加码点数。例如 `U+0958` 规范化后为 `U+0915` 和 `U+093C`,此时 `LENGTHC` 返回 2。 + +=== 重载、类型转换与索引 + +安装脚本声明了 18 个精确重载,其中 15 个参与计数,3 个用于拒绝大对象。对于支持的非字符串类型,SQL 重载先将输入显式转为 `sys.oravarcharchar`,再复用字符计数入口。 + +[cols="1,3,3", options="header"] +|=== +|输入 |SQL 重载参数类型 |实现 + +|字符 +|`text`、`sys.oracharchar`、`sys.oracharbyte`、`sys.oravarcharchar`、`sys.oravarcharbyte` +|直接绑定 `ora_lengthc()` 的字符重载声明为 `STRICT`、`IMMUTABLE` 和 `PARALLEL SAFE`,支持字符列上的表达式索引。`LONG` 通过其基础类型 `text` 查找重载。 + +|数值 +|`integer`(`int4`)、`numeric`、`sys.number`、`sys.binary_double` +|按数值转换后的文本计数。 + +|日期时间 +|`sys.oradate`、`sys.oratimestamp`、`sys.oratimestamptz` +|文本格式取决于会话的 NLS 设置,因此这些重载声明为 `STABLE`。表达式索引会拒绝这些重载。 + +|二进制 +|`bytea`、`sys.raw`、`sys.long_raw` +|单独声明重载以免与 `BLOB` 产生歧义。按 `bytea_output` 转成文本后计数。 + +|大对象 +|`sys.clob`、`sys.nclob`、`sys.blob` +|精确匹配时调用 `ora_lengthc_unsupported()` 报类型错误。传入这些类型的 `NULL` 同样报错。 +|=== + +== 相关文件与验证 + +以下路径相对于 `contrib/ivorysql_ora/`。 + +[cols="2,3", options="header"] +|=== +|文件 |职责 + +|`src/builtin_functions/character_datatype_functions.c` +|字符计数、NFC 规范化和大对象类型错误。 + +|`src/builtin_functions/builtin_functions--1.0.sql` +|SQL 重载、类型转换和易变性声明。 + +|`sql/ora_character_datatype_functions.sql`、`expected/ora_character_datatype_functions.out` +|覆盖规范化、补齐空格、空值、类型转换、大对象拒绝和表达式索引。字符计数用例还与 `length(normalize(value, 'NFC'))` 的结果比对。 +|=== diff --git a/CN/modules/ROOT/pages/master/compatibility_features_design/utl_raw_impl.adoc b/CN/modules/ROOT/pages/master/compatibility_features_design/utl_raw_impl.adoc new file mode 100644 index 00000000..2df0ebc2 --- /dev/null +++ b/CN/modules/ROOT/pages/master/compatibility_features_design/utl_raw_impl.adoc @@ -0,0 +1,50 @@ +:sectnums: +:sectnumlevels: 5 + += UTL_RAW 实现说明 + +== 目的 + +`ivorysql_ora` 提供 Oracle 兼容的 `UTL_RAW.CAST_TO_RAW`,将文本的数据库编码字节作为 `RAW` 返回。调用示例见 xref:master/oracle_compatibility/compat_utl_raw.adoc[UTL_RAW 包]。 + +== 实现说明 + +=== 调用与编码 + +包规范声明 `CAST_TO_RAW(c IN VARCHAR2) RETURN RAW`,包体在 PL/iSQL 中执行以下表达式。 + +[source,sql] +---- +RETURN pg_catalog.convert_to(c::text, pg_catalog.getdatabaseencoding()); +---- + +. 将输入转为 `text`,并用 `getdatabaseencoding()` 取得当前数据库编码。 +. `convert_to()` 以数据库编码作为源编码。目标编码也取数据库编码,因此输出保留原字节。以 `LATIN1` 编码存储的 `é` 返回单字节 `e9`。 +. `convert_to()` 的结果为 `bytea`,包按声明返回 `sys.raw`。`sys.raw` 是基于 `bytea` 的域类型。 + +=== 显示与空值 + +`RAW` 沿用 `bytea_output` 的显示格式。默认以 `\x` 开头显示十六进制字节串。需要返回十六进制文本时可调用 xref:master/oracle_builtin_functions/rawtohex.adoc[RAWTOHEX]。 + +`convert_to()` 对 `NULL` 输入返回 `NULL`。空字符串的结果取决于传入包函数的值,分别对应 `NULL` 或零字节的 `RAW`。 + +== 相关文件与验证 + +以下路径相对于 `contrib/ivorysql_ora/`。 + +[cols="2,3", options="header"] +|=== +|文件 |职责 + +|`src/builtin_packages/utl_raw/utl_raw--1.0.sql` +|包规范、字节序常量及 PL/iSQL 函数体。 + +|`src/builtin_packages/utl_raw/utl_raw.c` +|保留模块说明。转换由包体调用内置函数完成。 + +|`ivorysql_ora_merge_sqls` +|将包定义合并到扩展安装脚本。 + +|`sql/utl_raw.sql`、`expected/utl_raw.out` +|回归用例及预期输出,覆盖 ASCII、多字节文本、空值、SQL 中引用包常量的错误以及 `LATIN1` 字节保留。 +|=== diff --git a/CN/modules/ROOT/pages/master/oracle_compatibility/compat_dbms_output.adoc b/CN/modules/ROOT/pages/master/oracle_compatibility/compat_dbms_output.adoc new file mode 100644 index 00000000..cc692da1 --- /dev/null +++ b/CN/modules/ROOT/pages/master/oracle_compatibility/compat_dbms_output.adoc @@ -0,0 +1,105 @@ +:sectnums: +:sectnumlevels: 5 + += DBMS_OUTPUT 包 + +== 目的 + +DBMS_OUTPUT 用于在匿名块、存储过程和函数中记录调试信息。信息先保存在当前会话的缓冲区中,再通过读取接口取出。 + +== 功能说明 + +DBMS_OUTPUT 由 `ivorysql_ora` 扩展提供。使用前应确认当前数据库已安装该扩展。以下示例使用 IvorySQL 的 psql 连接 Oracle 兼容端口(默认 1521,按实际配置修改): + +[source,sh] +---- +psql -h localhost -p 1521 -d postgres +---- + +通过 Oracle 兼容端口连接后,会话会自动进入 Oracle 兼容模式。 + +=== 接口 + +以下接口均以 `DBMS_OUTPUT.` 为前缀调用。 + +[cols="2,3", options="header"] +|=== +|接口 +|说明 + +|`ENABLE(buffer_size INTEGER DEFAULT 20000)` +|启用输出。默认容量为 20000 字节;小于 2000 的值按 2000 处理;传入 `NULL` 表示不设容量上限。 + +|`DISABLE()` +|禁用输出并清空缓冲区。禁用期间写入的信息会被忽略。 + +|`PUT(a TEXT)` +|追加文本,不结束当前行。 + +|`PUT_LINE(a TEXT)` +|追加文本并结束当前行。 + +|`NEW_LINE()` +|结束当前行;没有待写文本时生成空行。 + +|`GET_LINE(line OUT TEXT, status OUT INTEGER)` +|取出一行。`status` 为 0 表示成功,为 1 表示没有可读取的行。`line` 也支持 `VARCHAR2`。 + +|`GET_LINES(lines OUT TEXT[], numlines IN OUT INTEGER)` +|批量取出。`numlines` 输入期望行数,输出实际行数;`lines` 也支持 `VARCHAR2[]`。 + +|=== + +=== 使用要点 + +- 先调用 `ENABLE`,再写入信息。`PUT` 写入的内容要经过 `NEW_LINE` 或 `PUT_LINE` 结束该行后才能读取。 +- `PUT_LINE` 将文本写入缓冲区。在 IvorySQL 的 `psql` 中,用顶层 `CALL` 调用 `GET_LINE` 或 `GET_LINES`,终端会将输出参数显示为结果列。`psql` 不支持 SQL*Plus 的 `SET SERVEROUTPUT ON`。 +- 在 PL/iSQL 块内读取时,将结果接收到局部变量中,再按需处理,例如用 `RAISE NOTICE` 打印。 +- 读写必须使用同一数据库连接。读取会移除已取出的行。缓冲区在提交和回滚后继续保留。 +- 重复调用 `ENABLE` 会保留未读行和 `PUT` 写入但尚未结束的文本,并更新容量限制。需要清空后重新开始时,先调用 `DISABLE`,再调用 `ENABLE`。`DISCARD ALL`、`DISCARD PACKAGE` 和断开连接也会清空缓冲区。`DISCARD PACKAGE` 仅在 Oracle 兼容模式可用。 +- 单行最多 32767 **字节**。超出行长时报 `ORU-10028`,超出缓冲区容量时报 `ORU-10027`;可通过缩短单行、及时读取或调整容量处理。 + +== 使用示例 + +以下示例可直接在 IvorySQL 的 `psql` 中执行。 + +=== 写入并读取一行 + +[source,sql] +---- +CALL DBMS_OUTPUT.ENABLE(); +CALL DBMS_OUTPUT.PUT_LINE('Hello, IvorySQL!'); +CALL DBMS_OUTPUT.GET_LINE(NULL, NULL); +---- + +`GET_LINE` 的两个 `NULL` 是 `OUT` 参数的占位值。读取结果如下。 + +[listing] +---- + line | status +------------------+-------- + Hello, IvorySQL! | 0 +(1 row) +---- + +=== 拼接文本并批量读取 + +[source,sql] +---- +CALL DBMS_OUTPUT.ENABLE(NULL); +CALL DBMS_OUTPUT.PUT('Task: '); +CALL DBMS_OUTPUT.PUT('demo'); +CALL DBMS_OUTPUT.NEW_LINE(); +CALL DBMS_OUTPUT.PUT_LINE('Finished'); +CALL DBMS_OUTPUT.GET_LINES(NULL::text[], 10); +---- + +`NULL::text[]` 指定 `TEXT[]` 重载。本例请求最多 10 行,实际返回 2 行。若缓冲区还有未读行,可再次调用 `GET_LINES` 并指定每次最多读取的行数。 + +[listing] +---- + lines | numlines +-------------------------+---------- + {"Task: demo",Finished} | 2 +(1 row) +---- diff --git a/CN/modules/ROOT/pages/master/oracle_compatibility/compat_dbms_scheduler.adoc b/CN/modules/ROOT/pages/master/oracle_compatibility/compat_dbms_scheduler.adoc new file mode 100644 index 00000000..c010fe5a --- /dev/null +++ b/CN/modules/ROOT/pages/master/oracle_compatibility/compat_dbms_scheduler.adoc @@ -0,0 +1,225 @@ +:sectnums: +:sectnumlevels: 5 + += DBMS_SCHEDULER 包 + +== 目的 + +`DBMS_SCHEDULER` 用于创建、运行和管理数据库作业。作业可以直接指定执行内容,也可以引用程序和调度计划。 + +== 功能说明 + +`DBMS_SCHEDULER` 由 `ivorysql_ora` 扩展提供。以下示例使用 IvorySQL 的 `psql` 连接 Oracle 兼容端口(默认 1521)。该端口会自动为会话启用 Oracle 兼容模式。单独一行的 `/` 用于提交匿名块。 + +=== 接口 + +[cols="2,3", options="header"] +|=== +|过程 |说明 + +|`CREATE_JOB` +|直接指定 `job_type` 和 `job_action`,或同时指定 `program_name` 和 `schedule_name`。作业默认禁用。 + +|`CREATE_PROGRAM`、`CREATE_SCHEDULE` +|分别定义可复用的执行内容和调度计划。计划至少指定 `start_date` 或 `repeat_interval` 之一。 + +|`DEFINE_PROGRAM_ARGUMENT`、`DROP_PROGRAM_ARGUMENT`、`SET_JOB_ARGUMENT_VALUE` +|定义或删除程序的输入参数,并为作业设置参数值。作业参数可以按位置或名称设置。 + +|`ENABLE`、`DISABLE` +|启用或禁用作业或程序。要启用引用程序的作业,须先启用程序。 + +|`RUN_JOB`、`STOP_JOB` +|`RUN_JOB` 在当前会话同步执行作业,包括尚未启用的作业。`STOP_JOB` 向同一数据库中正在运行的作业发出取消请求。 + +|`DROP_JOB`、`DROP_PROGRAM`、`DROP_SCHEDULE` +|删除对应对象。删除作业后,其运行历史仍可查询。 + +|`EVALUATE_CALENDAR_STRING` +|以 `start_date` 为起点,通过 `next_run_date` 输出严格晚于 `return_date_after` 的下一次匹配时间。 + +|`PURGE_LOG` +|按保留天数清理已结束的运行记录,可指定单个作业。保留天数为 0 时清理选中的全部历史。 +|=== + +- 对于直接定义的作业,`job_action` 接收完整的匿名块文本或存储过程名。 +- 未加双引号的作业名在视图中显示为大写。 + +=== 兼容范围 + +IvorySQL 实现了 Oracle `DBMS_SCHEDULER` 的库内定时作业子集,支持一次性和周期性作业。上表列出了已实现的过程。 + +- **作业和参数**支持 `PLSQL_BLOCK` 和 `STORED_PROCEDURE`。程序参数限于存储过程的输入参数,可以定义默认值,也可以在作业上覆盖默认值。 +- **日历表达式**必须包含 `FREQ`,并支持 `INTERVAL`、`BYMONTH`、`BYMONTHDAY`、`BYDAY`、`BYDATE`、`BYHOUR`、`BYMINUTE` 和 `BYSECOND`。 +- **运行记录**支持查询和清理。`PURGE_LOG` 按名称筛选时一次只接受一个作业名。 + +作业链、作业类、调度窗口、事件触发计划、外部可执行程序和远程作业不在本次兼容范围内。`job_class` 和 `auto_drop` 仅作为元数据保存。 https://docs.oracle.com/en/database/oracle/oracle-database/19/arpls/DBMS_SCHEDULER.html[Oracle DBMS_SCHEDULER 参考] + +=== 执行方式 + +- **手动立即执行**。调用 `CALL DBMS_SCHEDULER.RUN_JOB('my_job');` 后,当前会话执行作业并等待结果。后台调度关闭时也可使用。`use_current_session` 默认为 `TRUE`。 +- **按计划后台执行**。用 `CALL DBMS_SCHEDULER.ENABLE('my_job');` 启用作业。目标数据库配置了后台调度时,调度器在作业到期后执行。省略 `repeat_interval` 时只调度一次。如果也省略 `start_date`,作业会在启用操作提交后尽快执行。 + +Oracle 支持用 `RUN_JOB(..., use_current_session => FALSE)` 提交一次后台运行请求并立即返回。IvorySQL 当前对 `FALSE` 报错。 + +=== 数据字典视图 + +视图位于 `sys` 模式。`USER_SCHEDULER_*` 仅显示当前用户拥有的对象及其运行历史。`DBA_SCHEDULER_*` 显示当前数据库中所有所有者的数据,并提供 `OWNER` 列,查询需要相应权限。 + +[cols="2,2,3", options="header"] +|=== +|当前用户视图 |全库视图 |用途 + +|`USER_SCHEDULER_JOBS` +|`DBA_SCHEDULER_JOBS` +|查看作业定义、启用状态、下次运行时间、运行次数和失败次数。 + +|`USER_SCHEDULER_PROGRAMS` +|`DBA_SCHEDULER_PROGRAMS` +|查看程序类型、执行内容、参数数量和启用状态。 + +|`USER_SCHEDULER_PROGRAM_ARGS` +|`DBA_SCHEDULER_PROGRAM_ARGS` +|查看程序参数的位置、名称、类型及默认值。 + +|`USER_SCHEDULER_SCHEDULES` +|`DBA_SCHEDULER_SCHEDULES` +|查看调度计划的起止时间和重复规则。 + +|`USER_SCHEDULER_JOB_ARGS` +|`DBA_SCHEDULER_JOB_ARGS` +|按位置查看在作业上显式设置的参数值。 + +|`USER_SCHEDULER_JOB_RUN_DETAILS` +|`DBA_SCHEDULER_JOB_RUN_DETAILS` +|查看每次运行的计划时间、实际开始时间、耗时和错误信息。状态 `r`、`s`、`f` 分别表示运行中、成功和失败。 +|=== + +=== 调度器 GUC 参数 + +在 `postgresql.conf` 中设置以下参数。后台执行还要求预加载 `ivorysql_ora`。 + +[cols="3,2,1,4", options="header"] +|=== +|参数 |默认值 |生效方式 |用途 + +|`ivorysql.scheduler` |`off` |重启 |启用后台调度器。 +|`ivorysql.scheduler_databases` |`''` |重载 |启用调度的数据库名单,以逗号分隔。空名单不调度任何数据库。 +|`ivorysql.scheduler_poll_interval` |5 秒 |重载 |数据库调度进程的轮询等待上限,范围为 1–600 秒。有作业即将到期时可提前唤醒。 +|`ivorysql.scheduler_max_job_workers` |4 |重启 |每个数据库可并行运行的后台作业进程上限,范围为 1–64,同时受实例的 `max_worker_processes` 限制。 +|`ivorysql.scheduler_job_timeout` |0 毫秒 |重载 |后台作业的执行超时,0 表示不限时。同步 `RUN_JOB` 使用调用会话的 `statement_timeout`。 +|`ivorysql.scheduler_max_failures` |0 |重载 |后台作业达到指定的连续失败次数后自动禁用。0 表示不设上限,`ENABLE` 会重置失败计数。 +|`ivorysql.scheduler_log_history` |30 天 |重载 |自动清理保留的运行历史天数。设为 0 时,清理会删除全部已结束的运行记录。 +|`ivorysql.scheduler_purge_schedule` +a|`FREQ=DAILY;` + +`BYHOUR=3;` + +`BYMINUTE=0;` + +`BYSECOND=0` +|重载 +|自动清理运行历史的时间,默认每天 03:00。空字符串关闭自动清理。 +|=== + +== 使用示例 + +=== 在当前会话运行作业 + +即使后台调度关闭,也可以用 `RUN_JOB` 立即执行。 + +[source,sql] +---- +CREATE TABLE scheduler_demo (note VARCHAR2(30)); + +BEGIN + DBMS_SCHEDULER.CREATE_JOB( + job_name => 'demo_once', + job_type => 'PLSQL_BLOCK', + job_action => 'BEGIN INSERT INTO scheduler_demo VALUES (''manual''); END;'); + DBMS_SCHEDULER.RUN_JOB('demo_once'); +END; +/ + +SELECT note FROM scheduler_demo; +SELECT job_name, status FROM user_scheduler_job_run_details +WHERE job_name = 'DEMO_ONCE' ORDER BY log_id; +---- + +表中新增一行 `manual`,作业运行记录的状态为 `s`。 + +=== 按计划在后台运行 + +确认 `shared_preload_libraries` 中包含 `ivorysql_ora`,再按以下示例在 `postgresql.conf` 中为 `postgres` 数据库启用后台调度并重启实例。 + +[source,ini] +---- +ivorysql.scheduler = on +ivorysql.scheduler_databases = 'postgres' +---- + +连接名单中的数据库,沿用前例的表。作业提交后,调度器按两秒间隔安排执行。待作业运行后查询成功记录。 + +[source,sql] +---- +BEGIN + DBMS_SCHEDULER.CREATE_JOB( + job_name => 'demo_repeat', + job_type => 'PLSQL_BLOCK', + job_action => 'BEGIN INSERT INTO scheduler_demo VALUES (''background''); END;', + repeat_interval => 'FREQ=SECONDLY;INTERVAL=2', + enabled => TRUE); +END; +/ + +SELECT job_name, status FROM user_scheduler_job_run_details +WHERE job_name = 'DEMO_REPEAT' AND status = 's' ORDER BY log_id; +---- + +验证后用 `CALL DBMS_SCHEDULER.DISABLE('demo_repeat');` 停止后续调度。 + +=== 使用 PROGRAM 和 SCHEDULE 创建定时作业 + +沿用前例的后台配置和 `scheduler_demo` 表。`PROGRAM` 指定要调用的存储过程和输入参数,`SCHEDULE` 指定每两秒运行一次。创建引用两者的作业后,先设置参数值,再启用作业。 + +[source,sql] +---- +CREATE OR REPLACE PROCEDURE scheduler_demo_write(p_note IN VARCHAR2) IS +BEGIN + INSERT INTO scheduler_demo VALUES (p_note); +END; +/ + +BEGIN + DBMS_SCHEDULER.CREATE_PROGRAM( + program_name => 'demo_program', + program_type => 'STORED_PROCEDURE', + program_action => 'scheduler_demo_write', + number_of_arguments => 1); + DBMS_SCHEDULER.DEFINE_PROGRAM_ARGUMENT( + program_name => 'demo_program', + argument_position => 1, + argument_name => 'p_note', + argument_type => 'VARCHAR2'); + DBMS_SCHEDULER.ENABLE('demo_program'); + + DBMS_SCHEDULER.CREATE_SCHEDULE( + schedule_name => 'demo_schedule', + repeat_interval => 'FREQ=SECONDLY;INTERVAL=2'); + DBMS_SCHEDULER.CREATE_JOB( + job_name => 'demo_named', + program_name => 'demo_program', + schedule_name => 'demo_schedule'); + DBMS_SCHEDULER.SET_JOB_ARGUMENT_VALUE('demo_named', 1, 'named schedule'); + DBMS_SCHEDULER.ENABLE('demo_named'); +END; +/ +---- + +待作业运行后,以下查询应返回 `named schedule` 和状态为 `s` 的运行记录。 + +[source,sql] +---- +SELECT DISTINCT note FROM scheduler_demo WHERE note = 'named schedule'; +SELECT job_name, status FROM user_scheduler_job_run_details +WHERE job_name = 'DEMO_NAMED' AND status = 's' ORDER BY log_id; +---- + +验证后用 `CALL DBMS_SCHEDULER.DISABLE('demo_named');` 停止后续调度。已有运行结束后,可先用 `DROP_JOB` 删除示例作业,再用 `DROP_PROGRAM` 和 `DROP_SCHEDULE` 删除程序和计划,最后删除存储过程和示例表。 diff --git a/CN/modules/ROOT/pages/master/oracle_compatibility/compat_lengthc_function.adoc b/CN/modules/ROOT/pages/master/oracle_compatibility/compat_lengthc_function.adoc new file mode 100644 index 00000000..d2ffa5a1 --- /dev/null +++ b/CN/modules/ROOT/pages/master/oracle_compatibility/compat_lengthc_function.adoc @@ -0,0 +1,97 @@ +:sectnums: +:sectnumlevels: 5 +:note-caption: 注意 + += 字符长度函数 + +== 目的 + +`LENGTHC` 是 Oracle 字符串长度函数之一,计数单位是 Unicode 完整字符。IvorySQL 在 `UTF8` 数据库中统计 NFC 规范化后的码点数,因此同一个字符的预组合形式和规范等价的分解形式计数相同。 + +== 功能说明 + +需要按规范化后的字符数比较文本长度时,可以使用 `LENGTHC`。例如,同一个带重音的字母可能由一个码点表示,也可能由字母与组合重音两个码点表示。 + +`LENGTHC` 由 `ivorysql_ora` 扩展提供。以下示例通过 Oracle 兼容端口(默认 1521)连接 `UTF8` 数据库。 + +=== 接口 + +`LENGTHC(value)` 返回 `integer`,也可以写成 `sys.lengthc(value)`。 + +这是一个 SQL 函数。参数可以是字面量、表字段、函数返回值或返回单值的标量子查询。表达式的类型需要直接匹配可用重载,或通过已有类型转换匹配。 + +字符输入为 `NULL` 时返回 `NULL`。空字符串在默认的 `ivorysql.enable_emptystring_to_NULL = on` 下返回 `NULL`,设为 `off` 时返回 0。`CHAR` 补齐的尾随空格也计入长度。 + +=== Oracle 长度函数的计数单位 + +[cols="1,3", options="header"] +|=== +|函数 |计数单位 + +|`LENGTH` |输入字符集中的字符 +|`LENGTHB` |字节 +|`LENGTHC` |Unicode 完整字符 +|`LENGTH2` |UCS-2 代码单元 +|`LENGTH4` |UCS-4 代码单元 +|=== + +IvorySQL 在 `UTF8` 数据库中按 NFC 规范化后的码点计数。在其他数据库编码下,`LENGTHC` 仍可使用,按该编码直接统计字符数。 + +=== 兼容范围 + +IvorySQL 支持 `CHAR`、`NCHAR`、`VARCHAR2` 和 `text` 等字符输入。Oracle 还在文档中列出 `NVARCHAR2`,当前 IvorySQL 不识别该类型名。直接传入 `CLOB`、`NCLOB` 或 `BLOB` 会报类型错误,即使值为这些类型的 `NULL`。 https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/LENGTH.html[Oracle LENGTH 系列函数参考] + +数值、日期时间以及 `RAW`、`bytea` 等输入会先转成文本再计数。日期时间结果取决于会话格式。二进制值在默认十六进制格式下会将 `\x` 前缀计入长度。 + +== 使用示例 + +=== 比较字符数、字节数和规范化后的长度 + +[source,sql] +---- +SELECT sample_name, + pg_catalog.encode(pg_catalog.convert_to(sample_text, 'UTF8'), 'hex') AS utf8_hex, + LENGTH(sample_text) AS char_count, + LENGTHB(sample_text) AS byte_count, + LENGTHC(sample_text) AS normalized_count +FROM (VALUES (1, 'precomposed', CHR(233)), + (2, 'decomposed', 'e' || CHR(769)), + (3, 'q_with_accent', 'q' || CHR(769))) samples(sample_no, sample_name, sample_text) +ORDER BY sample_no; +---- + +[listing] +---- + sample_name | utf8_hex | char_count | byte_count | normalized_count +---------------+----------+------------+------------+------------------ + precomposed | c3a9 | 1 | 2 | 1 + decomposed | 65cc81 | 2 | 3 | 1 + q_with_accent | 71cc81 | 2 | 3 | 2 +(3 rows) +---- + +预组合的 `é` 使用一个码点 `U+00E9`。分解形式使用 `e`(`U+0065`)和组合尖音符(`U+0301`)。NFC 将这两种形式规范为同一个码点。 https://www.unicode.org/reports/tr15/[Unicode 规范化形式] + +[NOTE] +==== +NFC 只会合并 Unicode 规定可组合的码点。`q` 加组合尖音符在 NFC 后仍是两个码点,即使显示时看起来像一个字符。 +==== + +=== 统计定长字符值 + +[source,sql] +---- +SELECT LENGTHC(CAST('ab' AS CHAR(5 CHAR))) AS fixed_length, + LENGTHC(CAST('ab' AS VARCHAR2(5 CHAR))) AS variable_length +FROM dual; +---- + +[listing] +---- + fixed_length | variable_length +--------------+----------------- + 5 | 2 +(1 row) +---- + +`fixed_length` 为 5,包含 3 个补齐空格。`variable_length` 为 2。 diff --git a/CN/modules/ROOT/pages/master/oracle_compatibility/compat_utl_raw.adoc b/CN/modules/ROOT/pages/master/oracle_compatibility/compat_utl_raw.adoc new file mode 100644 index 00000000..7498086d --- /dev/null +++ b/CN/modules/ROOT/pages/master/oracle_compatibility/compat_utl_raw.adoc @@ -0,0 +1,67 @@ +:sectnums: +:sectnumlevels: 5 +:note-caption: 注意 + += UTL_RAW 包 + +== 目的 + +`UTL_RAW.CAST_TO_RAW` 将 `VARCHAR2` 文本转换为 `RAW`,保留文本在当前数据库编码中的字节。 + +== 功能说明 + +需要将文本的原始字节写入 `RAW` 列,或传给接收 `RAW` 参数的函数时,可以使用 `CAST_TO_RAW`。 + +`UTL_RAW` 由 `ivorysql_ora` 扩展提供。以下示例使用 IvorySQL 的 `psql` 连接 Oracle 兼容端口(默认 1521),该端口会自动为会话启用 Oracle 兼容模式。 + +=== 接口 + +[source,sql] +---- +FUNCTION CAST_TO_RAW(c IN VARCHAR2) RETURN RAW; +---- + +输入 `NULL` 时返回 `NULL`。空字符串由 `ivorysql.enable_emptystring_to_NULL` 控制。该参数为默认值 `on` 时返回 `NULL`,设为 `off` 时返回零字节的 `RAW`。 + +=== 兼容范围 + +==== 函数 + +IvorySQL 当前只实现了 Oracle `UTL_RAW` 中的 `CAST_TO_RAW` 函数。原版包还提供 `CAST_TO_VARCHAR2`、`CONVERT`、`BIT_AND` 和 `CONCAT` 等函数。 https://docs.oracle.com/en/database/oracle/oracle-database/19/arpls/UTL_RAW.html[Oracle UTL_RAW 参考] + +==== 常量 + +Oracle 的二进制数值转换函数用以下常量指定多字节数值的字节顺序。 + +- `BIG_ENDIAN`(1)表示大端序,最高有效字节在前。 +- `LITTLE_ENDIAN`(2)表示小端序,最低有效字节在前。 +- `MACHINE_ENDIAN`(3)表示使用数据库服务器的本机字节序。 + +IvorySQL 保留了这三个常量。`CAST_TO_RAW` 按原顺序返回文本字节。 + +[NOTE] +==== +这些常量可在 PL/iSQL 中引用。直接在 SQL 的 `SELECT` 中引用会报无效标识符。 +==== + +== 使用示例 + +=== 转换 ASCII 文本 + +[source,sql] +---- +SELECT UTL_RAW.CAST_TO_RAW('ABC') AS raw_value, + RAWTOHEX(UTL_RAW.CAST_TO_RAW('ABC')) AS hex_value; +---- + +默认十六进制显示格式下,`raw_value` 为 `\x414243`。`hex_value` 为 `414243`,是 xref:master/oracle_builtin_functions/rawtohex.adoc[RAWTOHEX] 返回的十六进制文本。 + +=== 转换多字节文本 + +[source,sql] +---- +SELECT pg_catalog.getdatabaseencoding() AS db_encoding, + pg_catalog.encode(UTL_RAW.CAST_TO_RAW('你好'), 'hex') AS raw_hex; +---- + +数据库编码为 `UTF8` 时,`raw_hex` 为 `e4bda0e5a5bd`。其他数据库编码下,结果反映该编码中的字节。 diff --git a/EN/modules/ROOT/pages/master/compatibility_features_design/dbms_output_impl.adoc b/EN/modules/ROOT/pages/master/compatibility_features_design/dbms_output_impl.adoc new file mode 100644 index 00000000..8d1de1b2 --- /dev/null +++ b/EN/modules/ROOT/pages/master/compatibility_features_design/dbms_output_impl.adoc @@ -0,0 +1,130 @@ +:sectnums: +:sectnumlevels: 5 + += DBMS_OUTPUT Implementation + +== Purpose + +`ivorysql_ora` provides an Oracle-style `DBMS_OUTPUT` package with session buffering, single-line and batch retrieval, and capacity and line-length checks. It uses the existing package mechanism, PL/iSQL, and the PostgreSQL C function interface. + +== Implementation + +=== Call Path + +[listing] +---- +DBMS_OUTPUT package procedures (PL/iSQL) + → sys.ora_dbms_output_* (LANGUAGE C VOLATILE) + → output_buffer in the current backend + ├── current_line Unfinished line + └── head → ... → tail Linked list of completed lines +---- + +The package provides `ENABLE`, `DISABLE`, `PUT`, `PUT_LINE`, `NEW_LINE`, `GET_LINE`, and `GET_LINES`. The read procedures have `TEXT` and `VARCHAR2` overloads for a single line and `TEXT[]` and `VARCHAR2[]` overloads for batches. The overloads share the same C implementation. + +The C functions return composite values of type `sys.dbms_output_line(line TEXT, status INTEGER)` or `sys.dbms_output_lines(lines TEXT[], numlines INTEGER)`. The package body assigns the fields to its `OUT` or `IN OUT` parameters. + +=== Buffer Structure + +`output_buffer` is a static pointer in each backend. Each connection maintains its own state. + +[cols="2,3", options="header"] +|=== +|Structure or field |Purpose + +|`DbmsOutputBuffer.head / tail` +|Head and tail of the completed-line list. New lines go at the tail, and reads remove lines from the head. + +|`buffer_size / buffer_used` +|The capacity limit and the total content bytes of completed lines, both stored as `int64`. A capacity of -1 means unlimited. + +|`line_count / enabled` +|Number of readable lines and whether buffering is enabled. + +|`current_line` +|A `StringInfo` holding the unfinished text written by `PUT`. + +|`buffer_mcxt` +|The dedicated `AllocSet` memory context for buffer contents. + +|`DbmsOutputLine.next / len / data[]` +|The next-line pointer, byte length, and inline line data. A length of -1 represents SQL `NULL`. +|=== + +Each completed line gets a node on demand. Appending or removing a node takes O(1), and copying the text takes time proportional to its length. + +=== Writing and Reading + +. `ora_dbms_output_enable()` maps a `NULL` capacity to -1 and raises values below 2,000 to 2,000 before calling `init_output_buffer()`. The SQL default is 20,000. For an active buffer, `init_output_buffer()` updates the limit and preserves unread lines and `current_line`. +. `PUT` appends to `current_line`. `PUT_LINE` combines pending text with its argument, and `NEW_LINE` completes the pending line. `add_line_to_buffer()` appends completed lines to the tail. These write operations return immediately while buffering is disabled. +. `GET_LINE` calls `pop_line_from_buffer()` to remove the head and update the line and byte counters. It builds the result and frees the node with `pfree()`. A successful read returns status 0. An empty buffer returns `(NULL, 1)`. +. `GET_LINES` reads up to the requested number of available lines and builds a one-based `TEXT[]`. Negative requests are treated as zero. With no readable lines or a request of zero, it returns an empty array and a count of zero. + +Reads consume completed lines only. A line with `len = -1` sets the SQL `NULL` flag in the result. A line of length zero represents an empty string. The session's empty-string compatibility setting determines whether SQL input is converted to `NULL` before reaching the package. + +=== Capacity and Errors + +[cols="2,3,1", options="header"] +|=== +|Limit |Check |Error + +|32,767 bytes per line +|Checked before a `PUT` append and when `PUT_LINE` combines pending text or queues a line directly. +|`ORU-10028` + +|Completed-line content within `buffer_size` +|Checked in `add_line_to_buffer()` before allocating a node. +|`ORU-10027` +|=== + +Both errors use `ereport(ERROR)` with SQLSTATE `54000` (`ERRCODE_PROGRAM_LIMIT_EXCEEDED`). The capacity check uses `line_len > buffer_size - buffer_used` to avoid addition overflow. + +`buffer_used` counts completed-line content bytes. It excludes nodes, allocator overhead, and the unfinished `current_line`, whose content counts once the line is queued. Reads free capacity for later writes. `ENABLE(NULL)` removes the content capacity limit. The line limit and available memory still apply. + +If a repeat `ENABLE` lowers the capacity below what is already buffered, existing lines remain readable. A new line that would exceed the limit raises `ORU-10027`. Reading enough buffered content allows writes to resume. + +=== Memory Lifetime and Session Cleanup + +`DbmsOutputBuffer` lives in `TopMemoryContext`, and line nodes and `current_line` live in a dedicated child `AllocSet`. Buffer contents survive statement, transaction, and subtransaction boundaries. Transaction rollback does not undo buffer writes or reads. + +`cleanup_output_buffer()` deletes the child context, frees the control structure, and clears the static pointer. The buffer is cleared through these paths. + +- `DISABLE` clears it and leaves buffering disabled until `ENABLE` is called again. +- For `DISCARD ALL` and `DISCARD PACKAGE`, `ivorysql_ora_ProcessUtility()` delegates to the previous hook or `standard_ProcessUtility()`. After the command succeeds, it calls `ora_dbms_output_reset()` so reused connections start with a clean buffer. The Oracle parser recognizes `DISCARD PACKAGE`, whose command tag is `DISCARD PACKAGES`. +- When the backend exits, its session memory is released. + +The extension installs the `ProcessUtility_hook` in `_PG_init()` and restores the previous hook in `_PG_fini()`. A normal read frees the consumed nodes, whose space the allocator can reuse. + +=== Compatibility Scope + +- Batch reads use `TEXT[]` and `VARCHAR2[]`. The package does not declare Oracle's `CHARARR` or `DBMSOUTPUT_LINESARRAY` collection types. +- Writes update the session buffer. In IvorySQL's `psql`, a top-level `CALL` displays the read procedures' output parameters. See xref:master/oracle_compatibility/compat_dbms_output.adoc[DBMS_OUTPUT Package] for examples. + +== Related Files and Tests + +Paths are relative to `contrib/ivorysql_ora/`. + +[cols="2,3", options="header"] +|=== +|File |Role + +|`src/builtin_packages/dbms_output/dbms_output.c` +|Buffer management, seven SQL-callable C functions, and the reset function. + +|`src/builtin_packages/dbms_output/dbms_output--1.0.sql` +|C function registrations, composite return types, and the package specification and body. + +|`src/ivorysql_ora.c`, `src/include/ivorysql_ora.h` +|Utility hook integration and the reset function declaration. + +|`ivorysql_ora_merge_sqls`, `gensql.pl` +|Include the package SQL in the extension installation script. + +|`Makefile`, `meson.build` +|Build the C implementation into the `ivorysql_ora` shared library. + +|`sql/ora_dbms_output.sql`, `expected/ora_dbms_output.out` +|Regression cases and expected output. The Makefile registers the test as `ora_dbms_output`. +|=== + +Cases 1.1 and 1.2 print PL/iSQL read results with `RAISE NOTICE` for comparison with the expected output. Cases 3.2 and 3.3 check that `DISABLE` clears the buffer and a repeat `ENABLE` preserves contents while applying the new limit. Case 10.1 reads across transactions in one session, and case 13.1 checks cleanup by `DISCARD ALL`. Other cases cover line length, `VARCHAR2` overloads, and capacity reuse after reads. diff --git a/EN/modules/ROOT/pages/master/compatibility_features_design/dbms_scheduler_impl.adoc b/EN/modules/ROOT/pages/master/compatibility_features_design/dbms_scheduler_impl.adoc new file mode 100644 index 00000000..09e194c3 --- /dev/null +++ b/EN/modules/ROOT/pages/master/compatibility_features_design/dbms_scheduler_impl.adoc @@ -0,0 +1,238 @@ +:sectnums: +:sectnumlevels: 5 + += DBMS_SCHEDULER Implementation + +== Purpose + +The `DBMS_SCHEDULER` package in `ivorysql_ora` manages jobs, evaluates calendars, and executes jobs synchronously or on a background schedule. For configuration and examples, see xref:master/oracle_compatibility/compat_dbms_scheduler.adoc[DBMS_SCHEDULER Package]. + +== Implementation + +=== Metadata Design + +PL/iSQL package procedures call the `sys.ora_dbms_scheduler_*` C functions, which use SPI to access the current database's `sys` schema. Jobs, programs, and schedules each use an owner and object name as their primary key and share a namespace per owner. Unquoted object names are converted to uppercase. + +Column types are shown as stored in an Oracle-compatible instance. The installation SQL declares time-zone-aware columns as `timestamptz`, which maps to `oratimestamptz` in this mode. + +The package checks object ownership and manages job references to programs and schedules. Forcing the drop of a referenced program or schedule disables dependent jobs. The base tables grant no access to `PUBLIC`. Query the dictionary views listed in the usage guide. + +==== `scheduler_jobs` + +Stores inline jobs and jobs that reference a named program and schedule. A table constraint requires exactly one of these forms. A unique index covers `job_id`, and a partial index on `next_run_date` covers enabled jobs. + +[cols="2,1,4", options="header"] +|=== +|Column |Type |Description + +|`job_owner` |`name` |Owning role. Together with `job_name`, forms the primary key. +|`job_name` |`name` |Job name. +|`job_id` |`bigint` |Unique job identifier generated by `scheduler_job_id_seq`. +|`job_type` |`text` |Inline job type, either `PLSQL_BLOCK` or `STORED_PROCEDURE`. +|`job_action` |`text` |Executable text or stored procedure name for an inline job. +|`number_of_arguments` |`integer` |Inline job argument count, from 0 to 255, defaulting to 0. Named-program jobs use the program's count. +|`program_owner` |`name` |Owning role of the referenced program. +|`program_name` |`name` |Name of the referenced program. +|`schedule_owner` |`name` |Owning role of the referenced schedule. +|`schedule_name` |`name` |Name of the referenced schedule. +|`start_date` |`oratimestamptz` |Start time for an inline job. +|`repeat_interval` |`text` |Repeat rule for an inline job. +|`end_date` |`oratimestamptz` |End time for an inline job. +|`next_run_date` |`oratimestamptz` |Next scheduled run time. +|`job_class` |`text` |Job class argument stored for Oracle compatibility. +|`auto_drop` |`boolean` |Automatic deletion flag stored for Oracle compatibility. Defaults to `TRUE`. +|`comments` |`text` |Job comments. +|`enabled` |`boolean` |Whether the job participates in background scheduling. Defaults to `FALSE`. +|`state` |`text` |Job state. Allowed values are `DISABLED`, `SCHEDULED`, `RUNNING`, `SUCCEEDED`, `FAILED`, and `COMPLETED`. Defaults to `DISABLED`. +|`run_count` |`bigint` |Run count, initially zero. +|`failure_count` |`bigint` |Failure count used to enforce the consecutive-failure limit for background jobs. Initially zero. +|`last_start_date` |`oratimestamptz` |Start time of the latest run recorded in the job statistics. +|`last_end_date` |`oratimestamptz` |End time of the latest run recorded in the job statistics. +|=== + +==== `scheduler_programs` + +Stores actions that multiple jobs can reference. + +[cols="2,1,4", options="header"] +|=== +|Column |Type |Description + +|`program_owner` |`name` |Owning role. Together with `program_name`, forms the primary key. +|`program_name` |`name` |Program name. +|`program_type` |`text` |Program type, either `PLSQL_BLOCK` or `STORED_PROCEDURE`. +|`program_action` |`text` |Executable text or stored procedure name. +|`number_of_arguments` |`integer` |Program argument count, from 0 to 255, defaulting to 0. +|`enabled` |`boolean` |Whether jobs can execute the program. Defaults to `FALSE`. +|`comments` |`text` |Program comments. +|=== + +==== `scheduler_program_args` + +Stores program argument definitions. The primary key combines program owner, program name, and argument position. Deleting a program cascades to its arguments. A unique index covers non-null argument names within each program. + +[cols="2,1,4", options="header"] +|=== +|Column |Type |Description + +|`program_owner` |`name` |Owning role of the associated program. +|`program_name` |`name` |Name of the associated program. +|`argument_position` |`integer` |One-based argument position. The table allows positions 1–255, and the package also checks the program's declared argument count. +|`argument_name` |`name` |Optional argument name. +|`argument_type` |`text` |Declared SQL type name of the argument. +|`default_value` |`text` |Text representation of the argument's default value. +|`has_default` |`boolean` |Whether a default was specified. Defaults to `FALSE` and distinguishes an omitted default from an explicit `NULL`. +|`out_argument` |`boolean` |Output argument flag. Defaults to `FALSE`. The package accepts input arguments only. +|=== + +==== `scheduler_schedules` + +Stores timing and recurrence rules that multiple jobs can reference. + +[cols="2,1,4", options="header"] +|=== +|Column |Type |Description + +|`schedule_owner` |`name` |Owning role. Together with `schedule_name`, forms the primary key. +|`schedule_name` |`name` |Schedule name. +|`start_date` |`oratimestamptz` |Schedule start time and calendar anchor. +|`repeat_interval` |`text` |Calendar expression for recurrence. +|`end_date` |`oratimestamptz` |Latest run time allowed by the schedule. +|`comments` |`text` |Schedule comments. +|=== + +==== `scheduler_job_args` + +Stores argument values explicitly set on jobs. The primary key combines job owner, job name, and argument position. Deleting a job cascades to its arguments. + +[cols="2,1,4", options="header"] +|=== +|Column |Type |Description + +|`job_owner` |`name` |Owning role of the associated job. +|`job_name` |`name` |Name of the associated job. +|`argument_position` |`integer` |One-based argument position, from 1 to 255. +|`argument_value` |`text` |Text representation of the job argument value. May be `NULL`. +|=== + +==== `scheduler_job_run_details` + +Stores one record per run and indexes job owner and name. The job identifier has no foreign key constraint, so history remains queryable after job deletion. + +[cols="2,1,4", options="header"] +|=== +|Column |Type |Description + +|`log_id` |`bigint` |Log primary key generated by `scheduler_log_id_seq`. +|`log_date` |`oratimestamptz` |Log creation time. Defaults to `now()` and is used to determine retention. +|`job_owner` |`name` |Job owner recorded for the run. +|`job_name` |`name` |Job name recorded for the run. +|`job_id` |`bigint` |Identifier of the job associated with the run. +|`status` |`text` |`r` means claimed or running, `s` succeeded, and `f` failed. +|`error_no` |`integer` |Integer error code. A successful run records zero, and execution errors generally store PostgreSQL's encoded SQLSTATE. +|`error_message` |`text` |Diagnostic message for a failure or interruption. +|`req_start_date` |`oratimestamptz` |Requested start time. For a scheduled run, this is the original due time. +|`actual_start_date` |`oratimestamptz` |Recorded actual start time. +|`worker_pid` |`integer` |PID of the process executing the run, exposed as `SLAVE_PID` in the dictionary views. +|`worker_backend_start` |`oratimestamptz` |Start time of the executing process. `STOP_JOB` checks both PID and start time to detect PID reuse. +|`run_duration` |`pg_catalog.interval` |Elapsed time of the run. +|=== + +=== Scheduler GUC Design + +During initialization, `ivorysql_ora` registers eight scheduler parameters through `IvorysqlOraDefineGucs()`. `PGC_POSTMASTER` settings take effect at server startup. `PGC_SIGHUP` settings can take effect on configuration reload. See the usage guide for defaults and ranges. + +==== Postmaster and Instance Launcher Parameters + +`ivorysql.scheduler` (`PGC_POSTMASTER`):: +The postmaster uses this setting during preloading to decide whether to register the launcher. A backend enabling a job also reads it to warn if background scheduling is disabled. + +`ivorysql.scheduler_databases` (`PGC_SIGHUP`):: +The launcher starts or stops database schedulers based on this list. A backend enabling a job also checks whether the current database is listed. + +==== Database Scheduler Parameters + +`ivorysql.scheduler_poll_interval` (`PGC_SIGHUP`):: +Sets the maximum wait per scheduling cycle. An earlier job or purge deadline can wake the scheduler sooner. + +`ivorysql.scheduler_max_job_workers` (`PGC_POSTMASTER`):: +Sets the number of job worker slots per database and caps concurrent dispatches. + +`ivorysql.scheduler_log_history` (`PGC_SIGHUP`):: +Sets how many days to retain finished run records. Zero removes all finished records when automatic purging runs. + +`ivorysql.scheduler_purge_schedule` (`PGC_SIGHUP`):: +Calculates the next automatic purge time from a calendar expression. An empty string disables automatic purging. The scheduler logs invalid expressions and uses the default schedule. + +==== Job Worker Parameters + +`ivorysql.scheduler_job_timeout` (`PGC_SIGHUP`):: +Arms a timeout before the job action starts and cancels execution when it expires. Zero disables the timeout. + +`ivorysql.scheduler_max_failures` (`PGC_SIGHUP`):: +Checks the consecutive failure count when updating background job statistics and disables the job at the limit. Zero disables the limit. + +=== Three-Tier Background Process Architecture + +The scheduler uses PostgreSQL background workers. The tree shows which process registers or dispatches the next tier. + +[listing] +---- +Instance launcher SchedulerLauncherMain +└─ Database scheduler SchedulerDatabaseWorkerMain + └─ Job worker SchedulerJobWorkerMain +---- + +==== Instance Launcher + +The launcher polls worker status. It does not connect to a database. + +. When scheduling is enabled and the server preloads `ivorysql_ora`, the server registers one launcher to start after recovery. +. Each cycle, the launcher starts or manages a scheduler for each database in `ivorysql.scheduler_databases` and stops schedulers for removed databases. It reports schedulers that stop on their own and retries them on configuration reload. +. It waits for a worker notification, a configuration reload signal, or a timeout of at most 10 seconds before starting the next cycle. + +==== Database Scheduler + +One scheduler per database combines polling with event-driven wakeups. + +. It connects as the bootstrap superuser, checks that `ivorysql_ora` is installed, and closes out run records left behind before startup. +. Each cycle, it purges expired records for finished runs when the purge is due, then reclaims slots from exited job workers and closes out their unfinished run records. +. If worker slots are available, it selects enabled, due jobs whose state is other than `RUNNING`, ordered by `next_run_date`. It updates the next run time, marks the job `RUNNING`, and inserts a run log entry with status `r`. After committing, it starts a job worker for the run. +. Its maximum wait is `ivorysql.scheduler_poll_interval`, which defaults to 5 seconds. With a slot available, it can wake at the next job deadline. A purge deadline or a wakeup signal can also shorten the wait. A committed `ENABLE` attempts to wake it sooner. + +`ivorysql.scheduler_max_job_workers` caps concurrency per database. Background runs of the same job never overlap. When a long run spans multiple scheduled times, the missed triggers collapse into one follow-up run. + +==== Job Worker + +Each dispatch starts one worker. It connects to the target database as the job owner, executes one run in Oracle compatibility mode, and exits without polling. + +. In the first transaction, it writes its PID and start time to the run log and loads the job definition and arguments. +. In the second transaction, it executes the job action through SPI, with a timeout if `ivorysql.scheduler_job_timeout` is positive. It commits a successful run or rolls back a failed one. +. In a separate transaction, it records the outcome and updates job statistics, then exits. + +== Related Files and Tests + +Paths are relative to `contrib/ivorysql_ora/`. + +[cols="2,3", options="header"] +|=== +|File |Role + +|`src/builtin_packages/dbms_scheduler/dbms_scheduler--1.0.sql` +|Package specification and body, metadata tables, and dictionary views. + +|`src/builtin_packages/dbms_scheduler/dbms_scheduler.c` and `scheduler_calendar.c` in the same directory +|C implementation of the package procedures, calendar parsing, and next-run calculation. + +|`src/builtin_packages/dbms_scheduler/scheduler_launcher.c` and `scheduler_worker.c` in the same directory +|Launcher, per-database schedulers, and job workers. + +|`src/guc/guc.c` +|Scheduler parameter definitions, defaults, and configuration contexts. + +|`sql/dbms_scheduler.sql`, `expected/dbms_scheduler.out` +|SQL regression tests and expected results for interfaces, calendars, synchronous runs, ownership checks, and log purging. + +|`t/001_dbms_scheduler.pl` +|Background scheduling TAP coverage for repeats, overlap prevention, timeouts, job cancellation, restart recovery, and automatic purging. +|=== diff --git a/EN/modules/ROOT/pages/master/compatibility_features_design/lengthc_function_impl.adoc b/EN/modules/ROOT/pages/master/compatibility_features_design/lengthc_function_impl.adoc new file mode 100644 index 00000000..b1b0b676 --- /dev/null +++ b/EN/modules/ROOT/pages/master/compatibility_features_design/lengthc_function_impl.adoc @@ -0,0 +1,71 @@ +:sectnums: +:sectnumlevels: 5 + += LENGTHC Implementation + +== Purpose + +`ivorysql_ora` provides Oracle-compatible `LENGTHC` to count Unicode code points after NFC normalization in `UTF8` databases. For examples, see xref:master/oracle_compatibility/compat_lengthc_function.adoc[LENGTHC Function]. + +== Implementation + +=== Character Inputs and Encoding Paths + +`sys.lengthc(text)` and the byte- and character-length variants of Oracle-compatible `CHAR` and `VARCHAR2` call `ora_lengthc()` directly. The C function reads the variable-length string data and preserves fixed-length padding. Casting a `CHAR` value to `text` would trim that padding, so these overloads operate on the original value. + +The entry point is `ora_lengthc(PG_FUNCTION_ARGS)` in `contrib/ivorysql_ora/src/builtin_functions/character_datatype_functions.c`. For UTF8 input it uses PostgreSQL's `src/common/unicode_norm.c` to apply Unicode NFC rules for canonical decomposition, ordering, and composition. Other database encodings use direct character counting. + +. For single-byte database encodings, return the byte count. +. For multibyte encodings other than `UTF8`, count characters with `pg_mbstrlen_with_len()`. +. For ASCII-only `UTF8` input, return the byte count. For other `UTF8` input, count code points, check the allocation limit, and decode into a `char32_t` array. +. Call `unicode_is_normalized_quickcheck(UNICODE_NFC, ...)` and return the existing count when the check confirms NFC. +. Otherwise, call `unicode_normalize(UNICODE_NFC, ...)` and return the normalized code point count. + +NFC can also increase the code point count. For example, `U+0958` normalizes to `U+0915` followed by `U+093C`, so `LENGTHC` returns 2. + +=== Overloads, Type Conversion, and Indexes + +The installation script declares 18 exact overloads. Fifteen count characters and three reject large-object types. For supported non-string inputs, the SQL overloads explicitly cast the value to `sys.oravarcharchar` before calling the character-counting function. + +[cols="1,3,3", options="header"] +|=== +|Input |SQL overload argument types |Implementation + +|Character +|`text`, `sys.oracharchar`, `sys.oracharbyte`, `sys.oravarcharchar`, `sys.oravarcharbyte` +|Character overloads bound to `ora_lengthc()` are `STRICT`, `IMMUTABLE`, and `PARALLEL SAFE`. They support expression indexes on character columns. `LONG` resolves through its base type, `text`. + +|Numeric +|`integer` (`int4`), `numeric`, `sys.number`, `sys.binary_double` +|Count the characters of the converted numeric text. + +|Datetime +|`sys.oradate`, `sys.oratimestamp`, `sys.oratimestamptz` +|Text formatting depends on session NLS settings, so these overloads are `STABLE`. Expression indexes reject them. + +|Binary +|`bytea`, `sys.raw`, `sys.long_raw` +|Separate overloads avoid ambiguity with `BLOB`. The count uses the text generated with `bytea_output`. + +|Large objects +|`sys.clob`, `sys.nclob`, `sys.blob` +|Call `ora_lengthc_unsupported()` to raise a type error on an exact match, including a `NULL` of one of these types. +|=== + +== Related Files and Tests + +Paths are relative to `contrib/ivorysql_ora/`. + +[cols="2,3", options="header"] +|=== +|File |Role + +|`src/builtin_functions/character_datatype_functions.c` +|Character counting, NFC normalization, and large-object type errors. + +|`src/builtin_functions/builtin_functions--1.0.sql` +|SQL overloads, type conversions, and volatility declarations. + +|`sql/ora_character_datatype_functions.sql`, `expected/ora_character_datatype_functions.out` +|Regression coverage for normalization, padding, null handling, type conversion, large-object rejection, and expression indexes. The counting cases also compare against `length(normalize(value, 'NFC'))`. +|=== diff --git a/EN/modules/ROOT/pages/master/compatibility_features_design/utl_raw_impl.adoc b/EN/modules/ROOT/pages/master/compatibility_features_design/utl_raw_impl.adoc new file mode 100644 index 00000000..67251e1b --- /dev/null +++ b/EN/modules/ROOT/pages/master/compatibility_features_design/utl_raw_impl.adoc @@ -0,0 +1,50 @@ +:sectnums: +:sectnumlevels: 5 + += UTL_RAW Implementation + +== Purpose + +`ivorysql_ora` provides Oracle-compatible `UTL_RAW.CAST_TO_RAW` to return text bytes in the database encoding as `RAW`. For examples, see xref:master/oracle_compatibility/compat_utl_raw.adoc[UTL_RAW Package]. + +== Implementation + +=== Calls and Encoding + +The package specification declares `CAST_TO_RAW(c IN VARCHAR2) RETURN RAW`. Its PL/iSQL body evaluates the following expression. + +[source,sql] +---- +RETURN pg_catalog.convert_to(c::text, pg_catalog.getdatabaseencoding()); +---- + +. Cast the input to `text` and retrieve the database encoding with `getdatabaseencoding()`. +. `convert_to()` uses the database encoding as its source. The target is also the database encoding, so the output preserves the original bytes. For example, `é` stored in a `LATIN1` database yields the single byte `e9`. +. `convert_to()` produces `bytea`, which the package returns as its declared type, `sys.raw`. `sys.raw` is a domain over `bytea`. + +=== Display and Null Values + +`RAW` uses the `bytea_output` display format. By default it appears as a hexadecimal string prefixed with `\x`. Use xref:master/oracle_builtin_functions/rawtohex.adoc[RAWTOHEX] to return hexadecimal text. + +`convert_to()` returns `NULL` for `NULL` input. The outcome for an empty string depends on the value passed to the package function, yielding either `NULL` or a zero-byte `RAW` value. + +== Related Files and Tests + +Paths are relative to `contrib/ivorysql_ora/`. + +[cols="2,3", options="header"] +|=== +|File |Role + +|`src/builtin_packages/utl_raw/utl_raw--1.0.sql` +|Package specification, byte-order constants, and PL/iSQL function body. + +|`src/builtin_packages/utl_raw/utl_raw.c` +|Module description. The package body performs the conversion through built-in functions. + +|`ivorysql_ora_merge_sqls` +|Includes the package definition in the extension installation script. + +|`sql/utl_raw.sql`, `expected/utl_raw.out` +|Regression coverage for ASCII, multibyte text, null input, the error when selecting a package constant in SQL, and byte preservation in `LATIN1`. +|=== diff --git a/EN/modules/ROOT/pages/master/oracle_compatibility/compat_dbms_output.adoc b/EN/modules/ROOT/pages/master/oracle_compatibility/compat_dbms_output.adoc new file mode 100644 index 00000000..d66a6859 --- /dev/null +++ b/EN/modules/ROOT/pages/master/oracle_compatibility/compat_dbms_output.adoc @@ -0,0 +1,101 @@ +:sectnums: +:sectnumlevels: 5 + += DBMS_OUTPUT Package + +== Purpose + +`DBMS_OUTPUT` records debugging messages from anonymous blocks, stored procedures, and functions. The package stores messages in a session buffer for later retrieval. + +== Functionality + +The `ivorysql_ora` extension provides `DBMS_OUTPUT`. Make sure the extension is installed in the current database. Connect with IvorySQL's `psql` using the Oracle compatibility port, which defaults to 1521 and selects Oracle compatibility mode for the session. + +[source,sh] +---- +psql -h localhost -p 1521 -d postgres +---- + +=== Interfaces + +Call each procedure with the `DBMS_OUTPUT.` prefix. + +[cols="2,3", options="header"] +|=== +|Procedure |Description + +|`ENABLE(buffer_size INTEGER DEFAULT 20000)` +|Enables buffering. The default is 20,000 bytes, and values below 2,000 are treated as 2,000. Pass `NULL` for unlimited capacity. + +|`DISABLE()` +|Disables buffering and clears the buffer. Writes while disabled are ignored. + +|`PUT(a TEXT)` +|Appends text to the current line without ending it. + +|`PUT_LINE(a TEXT)` +|Appends text and ends the current line. + +|`NEW_LINE()` +|Ends the current line. If there is no pending text, it adds an empty line. + +|`GET_LINE(line OUT TEXT, status OUT INTEGER)` +|Retrieves one line. A status of 0 means a line was read, and 1 means no line was available. The `line` output also supports `VARCHAR2`. + +|`GET_LINES(lines OUT TEXT[], numlines IN OUT INTEGER)` +|Retrieves lines in a batch. Pass the requested count in `numlines`. The procedure returns the actual count in the same parameter. The `lines` output also supports `VARCHAR2[]`. +|=== + +=== Usage Notes + +- Call `ENABLE` before writing. Use `NEW_LINE` or `PUT_LINE` to complete a line started with `PUT` before reading it. +- In IvorySQL's `psql`, a top-level `CALL` to `GET_LINE` or `GET_LINES` displays the output parameters as result columns. `psql` does not support SQL*Plus's `SET SERVEROUTPUT ON`. +- In a PL/iSQL block, read the output into local variables. You can print the retrieved text with `RAISE NOTICE`. +- Use the same database connection to write and read. Reading removes the retrieved lines. The buffer survives commits and rollbacks. +- Repeating `ENABLE` updates the capacity limit and preserves unread lines and unfinished `PUT` text. Call `DISABLE` followed by `ENABLE` to start with an empty buffer. `DISCARD ALL`, `DISCARD PACKAGE`, and disconnecting also clear the buffer. `DISCARD PACKAGE` is available in Oracle compatibility mode. +- Each line can contain up to 32,767 bytes. Exceeding the line limit raises `ORU-10028`. Exceeding the buffer limit raises `ORU-10027`. Shorten lines, read them sooner, or adjust the buffer capacity as appropriate. + +== Examples + +Run these examples in IvorySQL's `psql`. + +=== Write and Read One Line + +[source,sql] +---- +CALL DBMS_OUTPUT.ENABLE(); +CALL DBMS_OUTPUT.PUT_LINE('Hello, IvorySQL!'); +CALL DBMS_OUTPUT.GET_LINE(NULL, NULL); +---- + +The two `NULL` arguments are placeholders for the `OUT` parameters. + +[listing] +---- + line | status +------------------+-------- + Hello, IvorySQL! | 0 +(1 row) +---- + +=== Assemble Text and Read a Batch + +[source,sql] +---- +CALL DBMS_OUTPUT.ENABLE(NULL); +CALL DBMS_OUTPUT.PUT('Task: '); +CALL DBMS_OUTPUT.PUT('demo'); +CALL DBMS_OUTPUT.NEW_LINE(); +CALL DBMS_OUTPUT.PUT_LINE('Finished'); +CALL DBMS_OUTPUT.GET_LINES(NULL::text[], 10); +---- + +`NULL::text[]` selects the `TEXT[]` overload. This call requests up to 10 lines and returns two. Call `GET_LINES` again with the desired batch size if more lines remain. + +[listing] +---- + lines | numlines +-------------------------+---------- + {"Task: demo",Finished} | 2 +(1 row) +---- diff --git a/EN/modules/ROOT/pages/master/oracle_compatibility/compat_dbms_scheduler.adoc b/EN/modules/ROOT/pages/master/oracle_compatibility/compat_dbms_scheduler.adoc new file mode 100644 index 00000000..610b857f --- /dev/null +++ b/EN/modules/ROOT/pages/master/oracle_compatibility/compat_dbms_scheduler.adoc @@ -0,0 +1,225 @@ +:sectnums: +:sectnumlevels: 5 + += DBMS_SCHEDULER Package + +== Purpose + +`DBMS_SCHEDULER` creates, runs, and manages database jobs. A job can specify its action directly or refer to a program and a schedule. + +== Functionality + +The `ivorysql_ora` extension provides `DBMS_SCHEDULER`. These examples use IvorySQL's `psql` on the Oracle compatibility port, which defaults to 1521 and selects Oracle compatibility mode for the session. A `/` on its own line submits an anonymous block. + +=== Interfaces + +[cols="2,3", options="header"] +|=== +|Procedure |Description + +|`CREATE_JOB` +|Specify `job_type` and `job_action` directly, or supply both `program_name` and `schedule_name`. Jobs are disabled by default. + +|`CREATE_PROGRAM`, `CREATE_SCHEDULE` +|Define a reusable action and schedule, respectively. A schedule requires at least one of `start_date` and `repeat_interval`. + +|`DEFINE_PROGRAM_ARGUMENT`, `DROP_PROGRAM_ARGUMENT`, `SET_JOB_ARGUMENT_VALUE` +|Define or remove program input arguments and set job argument values. A job argument can be set by position or by name. + +|`ENABLE`, `DISABLE` +|Enable or disable a job or program. Enable a referenced program before enabling its job. + +|`RUN_JOB`, `STOP_JOB` +|`RUN_JOB` runs a job synchronously in the calling session, even if the job is disabled. `STOP_JOB` requests cancellation of an active run in the same database. + +|`DROP_JOB`, `DROP_PROGRAM`, `DROP_SCHEDULE` +|Drop the corresponding object. A job's run history remains available after the job is dropped. + +|`EVALUATE_CALENDAR_STRING` +|Evaluate a calendar anchored at `start_date` and return the next match strictly after `return_date_after` in `next_run_date`. + +|`PURGE_LOG` +|Purge completed run records by retention age, optionally for one job. A retention of zero purges all selected history. +|=== + +- For an inline job, supply the full anonymous block or the stored procedure name in `job_action`. +- The views display unquoted job names in uppercase. + +=== Oracle Compatibility Scope + +IvorySQL implements a subset of Oracle `DBMS_SCHEDULER` for local database jobs that run once or on a recurring schedule. The table above lists the implemented procedures. + +- **Jobs and arguments.** Supported job types are `PLSQL_BLOCK` and `STORED_PROCEDURE`. Program arguments are limited to stored procedure inputs. Programs can define defaults, and jobs can override them. +- **Calendar expressions.** Expressions require `FREQ` and support `INTERVAL`, `BYMONTH`, `BYMONTHDAY`, `BYDAY`, `BYDATE`, `BYHOUR`, `BYMINUTE`, and `BYSECOND`. +- **Run history.** You can query and purge job run history. `PURGE_LOG` accepts one job name when filtering by name. + +Job chains, job classes, scheduler windows, event schedules, external executables, and remote jobs are outside this subset. The scheduler stores `job_class` and `auto_drop` as metadata only. https://docs.oracle.com/en/database/oracle/oracle-database/19/arpls/DBMS_SCHEDULER.html[Oracle DBMS_SCHEDULER Reference] + +=== Execution Modes + +- **Run immediately.** With `CALL DBMS_SCHEDULER.RUN_JOB('my_job');`, the calling session executes the job and waits for the result. This works even when background scheduling is off. `use_current_session` defaults to `TRUE`. +- **Run on a background schedule.** Use `CALL DBMS_SCHEDULER.ENABLE('my_job');` to enable the job. When background scheduling is configured for the database, the scheduler runs the job when it is due. Omit `repeat_interval` to schedule a single run. If you also omit `start_date`, the job runs as soon as the scheduler can dispatch it after the enable operation commits. + +Oracle supports `RUN_JOB(..., use_current_session => FALSE)` to request one background run and return immediately. IvorySQL currently raises an error for `FALSE`. + +=== Dictionary Views + +The views are in the `sys` schema. The `USER_SCHEDULER_*` views show objects and run history owned by the current user. The `DBA_SCHEDULER_*` views include all owners in the current database and expose an `OWNER` column. Querying them requires the appropriate privileges. + +[cols="2,2,3", options="header"] +|=== +|Current-user view |Database-wide view |Purpose + +|`USER_SCHEDULER_JOBS` +|`DBA_SCHEDULER_JOBS` +|Job definitions, enabled status, next run time, run counts, and failure counts. + +|`USER_SCHEDULER_PROGRAMS` +|`DBA_SCHEDULER_PROGRAMS` +|Program type, action, argument count, and enabled status. + +|`USER_SCHEDULER_PROGRAM_ARGS` +|`DBA_SCHEDULER_PROGRAM_ARGS` +|Program argument positions, names, types, and default values. + +|`USER_SCHEDULER_SCHEDULES` +|`DBA_SCHEDULER_SCHEDULES` +|Schedule start and end times and repeat rules. + +|`USER_SCHEDULER_JOB_ARGS` +|`DBA_SCHEDULER_JOB_ARGS` +|Explicitly set job argument values by position. + +|`USER_SCHEDULER_JOB_RUN_DETAILS` +|`DBA_SCHEDULER_JOB_RUN_DETAILS` +|Scheduled and actual start times, duration, and error details for each run. Statuses `r`, `s`, and `f` indicate running, succeeded, and failed. +|=== + +=== Scheduler GUC Parameters + +Set these parameters in `postgresql.conf`. Background execution also requires preloading `ivorysql_ora`. + +[cols="3,2,1,4", options="header"] +|=== +|Parameter |Default |Applies on |Purpose + +|`ivorysql.scheduler` |`off` |Restart |Enables the background scheduler. +|`ivorysql.scheduler_databases` |`''` |Reload |Comma-separated list of databases to schedule. An empty list schedules no databases. +|`ivorysql.scheduler_poll_interval` |5 seconds |Reload |Maximum wait between polls, from 1 to 600 seconds. The database scheduler can wake sooner for a due job. +|`ivorysql.scheduler_max_job_workers` |4 |Restart |Maximum concurrent background job workers per database, from 1 to 64, subject to the instance-wide `max_worker_processes` limit. +|`ivorysql.scheduler_job_timeout` |0 ms |Reload |Execution timeout for background jobs. Zero disables the limit. Synchronous `RUN_JOB` uses the calling session's `statement_timeout`. +|`ivorysql.scheduler_max_failures` |0 |Reload |Disables a background job after this many consecutive failures. Zero disables the limit, and `ENABLE` resets the failure count. +|`ivorysql.scheduler_log_history` |30 days |Reload |Days of run history to retain during automatic purging. Zero purges all finished run records. +|`ivorysql.scheduler_purge_schedule` +a|`FREQ=DAILY;` + +`BYHOUR=3;` + +`BYMINUTE=0;` + +`BYSECOND=0` +|Reload +|Calendar for automatic history purging. The default is daily at 03:00. An empty string disables automatic purging. +|=== + +== Examples + +=== Run a Job in the Current Session + +`RUN_JOB` executes immediately even when background scheduling is off. + +[source,sql] +---- +CREATE TABLE scheduler_demo (note VARCHAR2(30)); + +BEGIN + DBMS_SCHEDULER.CREATE_JOB( + job_name => 'demo_once', + job_type => 'PLSQL_BLOCK', + job_action => 'BEGIN INSERT INTO scheduler_demo VALUES (''manual''); END;'); + DBMS_SCHEDULER.RUN_JOB('demo_once'); +END; +/ + +SELECT note FROM scheduler_demo; +SELECT job_name, status FROM user_scheduler_job_run_details +WHERE job_name = 'DEMO_ONCE' ORDER BY log_id; +---- + +The table contains a `manual` row and the run is logged with status `s`. + +=== Run a Job on a Background Schedule + +Make sure `shared_preload_libraries` includes `ivorysql_ora`. Enable background scheduling for the `postgres` database in `postgresql.conf` as shown below, then restart the instance. + +[source,ini] +---- +ivorysql.scheduler = on +ivorysql.scheduler_databases = 'postgres' +---- + +Connect to a listed database and use the table from the previous example. Once the job is committed, the scheduler schedules a run every two seconds. Wait for a run before checking for successful entries. + +[source,sql] +---- +BEGIN + DBMS_SCHEDULER.CREATE_JOB( + job_name => 'demo_repeat', + job_type => 'PLSQL_BLOCK', + job_action => 'BEGIN INSERT INTO scheduler_demo VALUES (''background''); END;', + repeat_interval => 'FREQ=SECONDLY;INTERVAL=2', + enabled => TRUE); +END; +/ + +SELECT job_name, status FROM user_scheduler_job_run_details +WHERE job_name = 'DEMO_REPEAT' AND status = 's' ORDER BY log_id; +---- + +After checking the runs, use `CALL DBMS_SCHEDULER.DISABLE('demo_repeat');` to stop future runs. + +=== Schedule a Job with a PROGRAM and a SCHEDULE + +Use the background configuration and the `scheduler_demo` table from the preceding examples. The `PROGRAM` names the stored procedure and its input argument. The `SCHEDULE` specifies a two-second interval. Create a job that references both objects, set its argument value, and then enable it. + +[source,sql] +---- +CREATE OR REPLACE PROCEDURE scheduler_demo_write(p_note IN VARCHAR2) IS +BEGIN + INSERT INTO scheduler_demo VALUES (p_note); +END; +/ + +BEGIN + DBMS_SCHEDULER.CREATE_PROGRAM( + program_name => 'demo_program', + program_type => 'STORED_PROCEDURE', + program_action => 'scheduler_demo_write', + number_of_arguments => 1); + DBMS_SCHEDULER.DEFINE_PROGRAM_ARGUMENT( + program_name => 'demo_program', + argument_position => 1, + argument_name => 'p_note', + argument_type => 'VARCHAR2'); + DBMS_SCHEDULER.ENABLE('demo_program'); + + DBMS_SCHEDULER.CREATE_SCHEDULE( + schedule_name => 'demo_schedule', + repeat_interval => 'FREQ=SECONDLY;INTERVAL=2'); + DBMS_SCHEDULER.CREATE_JOB( + job_name => 'demo_named', + program_name => 'demo_program', + schedule_name => 'demo_schedule'); + DBMS_SCHEDULER.SET_JOB_ARGUMENT_VALUE('demo_named', 1, 'named schedule'); + DBMS_SCHEDULER.ENABLE('demo_named'); +END; +/ +---- + +After the job runs, these queries return `named schedule` and a run record with status `s`. + +[source,sql] +---- +SELECT DISTINCT note FROM scheduler_demo WHERE note = 'named schedule'; +SELECT job_name, status FROM user_scheduler_job_run_details +WHERE job_name = 'DEMO_NAMED' AND status = 's' ORDER BY log_id; +---- + +After checking the runs, use `CALL DBMS_SCHEDULER.DISABLE('demo_named');` to stop future runs. Once any active run finishes, use `DROP_JOB` to remove the example jobs. Remove the program and schedule with `DROP_PROGRAM` and `DROP_SCHEDULE`, then drop the stored procedure and example table. diff --git a/EN/modules/ROOT/pages/master/oracle_compatibility/compat_lengthc_function.adoc b/EN/modules/ROOT/pages/master/oracle_compatibility/compat_lengthc_function.adoc new file mode 100644 index 00000000..5f20757f --- /dev/null +++ b/EN/modules/ROOT/pages/master/oracle_compatibility/compat_lengthc_function.adoc @@ -0,0 +1,96 @@ +:sectnums: +:sectnumlevels: 5 + += LENGTHC Function + +== Purpose + +`LENGTHC` is an Oracle string-length function that counts Unicode complete characters. In a `UTF8` database, IvorySQL counts code points after NFC normalization, so a precomposed character and its canonically equivalent decomposed form have the same length. + +== Functionality + +Use `LENGTHC` to compare text lengths after normalization. An accented letter, for example, can be represented by one code point or by a letter followed by a combining accent. + +The `ivorysql_ora` extension provides `LENGTHC`. The examples connect to a `UTF8` database through the Oracle compatibility port, which defaults to 1521. + +=== Interface + +`LENGTHC(value)` returns an `integer`. You can also call it as `sys.lengthc(value)`. + +The argument can be a SQL expression such as a literal, table column, function result, or scalar subquery. Its type must match a supported overload directly or through an available type conversion. + +A character input of `NULL` returns `NULL`. An empty string returns `NULL` with the default `ivorysql.enable_emptystring_to_NULL = on`, or zero with `off`. Trailing padding spaces in `CHAR` values count toward the length. + +=== Counting Units in Oracle Length Functions + +[cols="1,3", options="header"] +|=== +|Function |Unit + +|`LENGTH` |Characters in the input character set +|`LENGTHB` |Bytes +|`LENGTHC` |Unicode complete characters +|`LENGTH2` |UCS-2 code units +|`LENGTH4` |UCS-4 code units +|=== + +IvorySQL counts code points after NFC normalization in `UTF8` databases. In other database encodings, `LENGTHC` remains available and counts characters directly in that encoding. + +=== Oracle Compatibility Scope + +IvorySQL accepts character inputs such as `CHAR`, `NCHAR`, `VARCHAR2`, and `text`. Oracle also lists `NVARCHAR2`, a type name that IvorySQL currently does not recognize. Direct `CLOB`, `NCLOB`, and `BLOB` inputs raise a type error, including `NULL` of those types. https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/LENGTH.html[Oracle LENGTH Function Reference] + +Numeric and datetime values and binary inputs such as `RAW` and `bytea` are converted to text before counting. Datetime results depend on the session format. For binary inputs, the default hexadecimal format includes the `\x` prefix in the count. + +== Examples + +=== Compare Character, Byte, and Normalized Lengths + +[source,sql] +---- +SELECT sample_name, + pg_catalog.encode(pg_catalog.convert_to(sample_text, 'UTF8'), 'hex') AS utf8_hex, + LENGTH(sample_text) AS char_count, + LENGTHB(sample_text) AS byte_count, + LENGTHC(sample_text) AS normalized_count +FROM (VALUES (1, 'precomposed', CHR(233)), + (2, 'decomposed', 'e' || CHR(769)), + (3, 'q_with_accent', 'q' || CHR(769))) samples(sample_no, sample_name, sample_text) +ORDER BY sample_no; +---- + +[listing] +---- + sample_name | utf8_hex | char_count | byte_count | normalized_count +---------------+----------+------------+------------+------------------ + precomposed | c3a9 | 1 | 2 | 1 + decomposed | 65cc81 | 2 | 3 | 1 + q_with_accent | 71cc81 | 2 | 3 | 2 +(3 rows) +---- + +Precomposed `é` uses one code point, `U+00E9`. The decomposed form uses `e` (`U+0065`) and a combining acute accent (`U+0301`). NFC normalizes both forms to the same code point. https://www.unicode.org/reports/tr15/[Unicode Normalization Forms] + +[NOTE] +==== +NFC applies the composition rules defined by Unicode. A `q` with a combining acute accent remains two code points after normalization, even when it looks like one character. +==== + +=== Count a Fixed-Length Character Value + +[source,sql] +---- +SELECT LENGTHC(CAST('ab' AS CHAR(5 CHAR))) AS fixed_length, + LENGTHC(CAST('ab' AS VARCHAR2(5 CHAR))) AS variable_length +FROM dual; +---- + +[listing] +---- + fixed_length | variable_length +--------------+----------------- + 5 | 2 +(1 row) +---- + +`fixed_length` is 5, including three padding spaces. `variable_length` is 2. diff --git a/EN/modules/ROOT/pages/master/oracle_compatibility/compat_utl_raw.adoc b/EN/modules/ROOT/pages/master/oracle_compatibility/compat_utl_raw.adoc new file mode 100644 index 00000000..f7a0715b --- /dev/null +++ b/EN/modules/ROOT/pages/master/oracle_compatibility/compat_utl_raw.adoc @@ -0,0 +1,66 @@ +:sectnums: +:sectnumlevels: 5 + += UTL_RAW Package + +== Purpose + +`UTL_RAW.CAST_TO_RAW` converts `VARCHAR2` text to `RAW`, preserving the text bytes in the current database encoding. + +== Functionality + +Use `CAST_TO_RAW` to store text bytes in a `RAW` column or pass them to a function that takes a `RAW` argument. + +The `ivorysql_ora` extension provides `UTL_RAW`. The examples use IvorySQL's `psql` on the Oracle compatibility port, which defaults to 1521 and selects Oracle compatibility mode for the session. + +=== Interface + +[source,sql] +---- +FUNCTION CAST_TO_RAW(c IN VARCHAR2) RETURN RAW; +---- + +A `NULL` input returns `NULL`. The `ivorysql.enable_emptystring_to_NULL` setting controls empty strings. With the default `on`, an empty string returns `NULL`. With `off`, it returns a zero-byte `RAW` value. + +=== Oracle Compatibility Scope + +==== Functions + +IvorySQL currently implements only the `CAST_TO_RAW` function from Oracle's `UTL_RAW` package. Oracle also provides functions such as `CAST_TO_VARCHAR2`, `CONVERT`, `BIT_AND`, and `CONCAT`. https://docs.oracle.com/en/database/oracle/oracle-database/19/arpls/UTL_RAW.html[Oracle UTL_RAW Reference] + +==== Constants + +Oracle's binary numeric conversions use these constants to specify the byte order for multibyte values. + +- `BIG_ENDIAN` (1) puts the most significant byte first. +- `LITTLE_ENDIAN` (2) puts the least significant byte first. +- `MACHINE_ENDIAN` (3) uses the database server's native byte order. + +IvorySQL retains these constants. `CAST_TO_RAW` returns the text bytes in their original order. + +[NOTE] +==== +PL/iSQL can reference these constants. Referencing them directly in a SQL `SELECT` raises an invalid identifier error. +==== + +== Examples + +=== Convert ASCII Text + +[source,sql] +---- +SELECT UTL_RAW.CAST_TO_RAW('ABC') AS raw_value, + RAWTOHEX(UTL_RAW.CAST_TO_RAW('ABC')) AS hex_value; +---- + +With the default hexadecimal display format, `raw_value` appears as `\x414243`. The xref:master/oracle_builtin_functions/rawtohex.adoc[RAWTOHEX] function returns the hexadecimal text `414243` in `hex_value`. + +=== Convert Multibyte Text + +[source,sql] +---- +SELECT pg_catalog.getdatabaseencoding() AS db_encoding, + pg_catalog.encode(UTL_RAW.CAST_TO_RAW('你好'), 'hex') AS raw_hex; +---- + +In a `UTF8` database, `raw_hex` is `e4bda0e5a5bd`. Other database encodings return the bytes for that encoding.