Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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` 重载和读取后的空间复用。
Original file line number Diff line number Diff line change
@@ -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)
----
Original file line number Diff line number Diff line change
@@ -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.
Loading
Loading