Unable to create table from within package - sql

I am attempting to create a package in which I drop and create a table using a CTAS query. This table needs to be refreshed frequently and columns are add/removed all the time from the underlying data. Since the structure of the table is constantly changing, it would be quite cumbersome to update merge/update queries each refresh to account for the new/missing columns. Currently, I have external scripts that do simple drops and creates but I need to centralize this in the database; therefore I am attempting to create a package to do it; however, I am having trouble with privileges.
As proof of concept, the following code works when ran as an anonymous block:
create table my_test_table as select * from dual; --create test table
declare
v_count int;
begin
select count(*) into v_count from all_tab_columns where table_name = upper('my_test_table');
if v_count >= 1 then
execute immediate 'drop table my_test_table';
end if;
execute immediate q'[
create table my_test_table as
select * from dual
]';
end;
select * from my_test_table; -- shows expected results
But when creating a package to do the same thing;
CREATE OR REPLACE PACKAGE test_pkg AS
PROCEDURE test_procedure;
END test_pkg;
CREATE OR REPLACE package body test_pkg as
procedure test_procedure
is
v_count int;
begin
select count(*) into v_count from all_tab_columns where table_name = upper('my_test_table');
if v_count >= 1 then
execute immediate 'drop table my_test_table';
end if;
execute immediate q'[
create table my_test_table as
select * from dual
]';
end test_procedure;
end test_pkg;
/
and testing with the following code:
create table my_test_table as select * from dual; --make sure table exists
execute TEST_PKG.TEST_PROCEDURE; --results in errors
select * from my_test_table; --table does not exist; therefore, DROP statement works but not CREATE
I get the following errors (in regards to executing TEST_PKG.TEST_PROCEDURE):
ORA-01031: insufficient privileges
ORA-06512: at test_pkg, line 15
When testing for the existence of the test table after executing the package, I can see that it no longer exists. This means the DROP statement is working but the CREATE TABLE statement is resulting in the insufficient privileges error.
Any and all insight into what privileges I need to create the table from within the package would be immensely helpful.

Create a table in procedure is only alowed when you have "Create table" or "create any table" privilege but granted directly to user (granted by role is not working).
https://docs.oracle.com/cd/B19306_01/network.102/b14266/authoriz.htm#i1008334
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.
To check system privileges granted directly to your user (not by role/roles), you can run this query from your user:
SELECT * FROM USER_SYS_PRIVS;

The package you've created, in the absence of a AUTHID CURRENT_USER clause is a definer's rights package. It can only do things that are allowed by privileges granted directly to the definer of the package. "Directly" is the key point here -- privileges granted through enabled roles are not honored during the package execution.
You've probably got the RESOURCE or similar role enabled for your user, which would explain why you can create the table during testing but not via your package procedure.
Try granting the CREATE TABLE and UNLIMITED TABLESPACE system privileges directly to your user and then recreate the package. (If that works, replace UNLIMITED TABLESPACE with quotas on the appropriate tablespace(s) in your database).

Related

Oracle Trigger with INSERT INTO table

I am trying to create an Oracle Trigger with After Update statement. It appears that I cannot create the trigger because I get prompted with Table does not exist error:
CREATE OR REPLACE TRIGGER USR1.CORE_FINISHED
AFTER UPDATE OF RUNTIME_STATUS
ON USR2.runtime_btc
FOR EACH ROW
WHEN ( new.RUNTIME_STATUS = 'FINISHED'
AND new.id = 'cr_daily')
BEGIN
INSERT INTO USR1.test_dq_log (BTC_NO, TBL_NAM, SCR_NAM)
SELECT BTC_NO, TBL_NAM, SCR_NAM
FROM USR2.EVENT_LG -- This is where the script is throwing errors
WHERE BTC_NO = :NEW.BTC_NO;
END;
What is weird is that the same expression when run outside of the trigger:
INSERT INTO USR1.test_dq_log (BTC_NO, TBL_NAM, SCR_NAM)
SELECT BTC_NO, TBL_NAM, SCR_NAM
FROM USR2.EVENT_LG
WHERE BTC_NO = 'any number here'
Seems to work smoothly and it inserts rows in the table!
It looks as if you were granted privileges to insert into that table via role. Were you?
If so, it works at SQL level or anonymous PL/SQL blocks, but won't work in named PL/SQL procedures (e.g. stored procedures, functions, triggers) - you'll have to acquire that grant directly (not via role).

