SYS_CONTEXT

Updated at:

SYS_CONTEXT retrieves session information—such as the current user, client IP address, and application module—from within SQL queries, triggers, and stored procedures. It provides an Oracle-compatible interface for implementing session-aware auditing, security policies, and application tracking in PolarDB for PostgreSQL (Compatible with Oracle).

Prerequisites

This feature requires a PolarDB for PostgreSQL (Compatible with Oracle) cluster running minor engine version 2.0.14.18.37.0 or later.

Check your minor engine version in the console or by running:

SHOW polardb_version;

If your cluster does not meet the version requirement, upgrade the minor engine version.

Syntax

SYS_CONTEXT(namespace VARCHAR2, attribute VARCHAR2) RETURN VARCHAR2

Parameters

ParameterDescription
namespaceThe namespace to query. Only 'USERENV' is supported.
attributeThe name of the attribute to retrieve. Attribute names are not case-sensitive.

Return value

The attribute value as VARCHAR2.

Quick start

The following query retrieves the database name, session user, client IP address, and application module for the current session:

SELECT
  SYS_CONTEXT('USERENV', 'DB_NAME')      AS db_name,
  SYS_CONTEXT('USERENV', 'SESSION_USER') AS session_user,
  SYS_CONTEXT('USERENV', 'IP_ADDRESS')   AS client_ip,
  SYS_CONTEXT('USERENV', 'MODULE')       AS app_module;

Example output (actual values depend on your session):

 db_name | session_user |    client_ip    | app_module
---------+--------------+-----------------+------------
 testdb  | dev_user     | 172.xx.xx.xx/xx |

Use cases

Track application context

Use SYS_CONTEXT with the DBMS_APPLICATION_INFO package to set and query the application module and operation for the current session. This creates a complete tracking chain from the application layer to the database.

  1. Set the application context when your backend connects to the database:

    -- Mark this session as the order-processing service
    CALL DBMS_APPLICATION_INFO.SET_MODULE('OrderProcessing', 'CreateNewOrder');
  2. Query the context from anywhere in the database—including triggers and logging functions:

    SELECT
      SYS_CONTEXT('USERENV', 'MODULE') AS current_module,
      SYS_CONTEXT('USERENV', 'ACTION') AS current_action;

    Expected output:

     current_module  | current_action
    -----------------+----------------
     OrderProcessing | CreateNewOrder

Audit changes with a trigger

SYS_CONTEXT captures the operator's environment directly inside a trigger, with no extra parameters needed from the application layer.

The following example automatically records the operating system user, client IP address, and session ID when a row in the employees table is updated.

  1. Create the employees table and insert a test row:

    CREATE TABLE employees (
        employee_id INT PRIMARY KEY,
        name        TEXT,
        salary      NUMERIC
    );
    INSERT INTO employees VALUES (101, 'test_user', 50000);
  2. Create the audit_log table to store audit records:

    CREATE TABLE audit_log (
        log_id      SERIAL PRIMARY KEY,
        table_name  TEXT        NOT NULL,
        os_user     TEXT,
        client_ip   TEXT,
        session_id  TEXT,
        change_time TIMESTAMPTZ DEFAULT NOW()
    );
  3. Create the trigger function. It reads OS_USER, IP_ADDRESS, and SESSIONID from USERENV and writes them to audit_log:

    CREATE OR REPLACE FUNCTION fn_audit_employees_update()
    RETURNS TRIGGER AS $$
    BEGIN
        INSERT INTO audit_log (table_name, os_user, client_ip, session_id)
        VALUES (
            TG_TABLE_NAME,
            SYS_CONTEXT('USERENV', 'OS_USER'),
            SYS_CONTEXT('USERENV', 'IP_ADDRESS'),
            SYS_CONTEXT('USERENV', 'SESSIONID')
        );
        RETURN NEW;
    END;
    $$ LANGUAGE plpgsql;
  4. Attach the trigger to the employees table:

    CREATE TRIGGER trg_audit_employees_update
    AFTER UPDATE ON employees
    FOR EACH ROW
    EXECUTE FUNCTION fn_audit_employees_update();
  5. Verify the audit is working. Run an update, then query audit_log:

    -- Simulate a salary update
    UPDATE employees SET salary = salary * 1.1 WHERE employee_id = 101;
    
    SELECT * FROM audit_log;

    Expected output:

     log_id | table_name | os_user  |    client_ip        | session_id |          change_time
    --------+------------+----------+---------------------+------------+--------------------------------
          1 | employees  | postgres | 172.xxx.xxx.xxx/xxx | 30         | 2025-10-17 07:41:50.666905 +00

Attribute reference

All attributes are in the USERENV namespace. Attribute names are not case-sensitive.

User and session information

AttributeDescriptionExample return value
CURRENT_USERThe current effective user.dev_user
SESSION_USERThe initial user of the session. This is the username used for authentication when the client first connects. It remains unchanged throughout the session.dev_user
CURRENT_USERIDThe numeric ID of the current effective user.16384
SESSION_USERIDThe numeric ID of the session user.16384
OS_USERThe operating system username of the connected client.postgres
ISDBAWhether the current user is a superuser.TRUE

Session identification

AttributeDescriptionExample return value
SESSIONIDThe session identifier. Returns the process ID (PID) of the database backend. SID is an alias for this attribute.30
SIDAlias for SESSIONID.30
CLIENT_IDENTIFIERThe client identifier, set by the application.myapp-worker-1
CLIENT_INFOAdditional client information, set by the application.batch-job

Database and schema information

AttributeDescriptionExample return value
DB_NAMEThe name of the connected database.testdb
DB_UNIQUE_NAMEThe unique name of the database.testdb
CURRENT_SCHEMAThe current default schema.public
SESSION_SCHEMAThe session schema name.public
INSTANCEThe instance number.1
INSTANCE_NAMEThe instance name.primary

Network and connection information

AttributeDescriptionExample return value
IP_ADDRESSThe IP address of the client.172.16.0.1/32
SERVER_HOSTThe host address of the database server.db-host.internal
HOSTThe hostname of the client.client-host
TERMINALThe terminal identifier of the client.pts/0

Application information

AttributeDescriptionExample return value
MODULEThe application module name, set via DBMS_APPLICATION_INFO.SET_MODULE.OrderProcessing
ACTIONThe current operation name, set via DBMS_APPLICATION_INFO.SET_MODULE.CreateNewOrder
DATABASE_ROLEThe database role.PRIMARY

Language and localization information

AttributeDescriptionExample return value
LANGThe current encoding.en
LANGUAGEThe complete language and locale settings.AMERICAN_AMERICA.AL32UTF8
NLS_DATE_FORMATThe date display format for the current session.DD-MON-RR

Version information

AttributeDescriptionExample return value
SESSION_EDITION_IDThe session edition ID.0
CURRENT_EDITION_IDThe current edition ID.0

What's next