DBMS_OUTPUT Implementation

1. 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.

2. Implementation

2.1. Call Path

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.

2.2. Buffer Structure

output_buffer is a static pointer in each backend. Each connection maintains its own state.

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.

2.3. Writing and Reading

  1. 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.

  2. 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.

  3. 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).

  4. 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.

2.4. Capacity and Errors

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.

2.5. 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.

2.6. 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 DBMS_OUTPUT Package for examples.

Paths are relative to contrib/ivorysql_ora/.

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.