Why does my query return no records inside a program (PL/SQL), but does when ran manually in SQL?

Hi everyone and thank you for taking the time to help me.
I have the following query:
SELECT owner, object_name
FROM all_objects
WHERE owner IN ('EDI')
ORDER BY object_type, object_name;
As you can see in the screenshot it returns some values.
When I call the query from inside a program, it is not returning any values (see second screenshot).
Test code to illustrate this is:
CREATE OR REPLACE PROCEDURE my_test
AS
BEGIN
DBMS_OUTPUT.put_line('Pre-Loop');
FOR indx IN (SELECT owner, object_name
FROM all_objects
WHERE owner IN ('EDI')
ORDER BY object_type, object_name)
LOOP
DBMS_OUTPUT.put_line('Object: ' || indx.owner || '.' || indx.object_name);
END LOOP;
DBMS_OUTPUT.put_line('Post-Loop');
END;
/
BEGIN
my_test();
END;
/
The EDI schema is brand new, so I suspect this is a grants/privileges issue, but I can't seem to find what I may be missing in order for this to work. I have tried running this as both the EDI user and SYS.
EDIT after getting an answer:
I mentioned in a comment about finding an alternative to the official answer to this question and wanted to make sure it was shared for anyone reading this later so they can weigh the decision the same.
Applying grants like EXECUTE ANY PROCEDURE or SELECT ANY TABLE to the user that is expected to run the code will work, but I am sure there are reasons not to give such wide open grants.
Your stored procedure is a definer's rights stored procedure. That means that it doesn't have access to privileges that are granted via roles only those privileges that are granted directly to the owner of the procedure. Ad hoc SQL, on the other hand, runs with the privileges of whatever roles are enabled for the current session in addition to the user's direct grants. Most likely, the owner of the procedure has access to the tables in question via roles rather than via direct grants.
You can test this by running
set role none;
and then running the ad hoc SQL statement. If my wager is right, the ad hoc SQL will now return 0 rows since you've disabled all the roles for the session.
Depending on what you are going to do with the procedure, you may be able to solve the problem by turning it into an invoker's rights stored procedure.
CREATE OR REPLACE PROCEDURE my_test
AUTHID CURRENT_USER
AS
That will cause the procedure to run with the privileges of the invoker's session (including privileges granted through roles) rather than those of the definer. Assuming that all the users you want to call the procedure will have access to the EDI tables, that should be sufficient.
This is what you have now - no result at all:
SQL> CREATE OR REPLACE PROCEDURE my_test
2 AS
3 BEGIN
4 DBMS_OUTPUT.put_line('Pre-Loop');
5
6 FOR indx IN (SELECT owner, object_name
7 FROM all_objects
8 WHERE owner IN ('SCOTT')
9 AND rownum < 5 -- you don't have that
10 ORDER BY object_type, object_name)
11 LOOP
12 DBMS_OUTPUT.put_line('Object: ' || indx.owner || '.' || indx.object_name);
13 END LOOP;
14
15 DBMS_OUTPUT.put_line('Post-Loop');
16 END;
17 /
Procedure created.
SQL> BEGIN
2 my_test();
3 END;
4 /
PL/SQL procedure successfully completed.
But, if you enable serveroutput, here it is!
SQL> set serveroutput on --> this!
SQL>
SQL> BEGIN
2 my_test();
3 END;
4 /
Pre-Loop
Object: SCOTT.BONUS
Object: SCOTT.DEPT
Object: SCOTT.EMP
Object: SCOTT.SALGRADE
Post-Loop
PL/SQL procedure successfully completed.
SQL>

How to grant stored procedure creation permission to an user in PostgreSQL

