SET PATH *LIBL ; 

CREATE OR REPLACE FUNCTION SAILPOINT.ES_REMOVE_MAPICS_USER_FROM_ROLE ( 
	ENVID CHAR(2) , 
	USERNAME CHAR(10) , 
	USERROLES VARCHAR(1000) ) 
	RETURNS CLOB(2147483647)   
	LANGUAGE SQL 
	SPECIFIC SAILPOINT.ESDELMUSRR 
	NOT DETERMINISTIC 
	MODIFIES SQL DATA 
	CALLED ON NULL INPUT 
	NOT FENCED 
	SET OPTION  ALWBLK = *ALLREAD , 
	ALWCPYDTA = *OPTIMIZE , 
	COMMIT = *NONE , 
	DECRESULT = (31, 31, 00) , 
	DYNDFTCOL = *NO , 
	DYNUSRPRF = *USER , 
	SRTSEQ = *HEX   
	BEGIN 
DECLARE LIBL VARCHAR ( 1024 ) DEFAULT '' ; 
DECLARE CUR_USR VARCHAR ( 10 ) DEFAULT '' ; 
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION 
BEGIN 
DECLARE V_SQLSTATE CHAR ( 5 ) ; 
DECLARE V_DB2_RETURN_CODE INT ; 
DECLARE V_DB2_MESSAGE_ID CHAR ( 7 ) ; 
DECLARE V_ERROR_MESSAGE CLOB ( 2048 ) ; 
-- Capture diagnostic info 
GET DIAGNOSTICS CONDITION 1 
V_DB2_RETURN_CODE = DB2_RETURNED_SQLCODE , 
V_SQLSTATE = RETURNED_SQLSTATE , 
V_ERROR_MESSAGE = MESSAGE_TEXT , 
V_DB2_MESSAGE_ID = DB2_MESSAGE_ID ; 
RETURN 
( JSON_OBJECT ( 
'success' VALUE 'false' , 'SQLInfo' VALUE JSON_OBJECT ( 
'SQLState' VALUE V_SQLSTATE , 
'SQLCode' VALUE V_DB2_RETURN_CODE , 
'messageID' VALUE V_DB2_MESSAGE_ID , 
'message' VALUE V_ERROR_MESSAGE , 
'currentTimestamp' VALUE CURRENT_TIMESTAMP 
) 
) ) ; 
END ; 
SET CISTOOLS . LIBL = CISTOOLS . SET_LIBRARY_LIST ( ENVID ) ; 
SET CUR_USR = CURRENT_USER ; 
FOR SELECT FRAGMENT 
FROM TABLE ( 
CISTOOLS . SPLIT_STRING ( 
REGEXP_REPLACE ( 
CAST ( USERROLES AS VARCHAR ( 1000 ) CCSID 37 ) , 
'[\[|\]|\{|\}|\"|\,|\s+]' , ',' ) , ',' ) 
) 
WHERE FRAGMENT <> '' 
AND FRAGMENT IS NOT NULL 
DO 
CALL SAILPOINT . REMOVE_ES_USER_FROM_ROLE ( ENVID , USERNAME , 
FRAGMENT ) ; 
END FOR ; 
RETURN 
COALESCE ( 
JSON_OBJECT ( 
'success' VALUE 'true' , 'data' VALUE ( 
SELECT 
JSON_ARRAYAGG ( 
JSON_OBJECT ( 
'userId' VALUE RTRIM ( 
CAST ( EUUSER AS VARCHAR ( 10 ) CCSID 37 ) ) , 
'roles' VALUE ROLESJSON FORMAT JSON 
) FORMAT JSON 
) AS FINALJSON 
FROM TABLE ( 
SELECT EUUSER , 
JSON_OBJECTAGG ( RTRIM ( 
CAST ( EUROLE AS VARCHAR ( 10 ) CCSID 37 ) ) 
VALUE RTRIM ( 
CAST ( EUDESC AS VARCHAR ( 50 ) CCSID 37 ) ) 
FORMAT JSON ) AS ROLESJSON 
FROM ESUSRP 
JOIN ESROLP 
USING ( EUROLE ) 
WHERE EUUSER = USERNAME 
GROUP BY EUUSER 
) ) FORMAT JSON 
) , JSON_OBJECT ( 
'success' VALUE 'false' , 'SQLInfo' VALUE JSON_OBJECT ( 
'messageID' VALUE 'SQL02000' , 
'message' VALUE 'Requested resource not found ' , 
'currentTimestamp' : CURRENT_TIMESTAMP 
) 
) ) ; 
END  ; 

GRANT ALTER , EXECUTE   
ON SPECIFIC FUNCTION SAILPOINT.ESDELMUSRR 
TO AMAPICS WITH GRANT OPTION ; 

GRANT EXECUTE   
ON SPECIFIC FUNCTION SAILPOINT.ESDELMUSRR 
TO PUBLIC ; 

