/**
  @file
  @brief setup mpe_filtermaster RLS test
  @brief testing row level security


  <h4> SAS Macros </h4>
  @li mf_getuniquename.sas
  @li mf_getuser.sas
  @li mp_assertcolvals.sas
  @li mpe_filtermaster.sas

  @author 4GL Apps Ltd
  @copyright 4GL Apps Ltd.  This code may only be used within Data Controller
    and may not be re-distributed or re-sold without the express permission of
    4GL Apps Ltd.

**/


/**
    During tests, a DC group is made admin.  By removing this account from the
    MPE_GROUPS table and replacing with a SAS system group (that this account is
    a member of) we can become a "regular" member.
  */

proc sql;
delete from &dc_libref..MPE_GROUPS where user_name="%mf_getuser()";

%let tempgroup=%mf_getuniquename();
insert into &dc_libref..MPE_GROUPS
  set user_name="%mf_getuser()"
    ,group_name="&tempgroup"
    ,group_desc="temp group"
    ,tx_from='01Jan1960:00:00:00'dt
    ,tx_to='31Dec9999:23:59:59'dt;

/**
  Prep table
  */
delete from &dc_libref..MPE_ROW_LEVEL_SECURITY
  where RLS_TABLE="MPE_X_TEST";
select max(rls_rk) into: max_rk from &dc_libref..MPE_ROW_LEVEL_SECURITY;

insert into &dc_libref..mpe_row_level_security set
    tx_from=0
    ,tx_to='31DEC5999:23:59:59'dt
    ,RLS_RK=&max_rk+1
    ,RLS_SCOPE='ALL'
    ,RLS_GROUP="&tempgroup"
    ,RLS_LIBREF="&dc_libref"
    ,RLS_TABLE="MPE_X_TEST"
    ,RLS_GROUP_LOGIC='AND'
    ,RLS_SUBGROUP_LOGIC='OR'
    ,RLS_SUBGROUP_ID=0
    ,RLS_VARIABLE_NM='SOME_DROPDOWN'
    ,RLS_OPERATOR_NM='IN'
    ,RLS_RAW_VALUE="('Option 1','Option 2')"
    ,RLS_ACTIVE=1;

/*
  Test 1 - Expect 5 records:

    ((
        LIBREF CONTAINS 'DC'
    ) AND (
        DSN = 'MPE_LOCK_ANYTABLE'
    ))

*/
%mpe_filtermaster(VIEW,&dc_libref..MPE_X_TEST,
  dclib=&dc_libref,
  outref=qref
)

data _null_;
  infile qref;
  input;
  if _n_=1 then put 'Test 1: filter query';
  put _infile_;
run;

data work.test;
  set &dc_libref..MPE_X_TEST;
  where %inc qref;;
run;
proc sort data=work.test out=work.logme nodupkey;
by some_dropdown;
run;
%put checking values;
data _null_;
  set work.logme;
  put some_dropdown=;
run;

data work.check;
  val='Option 1';output;
  val='Option 2';output;
run;
%mp_assertcolvals(work.test.SOME_DROPDOWN,
  checkvals=work.check.val,
  desc=Testing for RLS filtered rows in MPE_X_TEST,
  test=ALLVALS
)

/**
  * put record back
  */
proc sql;
insert into &dc_libref..mpe_groups set
    tx_from=&dc_dttmtfmt.
    ,group_name="DC Demo Group"
    ,group_desc="Custom Group for Data Controller Purposes"
    ,user_name="%mf_getuser()"
    ,tx_to='31DEC5999:23:59:59'dt;