I need to grant permission to a specific user to create stored procedures in PostgreSQL without writing permissions to other tables. The stored procedure should read and write only in one table.
I've already setup the read permission to that table, but I'm struggling with the writting permissions.
GRANT CONNECT ON DATABASE production_database TO user;
GRANT USAGE ON SCHEMA public TO user;
GRANT SELECT ON table TO user;
If you want to write a procedure in PL/PGSQL you need to use PostgreSQL 11 or 12.
In PostgreSQL there is no explicit privilege to create a procedure or a function.
However you can try:
to create a specific schema just for the procedure
to grant USAGE to this schema only to the specific user
to create the procedure with SECURITY DEFINER as the table owner
Example:
create user myuser password 'myuser';
--
create table public.t(x int);
--
create schema myschema;
--
create or replace procedure myschema.myproc(param int)
language plpgsql
as
$$
declare
v int;
begin
insert into public.t values(param);
end;
$$
security definer
set search_path='';
--
grant usage on schema myschema to myuser;
Here the table owner is superuser postgres and the table schema is public:
With this script:
\c postgres myuser
select * from t;
call myschema.myproc(1);
\c postgres postgres
select * from t;
I get:
You are now connected to database "postgres" as user "myuser".
select * from t;
psql:cp.sql:25: ERROR: permission denied for table t
call myschema.myproc(1);
CALL
You are now connected to database "postgres" as user "postgres".
select * from t;
x
---
1
(1 row)

ORACLE11g, table or view does not exist while creating procedure

There're two schema in db, I create a materialized view -- 'MV1' and grant it successfully,selecting from it in other schema is ok.
GRANT select ON schemaA.MV_CA_REVENU_MS_GEO TO read;
/
GRANT select ON schemaA.MV_CA_REVENU_MS_GEO TO write;
/
GRANT update ON schemaA.MV_CA_REVENU_MS_GEO TO write;
/
But while compiling the procedure, there's error message says 'table or view does not exist' for 'MV1'. The procedure code is:
create or replace
PROCEDURE SP_NAME (args ... ) is
.
.
begin
INSERT INTO tableName(
.
.
) SELECT ...
FROM (SELECT ...
FROM MV1 -- **schemaA.MV1 doesn't work either**
WHERE
end SP_NAME;
/
GRANT EXECUTE ON schemaB.SP_NAME TO read;
GRANT DEBUG ON schemaB.SP_NAME TO read;
GRANT EXECUTE ON schemaB.SP_NAME TO write;
GRANT DEBUG ON schemaB.SP_NAME TO write;
/
CREATE or replace PUBLIC SYNONYM SP_NAME FOR schemaB.SP_NAME;
/
I try to add schemaA in front of MV1, it doesn't work. Is there any other step should I take a check?
Are "read" and "write" schema names or role names? Permissions in Oracle granted indirectly via roles are not available when compiling stored procedures, functions, and packages

Oracle select privilege on DBA_ROLES

I am connected into Oracle 10g database with user "user", when i run a select on DBA_ROLES it displays the result without any problem, but when the select is inside a procedure it returns the error ORA-00942: table or view does not exist
is the user missing some privileges? why is it possible to execute a SELECT but not to include it inside a procedure?
SQL> SELECT COUNT(*) FROM DBA_ROLES;
COUNT(*)
----------
18
SQL> CREATE OR REPLACE PROCEDURE tst_role IS
v VARCHAR2(100);
BEGIN
v := '';
FOR rec IN (SELECT ROLE FROM DBA_ROLES) LOOP
v := rec.role;
DBMS_OUTPUT.put_line(v);
END LOOP;
END;
/
Warning: Procedure created with compilation errors.
SQL> show errors
Errors for PROCEDURE TST_ROLE:
LINE/COL ERROR
-------- -----------------------------------------------------------------
5/13 PL/SQL: SQL Statement ignored
5/30 PL/SQL: ORA-00942: table or view does not exist
6/3 PL/SQL: Statement ignored
6/8 PLS-00364: loop index variable 'REC' use is invalid
within a definer's rights stored procedure, you don't have access to privileges that are granted via a role. This most likely means that whatever Oracle user you are using has been granted access to DBA_ROLES via a role rather than via a direct grant. Most likely, you can ask your DBA to grant your account the SELECT ANY DICTIONARY privilege
GRANT SELECT ANY DICTIONARY
TO your_oracle_user
You can verify that the problem is, indeed, that the privilege is granted via a role by disabling roles in your session and verifying that you get an error. If you
SQL> set role none;
SQL> SELECT COUNT(*) FROM DBA_ROLES;
I'll wager that you get the same ORA-00942 error.