/*
 * Title  : cr_sch.sql
 * Author : EXADIME LLC
 * Created: 29-Jul-2017
 * Updated: 10-Aug-2021
 * Release: 1.0.0
 * Purpose: Generates schema creation script for the given schema.
 * History: N/A
 */

start oracle.ini

set echo off
set feedback off
set serverout on
set termout on

set linesize 125
set pagesize 0
set pause off
set long 80

set heading off
set headsep on
set underline on
set colsep " "

set define on
set verify off
set escape off
set embedded on

set serveroutput on
execute dbms_output.enable(10000000);

accept p_schema prompt 'Enter schema name: '

spool &&tmp_dir/cr_sch.tmp

prompt set feedback on echo on
prompt spool &&rpt_dir/cr_sch.rpt
prompt 
prompt rem 0.Create users.

select 
        'CREATE USER ' || a.username ||chr(10)||chr(9)||
        'IDENTIFIED BY VALUES '''|| b.password || '''' || chr(10)||chr(9)||
        'DEFAULT TABLESPACE ' || a.default_tablespace ||chr(10)||chr(9)||
        'TEMPORARY TABLESPACE ' || a.temporary_tablespace ||chr(10)||chr(9)||
        'PROFILE ' || a.profile || ';'
from
        dba_users a,sys.user$ b
where
	a.username=b.name
and	username = upper('&&p_schema')
/

prompt
prompt rem 1.Grant tablespace quotas.

select 
	'alter user ' || username || ' quota ' || decode(max_bytes,-1,'unlimited',max_bytes) || ' on ' || tablespace_name || ';'
from 
	dba_ts_quotas
where
	username = upper('&&p_schema')
/

prompt rem 2.Grant roles.

select 
	'GRANT '|| granted_role || ' TO ' || grantee ||';'
from
	dba_role_privs
where
	grantee = upper('&&p_schema')
/

prompt
prompt rem Note:- Admin|Grant option will not be shown in this script.

prompt
prompt rem 3.Grant system privileges.

select 
	'GRANT '|| privilege || ' TO ' || grantee ||';'
from 
	dba_sys_privs
where 
	grantee = upper('&&p_schema')
/

prompt
prompt rem 4.Grant table privileges.

select 
	'GRANT '|| privilege || ' ON '|| owner || '.' || table_name || ' TO ' || grantee ||';'
from 
	dba_tab_privs
where 
	grantee = upper('&&p_schema')
/

prompt
prompt spool off

spool off

prompt Run the script "&&tmp_dir/cr_sch.tmp" manually.
prompt

set embedded off
set escape off
set verify on
set define on

set colsep " "
set underline on
set headsep on
set heading on

set pause off
set pagesize 24
set linesize 80
set long 80

set termout on
set serverout off
set feedback on
set echo off
