Is there a way to communicate application context to a DB connection in non-Sybase DB servers (similar to set_appcontext in Sybase)?

ぐ巨炮叔叔 提交于 2019-12-05 16:33:31

Oracle has a couple of different ways of accomplishing this. First off, you have the DBMS_APPLICATION_INFO package. Although you can use this to set arbitrary context information, it is generally used for tracing an application. You would normally set the module to be the name of the application and the action to be a description of the particular business process. You can then reference this information from V$SESSION and monitor long-running operations via V$SESSION_LONGOPS.

Oracle also has the ability to create a database object called a context. This is a more flexible way to populate session-level context. You can create a new context and then create whatever attributes you'd like within that context. And all of your code can simply reference the context. For example

SQL> create context my_ctx
  2    using pkg_ctx;

Context created.

SQL> create package pkg_ctx
  2  as
  3    procedure set_context;
  4  end;
  5  /

Package created.

SQL> create or replace package body pkg_ctx
  2  as
  3    procedure set_context
  4    as
  5    begin
  6      dbms_session.set_context( 'MY_CTX', 'USERNAME', 'Justin Cave' );
  7    end;
  8  end;
  9  /

Package body created.

SQL> exec pkg_ctx.set_context;

PL/SQL procedure successfully completed.

SQL> select sys_context( 'MY_CTX', 'USERNAME' )
  2    from dual;

SYS_CONTEXT('MY_CTX','USERNAME')
-------------------------------------------------------------------------------
Justin Cave

For PostgreSQL you can create a custom variable class which is a configuration setting in postgresql.conf. Something like this:

custom_variable_classes = 'myvars'

(Setting this requires a server restart if I'm not mistaken)

Now from through SQL you can read and write this in the following way:

set myvars.some_flag = 'true';
select current_setting('myvars.some_flag');

Note that you can "dynamically" defined new "variables" that are all prefixed with myvars. The individual values do not need to be declard in postgresql.conf

Originally this was intended for add-on modules to allow the definition of custom configuration options so it it a slight abuse of the feature but it should work nevertheless.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!