var filename VARCHAR2(100)

set termout off feed off verify off
alter session set nls_date_format='DD-MON-YYYY HH24:MI:SS';


BEGIN
	SELECT 'DL_maintenance_&1._&2._' || name || '_' || to_char(sysdate, 'DDMMYYYYHH24MISS') || '.log'
	INTO :filename
	FROM v$pdbs;
END;
/

column filename new_value _filename
select :filename filename from dual;
set termout on


set lines 5000 termout off echo off pages 50000 trimspool on timing on feedback on head on


spool &_filename

prompt Owner: &1
prompt Table Name: &2
prompt ----------------------------------

prompt 

set timing off

col owner for a20
col mview_name for a35
col last_refresh_date for a35
col last_refresh_end_time for a35
col compile_state for a20
col staleness for a15

select owner, mview_name, last_refresh_date, last_refresh_end_time, compile_state, staleness
from dba_mviews where mview_name = '&2' and owner = REPLACE('&1','DW','CORR');


col OBJECT_NAME format a35
col OBJECT_TYPE for a20
col OWNER for a20

select owner, object_name, object_type, created, last_ddl_time, status
from dba_objects
where object_name = '&2'
and object_type = 'MATERIALIZED VIEW'
and owner = REPLACE('&1','DW','CORR')
order by object_name;

prompt 
prompt 


set serverout on feed off timing on

DECLARE
	p_owner VARCHAR2(100 CHAR) := '&1';
	p_view VARCHAR2(100 CHAR) := '&2';

	p_owner_corr VARCHAR2(100 CHAR);
	v_grant_select VARCHAR2(300 CHAR);

	v_error VARCHAR2(4000 CHAR);
	v_status_grant VARCHAR2(10 CHAR);
	v_owner_exists NUMBER;
	v_tab_exists NUMBER := 0;
	v_trigger_sql VARCHAR2(4000 CHAR);
	v_db_name VARCHAR2(100);
	v_audit_condition VARCHAR2(500);

