Application Context是内存中的一组name-value对,application context从属于某个命名空间(namespace)。
用户只能通过一个自定义procedure调用dbms_session.set_context来设置application context的值。用户使用sys_context(
Application context分为三种
Global application context存储在SGA中,只要SGA不消亡,global application context就一直存在。global application context常常用于跨会话,与会话无关的场景。dbms_session.set_context有两个默认值为NULL的参数:
username = null , client_id=null。所有用户都能访问。
username = null, client_id=
username =
username =
username =
例子1: 所有用户都能访问的application context
CREATE OR REPLACE CONTEXT global_hr_ctx USING hr_ctx_pkg ACCESSED GLOBALLY;
CREATE OR REPLACE PACKAGE hr_ctx_pkg
AS
PROCEDURE set_hr_ctx(sec_level IN VARCHAR2);
PROCEDURE clear_hr_context;
END;
/
CREATE OR REPLACE PACKAGE BODY hr_ctx_pkg
AS
PROCEDURE set_hr_ctx(sec_level IN VARCHAR2)
AS
BEGIN
DBMS_SESSION.SET_CONTEXT(
namespace => 'global_hr_ctx',
attribute => 'job_role',
value => sec_level);
END set_hr_ctx;
PROCEDURE clear_hr_context
AS
BEGIN
DBMS_SESSION.CLEAR_CONTEXT('global_hr_ctx', 'job_role');
END clear_context;
END;
/
例子2: 跨session/application,但是使用同一个数据库schema的application context。
CREATE OR REPLACE PACKAGE hr_ctx_pkg
AS
PROCEDURE set_hr_ctx(sec_level IN VARCHAR2, user_name IN VARCHAR2);
PROCEDURE clear_hr_context;
END;
/
CREATE OR REPLACE PACKAGE BODY hr_ctx_pkg
AS
PROCEDURE set_hr_ctx(sec_level IN VARCHAR2, user_name IN VARCHAR2)
AS
BEGIN
DBMS_SESSION.SET_CONTEXT(
namespace => 'global_hr_ctx',
attribute => 'job_role',
value => sec_level,
username => user_name);
END set_hr_ctx;
PROCEDURE clear_hr_context
AS
BEGIN
DBMS_SESSION.CLEAR_CONTEXT('global_hr_ctx');
END clear_context;
END;
/
两个例子都提供了clear_hr_context 存储过程。这是因为global application context常驻SGA,需要用户使用完毕就清理,以免信息泄露。
USERENV
USERENV是Oracle预定义的命名空间。它包含了许多常用的application context。