Search This Blog

Tuesday, April 1, 2008

Insufficient Privileges in Stored Procedures

Hello All,
I came across an intersting problem.
There are two roles CONNECT and RESOURCE given to user xxx.
The problem is while creating a view dynamically through named procedures,i get insufficient privileges error
ex:create or replace procedure stg_proc as
begin
execute immediate 'create or replace view stg_view as select * from stg_dummy';
end;
SQL> /
Procedure created.
SQL> exec stg_proc;
BEGIN stg_proc; END;
ERROR at line 1:
ORA-01031: insufficient privileges
ORA-06512: at "STB_STAGING.STG_PROC", line 3
ORA-06512: at line 1
but the strange thing was, there was no error with anonymous procedure block while creatng the view dynamically
ex:begin
execute immediate 'create or replace view stg_view as select * from stg_dummy';
end;
SQL> /
PL/SQL procedure successfully completed.
The reason why this happens is
PL/SQL Blocks and Roles
The use of roles in a PL/SQL block depends on whether it is an anonymous block or a named block (stored procedure, function, or trigger), and whether it executes with definer's rights or invoker's rights.
Named Blocks with Definer's Rights
All roles are disabled in any named PL/SQL block (stored procedure, function, or trigger) that executes with definer's rights. Roles are not used for privilege checking and you cannot set roles within a definer's rights procedure.
The SESSION_ROLES view shows all roles that are currently enabled. If a named PL/SQL block that executes with definer's rights queries SESSION_ROLES, the query does not return any rows.
Anonymous Blocks with Invoker's Rights
Named PL/SQL blocks that execute with invoker's rights and anonymous PL/SQL blocks are executed based on privileges granted through enabled roles. Current roles are used for privilege checking within an invoker's rights PL/SQL block, and you can use dynamic SQL to set a role in the session.
There are 2 solutions to the above problem
1)AUTHID as CURRENT_USER
2)Grant CREATE VIEW permission to xxx.
ex:create or replace procedure stg_proc AUTHID CURRENT_USER as
begin
execute immediate 'create or replace view stg_view as select * from stg_dummy';
end;
Procedure created.
SQL> exec stg_proc;
PL/SQL procedure successfully completed.
For further information can be found at http://stanford.edu/dept/itss/docs/oracle/10g/network.101/b10773/authoriz.htm#1007305
Hope it helps....