create or replace FUNCTION fnc_26ai_censo_vpd (
  schema_name  IN VARCHAR2,
  object_name  IN VARCHAR2
) RETURN VARCHAR2
AS
/*

  Criado por: fernando.leal@oracle.com
  Data: Oct/2025
  Objetivo: demonstrar casos de uso do Oracle AI Database 26ai

  v1 - funcao de VPD para demonstracao de dados Censo - leal

  Pre req: 
  
-- como ADMIN
grant CREATE ANY CONTEXT to aichat1

-- como AICHAT1
CREATE CONTEXT CTX_26AI_RLS USING pkg_26AI_CENSO_RLS;

CREATE OR REPLACE PACKAGE pkg_26AI_CENSO_RLS AS
  PROCEDURE set_user(p_user IN VARCHAR2);
END;

CREATE OR REPLACE PACKAGE BODY pkg_26AI_CENSO_RLS AS

  PROCEDURE set_user(p_user IN VARCHAR2) IS
  BEGIN
    DBMS_SESSION.SET_CONTEXT(
      namespace => 'CTX_26AI_RLS',
      attribute => 'SESSION_USER',
      value     => p_user
    );
  END;

END ;

-- teste
BEGIN
  pkg_26AI_CENSO_RLS.set_user('ADMIN');
END;

SELECT SYS_CONTEXT('CTX_26AI_RLS','SESSION_USER') ;


*/
  l_predicate  VARCHAR2(4000);
BEGIN

  pkg_26AI_CENSO_RLS.set_user( trim(lower(V('APP_USER')))  );

  -- Build a predicate that filters by allowed operation codes for current user
  l_predicate := ' UF IN (SELECT UF FROM TB_26AI_CENSO_VPD WHERE trim(lower(username)) = ''' || SYS_CONTEXT('CTX_26AI_RLS','SESSION_USER')  || ''')';

  --insert into tb_test values(  l_predicate  );
    
  RETURN l_predicate;
END;
/