Synonym Approach



This method relies on synonyms owned by the application user to point to the correct location of the schema objects.

First, we create the users in a similar way to the previous example.


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, CREATE SYNONYM TO app_user;


Once again, the application user can connect, but does not have any tablespace quotas. The difference here is that the application user does have the privilege to create synonyms.

Next, we create some roles to allow read-write and read-only access and grant the read-write role to the application user.


CREATE ROLE schema_rw_role;
CREATE ROLE schema_ro_role;
GRANT schema_rw_role TO app_user;


Now we are ready to create an object in the schema owner in the same way we did in the previous example.


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;


If we now connect to the application user we are not able to see the object without qualifying it with a schema name. We can either proceed in this fashion or use a synonym to point to the correct object.


CONN app_user/password
Connected.
DESC test_tab
ERROR:
ORA-04043: object test_tab does not exist


DESC schema_owner.test_tab
Name Null? Type

ID NOT NULL NUMBER
DESCRIPTION VARCHAR2(50)

CREATE SYNONYM test_tab FOR schema_owner.test_tab;

Synonym created.

DESC test_tab
Name Null? Type


ID NOT NULL NUMBER
DESCRIPTION VARCHAR2(50)

I find this method rather cumbersome due to the sheer number of synonyms required, especially when there are a large number of application users. Obviously, it is possible to use public synonyms, but this can be problematic when you have multiple application schemas on a single instance. I only use this method when I have developers who need to create their own schema objects for testing.

Hope this helps.
Regards

Comments

Popular posts from this blog

SQL Interview Questions

Manage Your Database Connection

Number of Days in Current Month