UTL_RAW Package

1. Purpose

UTL_RAW.CAST_TO_RAW converts VARCHAR2 text to RAW, preserving the text bytes in the current database encoding.

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

2.1. Interface

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.

2.2. Oracle Compatibility Scope

2.2.1. 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. Oracle UTL_RAW Reference

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

PL/iSQL can reference these constants. Referencing them directly in a SQL SELECT raises an invalid identifier error.

3. Examples

3.1. Convert ASCII Text

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 RAWTOHEX function returns the hexadecimal text 414243 in hex_value.

3.2. Convert Multibyte Text

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.