SET PATH *LIBL ; 

CREATE OR REPLACE FUNCTION SAILPOINT.ES_V2_ASSIGN_MAPICS_USER_TO_ROLE ( 
	ENVID CHAR(2) , 
	USERNAME CHAR(10) , 
	USERROLES VARCHAR(1000) ) 
	RETURNS CLOB(2147483647)   
	LANGUAGE SQL 
	SPECIFIC SAILPOINT.V2_ESADDMUSRR 
	NOT DETERMINISTIC 
	MODIFIES SQL DATA 
	CALLED ON NULL INPUT 
	NOT FENCED 
	SET OPTION  ALWBLK = *ALLREAD , 
	ALWCPYDTA = *OPTIMIZE , 
	COMMIT = *NONE , 
	DECRESULT = (31, 31, 00) , 
	DLYPRP = *NO , 
	DYNDFTCOL = *NO , 
	DYNUSRPRF = *USER , 
	SRTSEQ = *HEX   
	BEGIN 
DECLARE LIBL VARCHAR ( 1024 ) DEFAULT '' ; 
DECLARE CUR_USR VARCHAR ( 10 ) DEFAULT '' ; 
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 . ASSIGN_ES_USER_TO_ROLE ( CUR_USR , 'G' , FRAGMENT , 
USERNAME ) ;  -- assign default 
END FOR ; 
RETURN 
( 
SELECT JSON_OBJECT ( 
'data' : 
JSON_ARRAYAGG ( 
JSON_OBJECT ( 
'userId' VALUE RTRIM ( 
CAST ( EUUSER AS VARCHAR ( 10 ) CCSID 37 ) ) , 
'roles' VALUE ROLESJSON FORMAT JSON 
) FORMAT JSON 
) , 
'errors' : JSON_ARRAY ( ) 
) 
FROM TABLE ( 
SELECT EUUSER , 
JSON_OBJECTAGG ( RTRIM ( 
CAST ( EUROLE AS VARCHAR ( 10 ) CCSID 37 ) ) VALUE 
RTRIM ( CAST ( EUDESC AS VARCHAR ( 50 ) CCSID 37 ) ) ) 
AS ROLESJSON 
FROM ESUSRP 
JOIN ESROLP 
USING ( EUROLE ) 
WHERE EUUSER = USERNAME 
GROUP BY EUUSER 
) ) ; 
END  ; 

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

GRANT EXECUTE   
ON SPECIFIC FUNCTION SAILPOINT.V2_ESADDMUSRR 
TO PUBLIC ; 