BEGIN

	IF upper(p_owner) = 'DW_RAR' THEN
		p_owner_corr := 'CORR_RAR';
		v_owner_exists := 1;

	ELSIF upper(p_owner) = 'DW_REF_MAIN' THEN
		p_owner_corr := 'CORR_REF_MAIN';
		v_owner_exists := 1;

	ELSE
		DBMS_OUTPUT.PUT_LINE('"' || upper(p_owner) || '" is not a valid schema.');
		v_owner_exists := 0;

	END IF;

	BEGIN
		select 1
		into v_tab_exists
		from dba_tables
		where owner = p_owner
			and table_name = p_view;
		
		EXCEPTION
			WHEN OTHERS THEN
			DBMS_OUTPUT.PUT_LINE('"' || upper(p_owner) || '"."' || p_view || '" table does not exist.');
			v_tab_exists := 0;
	END;


	IF v_owner_exists = 1 AND v_tab_exists = 1 THEN

		-- Grant SELECT privs
		BEGIN
			v_grant_select := 'grant SELECT ON "' || p_owner || '"."' || p_view || '" to "' || p_owner_corr || '"';
			DBMS_OUTPUT.PUT_LINE('Granting SELECT privilege');
			DBMS_OUTPUT.PUT_LINE('---------------------------------------------');
			DBMS_OUTPUT.PUT_LINE(v_grant_select);

			EXECUTE IMMEDIATE v_grant_select;

			--v_status_grant := 'SUCCESS';
			--DBMS_OUTPUT.PUT_LINE('Status: ' || v_status_grant);
			DBMS_OUTPUT.PUT_LINE('SELECT privilege successfully granted!');
			DBMS_OUTPUT.PUT_LINE(chr(10));

			EXCEPTION
				WHEN OTHERS THEN
					--v_status_grant := 'FAILED';
					v_error := SUBSTR(SQLERRM,1,2000);
					DBMS_OUTPUT.PUT_LINE(chr(10));
					DBMS_OUTPUT.PUT_LINE('Granting SELECT privilege FAILED!');
					DBMS_OUTPUT.PUT_LINE('Error code: ' || v_error);
					--DBMS_OUTPUT.PUT_LINE('Status: ' || v_status_grant);
		
		DBMS_OUTPUT.PUT_LINE(chr(10));
		END;
		-- End of grant SELECT privs

		-- Create materialized view
		BEGIN
			DBMS_OUTPUT.PUT_LINE('Creating materialized view "' || p_owner_corr || '"."' || p_view || '"');
			DBMS_OUTPUT.PUT_LINE('------------------------------------------------------------------------');
			CORR_RAR_TECH.MVIEW_CREATE_PKG.MVIEW_CREATE(p_owner, p_view);
			--CORR_RAR_TECH.MVIEW_PKG.MVIEW_CREATE(p_owner, p_view);
			
			DBMS_OUTPUT.PUT_LINE('Materialized view "' || p_owner_corr || '"."' || p_view || '" successfully created!');
			DBMS_OUTPUT.PUT_LINE(chr(10));

			EXCEPTION
				WHEN OTHERS THEN
					--v_status_grant := 'FAILED';
					v_error := SUBSTR(SQLERRM,1,2000);
					DBMS_OUTPUT.PUT_LINE(chr(10));
					DBMS_OUTPUT.PUT_LINE('Materialized view creation FAILED!');
					DBMS_OUTPUT.PUT_LINE('Error code: ' || v_error);
		
		DBMS_OUTPUT.PUT_LINE(chr(10));
		END;
		-- End of the creation of the materialized view

		-- Create audit trigger
		BEGIN
			FOR i IN (SELECT mview_name FROM dba_mviews WHERE owner = 'CORR_RAR') LOOP
			BEGIN
			  DBMS_OUTPUT.PUT_LINE('Creating audit trigger for materialized view "' || p_owner_corr || '"."' || p_view || '"');
			  DBMS_OUTPUT.PUT_LINE('------------------------------------------------------------------------------------------');
			  p_view := i.mview_name;
			  v_trigger_sql := 'CREATE OR REPLACE TRIGGER "' || p_owner_corr || '"."' || p_view || '"' || chr(10) ||
			  'FOR INSERT OR UPDATE OR DELETE ON "' || p_owner_corr || '"."' || p_view || '"' || chr(10) ||
			  'COMPOUND TRIGGER' || chr(10) ||
			  '  type      typ_audit is table of CORR_RAR_TECH.A_MVIEW_AUDIT_TBL%rowtype index by pls_integer;' || chr(10) ||
			  '  tbl_audit typ_audit;' || chr(10) ||
			  '  l_idx     pls_integer := 0;' || chr(10) ||
			  '  v_index   SIMPLE_INTEGER            := 0;' || chr(10) ||
			  'AFTER EACH ROW' || chr(10) ||
			  'IS' || chr(10) ||
			  'BEGIN' || chr(10) ||
			  '  v_index := v_index + 1;' || chr(10) ||
			  'END AFTER EACH ROW;' || chr(10) ||
			  'AFTER STATEMENT IS' || chr(10) ||
			  'BEGIN' || chr(10) ||
			  '  IF v_index > 0 THEN' || chr(10) ||
			  '    l_idx := tbl_audit.count + 1;' || chr(10) ||
			  '    tbl_audit(l_idx).action := case when inserting then ''INSERT'' when updating then ''UPDATE'' else ''DELETE'' end;' || chr(10) ||
			  '    tbl_audit(l_idx).changed_by := CORR_RAR_TECH.MVIEW_FGA_HANDLER_PKG.g_user;' || chr(10) ||
			  '    tbl_audit(l_idx).change_ts := systimestamp;' || chr(10) ||
			  '    tbl_audit(l_idx).query_sql := CORR_RAR_TECH.MVIEW_FGA_HANDLER_PKG.g_statement;' || chr(10) ||
			  '    tbl_audit(l_idx).binds := CORR_RAR_TECH.MVIEW_FGA_HANDLER_PKG.g_binds;' || chr(10) ||
			  '    insert into CORR_RAR_TECH.A_MVIEW_AUDIT_TBL values tbl_audit(l_idx);' || chr(10) ||
			  '    tbl_audit.delete;' || chr(10) ||
			  '  END IF;' || chr(10) ||
			  'END AFTER STATEMENT;' || chr(10) ||
			  'END;';
				  
			  EXECUTE IMMEDIATE v_trigger_sql;
				
			  DBMS_OUTPUT.PUT_LINE('Audit trigger for materialized view "' || p_owner_corr || '"."' || p_view || '" successfully created!');
			  DBMS_OUTPUT.PUT_LINE(chr(10));
			
			  EXCEPTION
				WHEN OTHERS THEN
				--v_status_grant := 'FAILED';
				  v_error := SUBSTR(SQLERRM,1,2000);
				  DBMS_OUTPUT.PUT_LINE(chr(10));
				  DBMS_OUTPUT.PUT_LINE('Audit trigger creation FAILED!');
				  DBMS_OUTPUT.PUT_LINE('Error code: ' || v_error);
				  
			  DBMS_OUTPUT.PUT_LINE(chr(10));
			END;
		  END LOOP;
		END;
		-- End of the creation of the audit trigger
		
		-- Create audit policy
		BEGIN
			
			SELECT  name 	
                        INTO v_db_name
                        FROM v$pdbs;


                        IF v_db_name like 'A%' THEN
                           v_audit_condition := 'SUBSTR(SYS_CONTEXT(''USERENV'', ''OS_USER''), 1, 30) <> ''ap-informatica-ipcwa''';
                        ELSIF v_db_name like 'P%' THEN
                           v_audit_condition := 'SUBSTR(SYS_CONTEXT(''USERENV'', ''OS_USER''), 1, 30) <> ''ap-informatica-ipcwp''';
                        ELSE	
                           v_audit_condition := 'SUBSTR(SYS_CONTEXT(''USERENV'', ''OS_USER''), 1, 30) <> ''ap-informatica-ipcwt''';
                        END IF;	
			
			DBMS_OUTPUT.PUT_LINE('Creating audit policy for materialized view "' || p_owner_corr || '"."' || p_view || '"');
			DBMS_OUTPUT.PUT_LINE('-----------------------------------------------------------------------------------------');
			DBMS_FGA.ADD_POLICY
			(
				OBJECT_SCHEMA => p_owner_corr,
				OBJECT_NAME => p_view,
				audit_condition => v_audit_condition,
				POLICY_NAME => 'RAR_DATAEDITING_AUD',
				STATEMENT_TYPES => 'INSERT, UPDATE, DELETE',
				HANDLER_SCHEMA => 'CORR_RAR_TECH',
				HANDLER_MODULE => 'MVIEW_FGA_HANDLER_PKG.set_statement'
			); 	
			
			DBMS_OUTPUT.PUT_LINE('Successfully added policy for ' || p_owner_corr || '.' || p_view);
			DBMS_OUTPUT.PUT_LINE(chr(10));
			
			EXCEPTION
				WHEN OTHERS THEN
					DBMS_OUTPUT.PUT_LINE('Failed to add policy for ' || p_owner_corr || '.' || p_view || ':' || SUBSTR(SQLERRM,1,200));
		  	
		DBMS_OUTPUT.PUT_LINE(chr(10));
		END;
		-- End of the creation of the audit policy

		-- Refresh materialized view
		BEGIN
			DBMS_OUTPUT.PUT_LINE('Refreshing materialized view "' || p_owner_corr || '"."' || p_view || '"');
			DBMS_OUTPUT.PUT_LINE('--------------------------------------------------------------------------');			
			

			IF p_owner_corr = 'CORR_RAR' THEN
				CORR_RAR.MVIEW_PKG.MVIEW_REFRESH(p_owner_corr, p_view);
			
			ELSIF p_owner_corr = 'CORR_REF_MAIN' THEN
				CORR_REF_MAIN.MVIEW_PKG.MVIEW_REFRESH(p_owner_corr, p_view);
		
			END IF;
	
			DBMS_OUTPUT.PUT_LINE('Materialized view "' || p_owner_corr || '"."' || p_view || '" successfully refeshed!');
			DBMS_OUTPUT.PUT_LINE(chr(10));
			
			EXCEPTION
				WHEN OTHERS THEN
					--v_status_grant := 'FAILED';
					v_error := SUBSTR(SQLERRM,1,2000);
					DBMS_OUTPUT.PUT_LINE(chr(10));
					DBMS_OUTPUT.PUT_LINE('Materialized view refresh FAILED!');
					DBMS_OUTPUT.PUT_LINE('Error code: ' || v_error);
		
		DBMS_OUTPUT.PUT_LINE(chr(10));
		END;
		-- End of the refresh of the materialized view




	ELSE
		DBMS_OUTPUT.PUT_LINE('Materialized view cannot be created. Please verify that the table exists. The program will exit.');

	END IF;


END;
/

set timing off

col owner for a20
col mview_name for a35
col last_refresh_date for a35
col last_refresh_end_time for a35
col compile_state for a20
col staleness for a15

select owner, mview_name, last_refresh_date, last_refresh_end_time, compile_state, staleness
from dba_mviews where mview_name = '&2' and owner = REPLACE('&1','DW','CORR');


col OBJECT_NAME format a35
col OBJECT_TYPE for a20
col OWNER for a20

select owner, object_name, object_type, created, last_ddl_time, status
from dba_objects
where object_name = '&2'
--and owner = 'OU_LEGACY'
and owner = REPLACE('&1','DW','CORR')
and object_type = 'MATERIALIZED VIEW'
order by object_name;

set timing on
spool off