How to write stored procedures using tables from another schema? - oracle

Is it necessary that table should be in HR user to call function and procedure of Oracle? When I run function from another user, it gives me a compilation error.
For my project,I want to run the function and procedure from another user. How can I implement it?

To write a function or procedure using a table in another schema the table owner needs to grant us the required privilege. For example:
SQL> conn hr/hr
SQL> grant select on employees to mousumi;
or ask a super user to do it for you:
SQL> conn dba_user/password
SQL> grant select on hr.employees to mousumi;
Privileges can be granted to roles but we cannot use those privileges to create procedures or views. For that purpose the privileges must be granted directly to us. Find out more.
When we reference that we need to include the schema name:
SQL> select * from hr.employees;
Alternatively we can create a synonym for it.
SQL> create synonym employee_table for hr.employees;
SQL> select * from employee_table;
The synonym is just a label: it can be anything we like providing it is unique within our schema (and conforms to Oracle naming conventions). Find out more.

Related

Oracle Privileges to Use Global Temporary Table via Definer's Rights Stored Procedure

Please assume:
User A creates global temporary table gtt.
User A creates stored procedure sp with definer's rights AUTHID DEFINER. For simplicity, assume this sp simply inserts a row into gtt and selects a value from the row in gtt.
User A grants user B execute on sp.
What additional grants, if any, need to be given to users A and B so that B can successfully execute sp?
I've heard that when a global temporary table is used (e.g. data inserted), that the user using the global temporary table needs create table privilege to create the instance of the globaly temporary table in their session's memory (even though the global temporary table itself was already created). Is that true? I assumed granting select and insert on the global temporary table would have been sufficient.
Because sp is defined by A does this mean A needs create any table, so the row of data can be inserted and selected from user B's session memory?
Sorry, I don't currently have access to an Oracle instance where I have enough privileges to try this myself.
Please note, I am not trying to create the global temporary table in the stored procedure.
Using Oracle 19c Enterprise Edition.
Thank you in advance for helping me understand the privileges involved here.
What additional grants, if any, need to be given to users A and B so that B can successfully execute sp?
None.
SQL> show user
USER is "SCOTT"
SQL> create global temporary table gtt (name varchar2(20));
Table created.
SQL> create or replace procedure sp
2 authid definer
3 as
4 begin
5 insert into gtt (name) values (user);
6 end;
7 /
Procedure created.
SQL> exec sp;
PL/SQL procedure successfully completed.
SQL> select * from gtt;
NAME
--------------------
SCOTT
SQL> grant execute on sp to mike;
Grant succeeded.
Everything works so far for the GTT and SP owner. Let's see the grantee.
SQL> connect mike/lion
Connected.
SQL> exec scott.sp;
PL/SQL procedure successfully completed.
SQL> select * From scott.gtt;
select * From scott.gtt
*
ERROR at line 1:
ORA-00942: table or view does not exist
Right; as I said, no other privileges are needed - stored procedure works (i.e. didn't fail), but - as scott didn't grant any additional privileges, mike can't check gtt table's contents.
Back to scott:
SQL> connect scott/tiger
Connected.
SQL> select * From scott.gtt;
no rows selected
SQL>
But of course; that's a global temporary table - scott sees only its own data (which is now lost).
[EDIT: to answer questions you posted as comments]
mike had create table privilege; now it doesn't:
SQL> connect sys as sysdba
Enter password:
Connected.
SQL> revoke create table from mike;
Revoke succeeded.
This piece of code is a copy/paste from above:
SQL> connect scott/tiger
Connected.
SQL> create global temporary table gtt (name varchar2(20));
Table created.
SQL> create or replace procedure sp
2 authid definer
3 as
4 begin
5 insert into gtt (name) values (user);
6 end;
7 /
Procedure created.
SQL> exec sp;
PL/SQL procedure successfully completed.
SQL> select * from gtt;
NAME
--------------------
SCOTT
SQL> grant execute on sp to mike;
Grant succeeded.
Additionally, scott now grants select on gtt to mike:
SQL> grant select on gtt to mike;
Grant succeeded.
What does mike see now?
SQL> connect mike/lion
Connected.
SQL> exec scott.sp;
PL/SQL procedure successfully completed.
SQL> select * from scott.gtt;
NAME
--------------------
MIKE
SQL>

Accessing synonym of DB link object

Background:
We have database FIN having schema as FIN_DEV.
We have another database APP having schema APP_DEV.
A DB link is created in APP_DEV pointing to FIN_DEV
CREATE DATABASE LINK FINDEV_FIN
CONNECT TO FIN_DEV
IDENTIFIED BY <PWD>
USING 'FIN'
We are able to access the objects in FIN_DEV from APP_DEV using
CREATE OR REPLACE SYNONYM TBL_FINA FOR TBL_FINA#FINDEV_FIN
All good until this point.
Here comes the question:
Another schema INT_DEV in APP database needs to access SYNONYM TBL_FINA from INT_DEV.
Could you please let me know the best way to accomplish this?
Here's how; I don't have your users (and don't feel like creating them), so:
my remote database = orcl (it is your fin database)
user in my remote database = my_remote_user (it is fin_dev in your database)
user in my local database = scott (app_dev in your database)
it'll create a database link and a synonym
another user in my local database = mike (int_dev in your database)
In a remote database, I'm creating a table to mimic your situation:
SQL> create table tbl_fina (id number);
Table created.
SQL> insert into tbl_fina values (1);
1 row created.
SQL> commit;
Commit complete.
SQL>
Connecting to local database, creating a database link & a synonym:
SQL> show user
USER is "SCOTT"
SQL> create database link findev_fin
2 connect to my_remote_user
3 identified by its_password
4 using 'orcl';
Database link created.
SQL> -- Testing, whether the DB link works
SQL> select * From dual#findev_fin;
D
-
X
SQL> -- Creating a snynonym
SQL> create synonym tbl_fina for tbl_fina#findev_fin;
Synonym created.
SQL> select * from tbl_fina;
ID
----------
1
SQL>
So far, so good - this is what you currently have.
Now, let's allow another user - in my local database - to access that synonym. Straightforward solution is to grant select on it, right?
SQL> grant select on tbl_fina to mike;
grant select on tbl_fina to mike
*
ERROR at line 1:
ORA-02021: DDL operations are not allowed on a remote database
SQL>
Whooops! That won't work. A workaround is to create a view (on the synonym) and grant select on that view to mike:
SQL> create view v_tbl_fina as select * from tbl_fina;
View created.
SQL> grant select on v_tbl_fina to mike;
Grant succeeded.
SQL>
That works. Finally, connect as another user and select from the view (i.e. a synonym):
SQL> connect mike/pwd
Connected.
SQL> select * from scott.v_tbl_fina;
ID
----------
1
SQL>
For easier access - to avoid naming view owner (scott) - mike can now create its own synonym:
SQL> create synonym tbl_fina for scott.v_tbl_fina;
Synonym created.
SQL> select * from tbl_fina;
ID
----------
1
SQL>
Certainly, another option is to create a database link in my mike user, but that's kind of dangerous as database link allows its owner to do virtually anything in the remote database, as it is now identified by the remote username and its password.

How could I prevent a user from querying SELECT on other schemas in Oracle?

I'm using Oracle 11g(11.2.0.1.0). I created about 20 tablespaces and users. And the data came by [Tools] - [Database Copy] on Oracle SQL Developer.
Somehow I found that a user is using SELECT query on the table from another schema. I want to prevent it for security. How should I change my grant options?
I read "Oracle Database Security Guide 11g Release 2(11.2)", but couldn't find the solution clearly.
Here are my creating and granting queries.
create user [USER_NAME]
identified by [PASSWORD]
default tablespace [TABLESPACE_NAME]
temporary tablespace TEMP;
grant create session,
create database link,
create materialized view,
create procedure,
create public synonym,
create role,
create sequence,
create synonym,
create table,
drop any table,
create trigger,
create type,
create view to [USER_NAME];
alter user [USER_NAME] quota unlimited on [TABLESPACE_NAME];
And here is the SELECT result of session_privs on a user.
SQL> SELECT * FROM session_privs;
PRIVILEGE
--------------------------------------------------------------------------------
CREATE SESSION
CREATE TABLE
DROP ANY TABLE
CREATE SYNONYM
CREATE PUBLIC SYNONYM
CREATE VIEW
CREATE SEQUENCE
CREATE DATABASE LINK
CREATE ROLE
CREATE PROCEDURE
CREATE TRIGGER
PRIVILEGE
--------------------------------------------------------------------------------
CREATE MATERIALIZED VIEW
CREATE TYPE
13 rows selected.
I want to prevent a user from querying SELECT on other schemas.
For example, the following query
-- connected with USER1
SELECT *
FROM USER2.table1;
should make an error like:
ERROR: USER1 doesn't have SELECT privilege on USER2.
Edited:
Use appropriate terms (changed some words from tablespace to schema)
Add SELECT result of session_privs on a user
Add the method of how the data came by.
It was my fault. I missed that I had added some roles.
To copy data using Oracle SQL Developer, I added predefined roles to users. The roles were exp_full_database and imp_full_database.
According to Oracle Database Security Guide: Configuring Privilege and Role Authorization, exp_full_database contains these privileges:
SELECT ANY TABLE
BACKUP ANY TABLE
EXECUTE ANY PROCEDURE
EXECUTE ANY TYPE
ADMINISTER RESOURCE MANAGER
INSERT, DELETE, UPDATE ON SYS.INCVID, SYS.INCFIL AND SYS.INCEXP
and roles:
EXECUTE_CATALOG_ROLE
SELECT_CATALOG_ROLE
Those roles are not required now. So the answer is removing them from users.
REVOKE exp_full_database, imp_full_databsae FROM USER1;
And I get the result I wanted.
-- connected with USER1
SELECT * FROM USER2.TABLE1;
ERROR at line 1:
ORA-01031: insufficient privileges

What are roles and privileges to give a user in order to perform CRUD(on Oracle 12)

I'm creating a USER on Oracle 12 c database, using TOAD.
After creating the TABLESPACE, I'm creating the USER. I'm a little confusing about the many ROLES and PRIVILEGES that can be given to a USER.
What are the minimum/standard roles and privileges a user must be given in order to perform CRUD operation and being able to 'edit' the database (create or delete table, DROP the schema ecc) from TOAD?
Thank you
It depends on what operations are you going to perform. If you want to work only with tables in your own db schema, then the following privileges are usually enough to start:
grant create session to <your_user>;
grant create table to <your_user>;
You have the default rights to insert/update/delete/select tables which you own.
Tablespace quota:
alter user <your_user> quota unlimited on <your_tablespace_name>;
It's better to set the default tablespace for the user. In this case you can omit the tablespace name in a create table statement.
alter user <your_user> default tablespace <your_tablespace_name>;
A link to the documentation - Privileges
Grant the user the following privileges:
CREATE SESSION (in order to allow the user to connect to the database)
INSERT
UPDATE
DELETE
SELECT
Use the below command to grant privileges to the user (you need to login as SYS or SYSTEM or another user that has GRANT privilege):
GRANT CREATE SESSION, SELECT, UPDATE, DETETE, INSERT TO user_name
Here's a suggestion you might (or might not) want to follow.
As a privileged user (such as SYS), check tablespaces available in your database. I'm using 11g XE (Express Edition) which shows the following:
SQL> show user
USER is "SYS"
SQL> select tablespace_name from dba_tablespaces;
TABLESPACE_NAME
------------------------------
SYSTEM
SYSAUX
UNDOTBS1
TEMP --> temporary
USERS --> my data
Now, create a user:
SQL> create user mdp identified by pdm
2 default tablespace users
3 temporary tablespace temp
4 quota unlimited on users;
User created.
Quite a long time ago, there were two popular predefined roles named CONNECT and RESOURCE which were granted some of the most frequent privileges so people just loved to grant those roles to newly created users.
Nowadays, you shouldn't be doing that: grant only minimal set of privileges your user might need. The first one is CREATE SESSION; without it, your user won't even be able to establish a connection.
SQL> grant create session to mdp;
Grant succeeded.
Then, you'll want to create some tables so - grant it:
SQL> grant create table to mdp;
Grant succeeded.
OK, let's connect as newly created user and do something:
SQL> connect mdp/pdm#xe
Connected.
SQL> create table test (id number);
Table created.
SQL> insert into test id values (1);
1 row created.
SQL> drop table test;
Table dropped.
SQL>
Nice; I can create tables, insert/update/delete/select from them. For beginning, that's quite enough. However, when it turns out that you'd want to, for example, create a view, it won't work until you grant it that privilege:
SQL> create view v_dual as select * From dual;
create view v_dual as select * From dual
*
ERROR at line 1:
ORA-01031: insufficient privileges
SQL> connect sys#xe as sysdba
Enter password:
Connected.
SQL> grant create view to mdp;
Grant succeeded.
SQL> connect mdp/pdm#xe
Connected.
SQL> create view v_dual as select * From dual;
View created.
SQL>
And so forth; don't grant anything just because you might need it - grant it if & when you need it. Especially pay attention to system privileges which can potentially be dangerous if you don't know what you're doing.

Schema, User and functional Id in Oracle

I confused lot in oracle about schema, user and functional id. Let consider my two different cases
Case I :
Let us consider SCOTT#ORCL.If we think SCOTT is user. while creating user alone it ll create a schema. Correct me If i am wrong. In this case while we were creating SCOTT user alone SCOTT schema was created. Suppose If we create another schema say X . Is this possible to SCOTT user owns X schema ?
Case II :
Let us consider SCOTT#ORCL.If we think SCOTT is schema alone i-e which is created by schema command alone. If it is so then what is the use of schema w/o any user who is going to own it.
I heard oracle function ID is one which will connect several user/schema(i don't know whether I can put schema/user here ) in a data base. is there is difference b/w oracle functional ID with user/schema ?
Many people find this topic confusing, because we tend to bandy around USER and SCHEMA interchangeably, when they are in fact separate if related entities.
A schema is the collection of database objects owned by a user. When we create a user we create their schema at the same time. Initially their schema is empty.
It is easy to demonstrate that USER and SCHEMA are distinct, because we change the current schema in the session. This just means we can reference objects in another user's schema without prefixing them with the owner's name.
SQL> desc t1
Name Null? Type
----------------------------------------- -------- -------------
ID NUMBER
SQL> alter session set current_schema=APC
2 /
Session altered.
SQL> desc t1
ERROR:
ORA-04043: object t1 does not exist
SQL> sho user
USER is "X"
SQL>
In this case, either APC doesn't have a table called T1 or he hasn't granted it to X. The only way X can see her own table is to prefix it with her own name, or switch the current schema back to herself.
To answer your first question, the schema always has the same name as the user. So it is not possible for SCOTT to own schema X; schema X is owned by user X.
To answer your second question, it is impossible to create a schema without a user.
True, there is a CREATE SCHEMA command, but this requires the prior creation of the user. It is actually not creating a schema but creating several database objects. In effect it is more of a ADD OBJECTS TO SCHEMA command.
SQL> conn sys as sysdba
Enter password:
Connected.
SQL> create user x identified by x
2 default tablespace users quota 10m on users
3 /
User created.
SQL> grant create session, create table to x
2 /
Grant succeeded.
SQL> conn x/x
Connected.
SQL> create schema authorization x
2 create table t1 (id number)
3 create table t2 (id number)
4 /
Schema created.
SQL> select table_name from user_tables
2 /
TABLE_NAME
------------------------------
T1
T2
SQL>
The CREATE SCHEMA command is pretty limited: we can create tables, views and indexes, and grant privileges on objects. The advantage of it is simply that we can create several objects in a single transaction, so that all the creates are rolled back if one fails. This is not possible when we run each create statement separately.
Not sure what you're thinking off when you mention "function ID". It's not a standard piece of Oracle functionality.
This does not define the difference between an owner and schema.
But I have always struggled with the idea that I create N number of users....when I want each of these users to "consume" (aka, use) a single schema.
This guy shows how to do this (have N number of users...get "redirected" to a single schema.
I will paste his code as well, on the off-chance the URL link dies in the future.
http://www.oracle-base.com/articles/misc/schema-owners-and-application-users.php
He has a second "synonym" approach. But I am only pasting the CURRENT_SCHEMA version.
AGAIN, I take NO credit for this. I just hate when someone says "your answer is at this link" and BOOM, the link is dead. :<
......................................................
(from http://www.oracle-base.com/articles/misc/schema-owners-and-application-users.php)
CURRENT_SCHEMA Approach
This method uses the CURRENT_SCHEMA session attribute to automatically point application users to the correct schema.
First, we create the schema owner and an application user.
CONN sys/password AS SYSDBA
-- Remove existing users and roles with the same names.
DROP USER schema_owner CASCADE;
DROP USER app_user CASCADE;
DROP ROLE schema_rw_role;
DROP ROLE schema_ro_role;
-- Schema owner.
CREATE USER schema_owner IDENTIFIED BY password
DEFAULT TABLESPACE users
TEMPORARY TABLESPACE temp
QUOTA UNLIMITED ON users;
GRANT CONNECT, CREATE TABLE TO schema_owner;
-- Application user.
CREATE USER app_user IDENTIFIED BY password
DEFAULT TABLESPACE users
TEMPORARY TABLESPACE temp;
GRANT CONNECT TO app_user;
Notice that the application user can connect, but does not have any tablespace quotas or privileges to create objects.
Next, we create some roles to allow read-write and read-only access.
CREATE ROLE schema_rw_role;
CREATE ROLE schema_ro_role;
We want to give our application user read-write access to the schema objects, so we grant the relevant role.
GRANT schema_rw_role TO app_user;
We need to make sure the application user has its default schema pointing to the schema owner, so we create an AFTER LOGON trigger to do this for us.
CREATE OR REPLACE TRIGGER app_user.after_logon_trg
AFTER LOGON ON app_user.SCHEMA
BEGIN
DBMS_APPLICATION_INFO.set_module(USER, 'Initialized');
EXECUTE IMMEDIATE 'ALTER SESSION SET current_schema=SCHEMA_OWNER';
END;
/
Now we are ready to create an object in the schema owner.
CONN schema_owner/password
CREATE TABLE test_tab (
id NUMBER,
description VARCHAR2(50),
CONSTRAINT test_tab_pk PRIMARY KEY (id)
);
GRANT SELECT ON test_tab TO schema_ro_role;
GRANT SELECT, INSERT, UPDATE, DELETE ON test_tab TO schema_rw_role;
Notice how the privileges are granted to the relevant roles. Without this, the objects would not be visible to the application user. We now have a functioning schema owner and application user.
SQL> CONN app_user/password
Connected.
SQL> DESC test_tab
Name Null? Type
----------------------------------------------------- -------- ------------------------------------
ID NOT NULL NUMBER
DESCRIPTION VARCHAR2(50)
SQL>
This method is ideal where the application user is simply an alternative entry point to the main schema, requiring no objects of its own.

Resources