oracle-databaseplsqldbms-metadata

Why ths works in anonymous but not in a procedure?


If I do the following, everything is fine:

declare
  l_foo clob;
begin
select
regexp_replace(
  dbms_metadata.get_ddl('USER', 'SCOTT', null) ||
  dbms_metadata.GET_GRANTED_DDL ('SYSTEM_GRANT', 'SCOTT') ||
  dbms_metadata.GET_GRANTED_DDL ('OBJECT_GRANT', 'SCOTT') ||
  dbms_metadata.GET_GRANTED_DDL ('ROLE_GRANT', 'SCOTT')
,'"' || chr(10), '";' || chr(10)) 
into l_foo 
from dual;
end;
/

But if I wrap this in a procedure:

create procedure tests is
  l_foo clob;
begin
select
regexp_replace(
  dbms_metadata.get_ddl('USER', 'SCOTT', null) ||
  dbms_metadata.GET_GRANTED_DDL ('SYSTEM_GRANT', 'SCOTT') ||
  dbms_metadata.GET_GRANTED_DDL ('OBJECT_GRANT', 'SCOTT') ||
  dbms_metadata.GET_GRANTED_DDL ('ROLE_GRANT', 'SCOTT')
,'"' || chr(10), '";' || chr(10)) 
into l_foo 
from dual;
end;
/

And execute the procedure by "exec tests;" then I catch a object SCOTT of type USER not found in schema SCOTT.

Why is this and how do I get around?

Thanks Chris


Solution

  • Oracle Documentation states:

    In stored procedures, functions, and definers-rights packages, roles (such as SELECT_CATALOG_ROLE) are disabled. Therefore, such a PL/SQL program can only fetch metadata for objects in its own schema. If you want to write a PL/SQL program that fetches metadata for objects in a different schema (based on the invoker's possession of SELECT_CATALOG_ROLE), you must make the program invokers-rights.

    To do this, you must add authid to your procedure.

    create procedure tests authid CURRENT_USER is
      l_foo clob;
    begin
    select
    regexp_replace(
      dbms_metadata.get_ddl('USER', 'SCOTT', null) ||
      dbms_metadata.GET_GRANTED_DDL ('SYSTEM_GRANT', 'SCOTT') ||
      dbms_metadata.GET_GRANTED_DDL ('OBJECT_GRANT', 'SCOTT') ||
      dbms_metadata.GET_GRANTED_DDL ('ROLE_GRANT', 'SCOTT')
    ,'"' || chr(10), '";' || chr(10)) 
    into l_foo 
    from dual;
    end;
    /
    
    SQL> EXEC tests 
    
    PL/SQL procedure successfully completed