Macros for SAS Application Developers
https://github.com/sasjs/core
Loading...
Searching...
No Matches
mp_filtercheck.sas
Go to the documentation of this file.
1/**
2 @file
3 @brief Checks an input filter table for validity
4 @details Performs checks on the input table to ensure it arrives in the
5 correct format. This is necessary to prevent code injection. Will update
6 SYSCC to 1008 if bad records are found, and call mp_abort.sas for a
7 graceful service exit (configurable).
8
9 Used for dynamic filtering in [Data Controller for SAS®](
10 https://datacontroller.io).
11
12 Usage:
13
14 %mp_filtercheck(work.filter,targetds=sashelp.class,outds=work.badrecords)
15
16 The input table should have the following format:
17
18 |GROUP_LOGIC:$3|SUBGROUP_LOGIC:$3|SUBGROUP_ID:8.|VARIABLE_NM:$32|OPERATOR_NM:$10|RAW_VALUE:$4000|
19 |---|---|---|---|---|---|
20 |AND|AND|1|AGE|=|12|
21 |AND|AND|1|SEX|<=|'M'|
22 |AND|OR|2|Name|NOT IN|('Jane','Alfred')|
23 |AND|OR|2|Weight|>=|7|
24
25 Rules applied:
26
27 @li GROUP_LOGIC - only AND/OR
28 @li SUBGROUP_LOGIC - only AND/OR
29 @li SUBGROUP_ID - only integers
30 @li VARIABLE_NM - must be in the target table
31 @li OPERATOR_NM - only =/>/</<=/>=/BETWEEN/IN/NOT IN/NE/CONTAINS/=:/^=:
32 @li RAW_VALUE - no unquoted values except integers, commas and spaces. For
33 numeric columns, SAS date, datetime and time literals are also accepted, eg
34 '20APR2042'd, '01JAN1960:00:00:42'dt, '00:00:42't.
35
36 @returns The &outds table containing any bad rows, plus a REASON_CD column.
37
38 @param [in] inds The table to be checked, with the format above
39 @param [in] targetds= The target dataset against which to verify VARIABLE_NM.
40 This must be available (ie, the library must be assigned).
41 @param [out] abort= (YES) If YES will call mp_abort.sas on any exceptions
42 @param [out] outds= (work.badrecords) The output table, which is a copy of the
43 &inds. table plus a REASON_CD column, containing only bad records.
44 If bad records are found, the SYSCC value will be set to 1008
45 (a general data problem).
46 Downstream processes should check this table (and return code) before
47 continuing.
48
49 <h4> SAS Macros </h4>
50 @li mp_abort.sas
51 @li mf_getuniquefileref.sas
52 @li mf_getvarlist.sas
53 @li mf_getvartype.sas
54 @li mp_filtergenerate.sas
55 @li mp_filtervalidate.sas
56
57 <h4> Related Macros </h4>
58 @li mp_filtergenerate.sas
59 @li mp_filtervalidate.sas
60
61 @version 9.3
62 @author Allan Bowe
63
64 @todo Support hex / name literals and exponents in RAW_VALUE field
65 @sasjslint {"maxLineLength": 99}
66**/
67
68%macro mp_filtercheck(inds,targetds=,outds=work.badrecords,abort=YES);
69
70%mp_abort(iftrue= (&syscc ne 0)
71 ,mac=&sysmacroname
72 ,msg=%str(syscc=&syscc - on macro entry)
73)
74
75/* Validate input column */
76%local vtype;
77%let vtype=%mf_getvartype(&inds,RAW_VALUE);
78%mp_abort(iftrue=(&abort=YES and &vtype ne C),
79 mac=&sysmacroname,
80 msg=%str(%str(ERR)OR: RAW_VALUE must be character)
81)
82%if &vtype ne C %then %do;
83 %put &sysmacroname: RAW_VALUE must be character;
84 %let syscc=42;
85 %return;
86%end;
87
88
89/**
90 * Sanitise the values based on valid value lists, then strip out
91 * quotes, commas, periods and spaces.
92 */
93%local reason_cd nobs;
94%let nobs=0;
95data &outds;
96 /*length GROUP_LOGIC SUBGROUP_LOGIC $3 SUBGROUP_ID 8 VARIABLE_NM $32
97 OPERATOR_NM $10 RAW_VALUE $4000;*/
98 set &inds end=last;
99 length reason_cd $4032 vtype vtype2 $1 vnum dsid 8 tmp $4000 re_temporal 8
100 vref $64;
101 drop tmp re_temporal vref;
102 retain re_temporal;
103 /* SAS temporal literals - date, datetime and time */
104 if _n_=1 then re_temporal=prxparse("/^'[^']*'(dt|d|t)$/i");
105
106 /* quick check to ensure column exists */
107 if upcase(VARIABLE_NM) not in
108 (%upcase(%mf_getvarlist(&targetds,dlm=%str(,),quote=SINGLE)))
109 then do;
110 REASON_CD="Variable "!!cats(variable_nm)!!" not in &targetds";
111 putlog REASON_CD= VARIABLE_NM=;
112 call symputx('reason_cd',reason_cd,'l');
113 call symputx('nobs',_n_,'l');
114 output;
115 return;
116 end;
117
118 /* need to open the dataset to get the column type */
119 retain dsid;
120 if _n_=1 then dsid=open("&targetds","i");
121 if dsid>0 then do;
122 vnum=varnum(dsid,VARIABLE_NM);
123 if vnum<1 then do;
124 /* should not happen as was also tested for above */
125 REASON_CD=cats("Variable (",VARIABLE_NM,") not found in &targetds");
126 putlog REASON_CD= dsid=;
127 call symputx('reason_cd',reason_cd,'l');
128 call symputx('nobs',_n_,'l');
129 output;
130 goto endstep;
131 end;
132 /* now we can get the type */
133 else vtype=vartype(dsid,vnum);
134 end;
135 else do;
136 REASON_CD=cats("Could not open &targetds");
137 putlog REASON_CD= dsid=;
138 call symputx('reason_cd',reason_cd,'l');
139 call symputx('nobs',_n_,'l');
140 output;
141 stop;
142 end;
143
144 /* closed list checks */
145 if GROUP_LOGIC not in ('AND','OR') then do;
146 REASON_CD='GROUP_LOGIC should be AND/OR, not:'!!cats(GROUP_LOGIC);
147 putlog REASON_CD= GROUP_LOGIC=;
148 call symputx('reason_cd',reason_cd,'l');
149 call symputx('nobs',_n_,'l');
150 output;
151 end;
152 if SUBGROUP_LOGIC not in ('AND','OR') then do;
153 REASON_CD='SUBGROUP_LOGIC should be AND/OR, not:'!!cats(SUBGROUP_LOGIC);
154 putlog REASON_CD= SUBGROUP_LOGIC=;
155 call symputx('reason_cd',reason_cd,'l');
156 call symputx('nobs',_n_,'l');
157 output;
158 end;
159 if mod(SUBGROUP_ID,1) ne 0 then do;
160 REASON_CD='SUBGROUP_ID should be integer, not '!!cats(subgroup_id);
161 putlog REASON_CD= SUBGROUP_ID=;
162 call symputx('reason_cd',reason_cd,'l');
163 call symputx('nobs',_n_,'l');
164 output;
165 end;
166 if OPERATOR_NM not in
167 ('=','>','<','<=','>=','NE','GE','LE','BETWEEN','IN','NOT IN','CONTAINS'
168 ,'=:','^=:')
169 then do;
170 REASON_CD='Invalid OPERATOR_NM: '!!cats(OPERATOR_NM);
171 putlog REASON_CD= OPERATOR_NM=;
172 call symputx('reason_cd',reason_cd,'l');
173 call symputx('nobs',_n_,'l');
174 output;
175 end;
176
177 /* the string operators are character-only - the engine rejects a numeric
178 operand for a truncated comparison, and CONTAINS has no numeric form, so
179 catch the pairing here rather than letting the generated clause fail
180 validation with no reference to the offending variable */
181 if vtype='N' & OPERATOR_NM in ('CONTAINS','=:','^=:') then do;
182 vref=cats("&targetds",'.',VARIABLE_NM);
183 REASON_CD=catx(' ',OPERATOR_NM,'is only valid for character'
184 ,'variables -',vref,'is numeric');
185 putlog REASON_CD= OPERATOR_NM=;
186 call symputx('reason_cd',reason_cd,'l');
187 call symputx('nobs',_n_,'l');
188 output;
189 return;
190 end;
191
192 /* the operand must be a string literal or a character variable - the
193 engine rejects an unquoted numeric value even where the column is
194 character, eg 'name contains 12' */
195 if vtype='C' & OPERATOR_NM='CONTAINS'
196 & subpad(strip(raw_value),1,1) not in ('"',"'")
197 then do;
198 vref=cats("&targetds",'.',VARIABLE_NM);
199 /* a bare value can only be a variable reference if it is a valid name */
200 vnum=0;
201 if prxmatch('/^[a-z_][a-z0-9_]*$/i',strip(raw_value))>0 then do;
202 vnum=varnum(dsid,strip(raw_value));
203 end;
204 if vnum>=1 then do;
205 /* the name is a variable of this table - the type must be character */
206 vtype2=vartype(dsid,vnum);
207 if vtype2='C' then return;
208 REASON_CD=catx(' ',"Compared Type ("!!vtype2!!") is not (C) -"
209 ,vref,'CONTAINS',cats(raw_value));
210 end;
211 else REASON_CD=catx(' ','CONTAINS requires a quoted value or a character'
212 ,'variable -',vref,'CONTAINS',cats(raw_value));
213 putlog REASON_CD= OPERATOR_NM=;
214 call symputx('reason_cd',reason_cd,'l');
215 call symputx('nobs',_n_,'l');
216 output;
217 return;
218 end;
219
220 /* special missing logic */
221 if vtype='N' & OPERATOR_NM in ('=','>','<','<=','>=','NE','GE','LE') then do;
222 if cats(upcase(raw_value)) in (
223 '.','.A','.B','.C','.D','.E','.F','.G','.H','.I','.J','.K','.L','.M','.N'
224 '.N','.O','.P','.Q','.R','.S','.T','.U','.V','.W','.X','.Y','.Z','._'
225 )
226 then do;
227 /* valid numeric - exit data step loop */
228 return;
229 end;
230 else if subpad(upcase(raw_value),1,1) in (
231 'A','B','C','D','E','F','G','H','I','J','K','L','M','N'
232 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z','_'
233 )
234 then do;
235 /* check if the raw_value contains a valid variable NAME */
236 vnum=varnum(dsid,subpad(raw_value,1,32));
237 if vnum>0 then do;
238 /* now we can get the type */
239 vtype2=vartype(dsid,vnum);
240 /* check type matches */
241 if vtype2=vtype then do;
242 /* valid target var - exit loop */
243 return;
244 end;
245 else do;
246 REASON_CD=cats("Compared Type (",vtype2,") is not (",vtype,")");
247 putlog REASON_CD= dsid=;
248 call symputx('reason_cd',reason_cd,'l');
249 call symputx('nobs',_n_,'l');
250 output;
251 goto endstep;
252 end;
253 end;
254 end;
255 end;
256
257 /* a SAS temporal literal is a valid value for a numeric column */
258 if vtype='N' and prxmatch(re_temporal,cats(raw_value))>0 then return;
259
260 /* special logic */
261 if OPERATOR_NM in ('IN','NOT IN','BETWEEN') then do;
262 if OPERATOR_NM='BETWEEN' then raw_value1=tranwrd(raw_value,' AND ',',');
263 else do;
264 if substr(raw_value,1,1) ne '('
265 or substr(cats(reverse(raw_value)),1,1) ne ')'
266 then do;
267 REASON_CD='Missing start/end bracket in RAW_VALUE';
268 putlog REASON_CD= OPERATOR_NM= raw_value= raw_value1= ;
269 call symputx('reason_cd',reason_cd,'l');
270 call symputx('nobs',_n_,'l');
271 output;
272 end;
273 else raw_value1=substr(raw_value,2,max(length(raw_value)-2,0));
274 end;
275 /* we now have a comma seperated list of values */
276 if vtype='N' then do i=1 to countc(raw_value1, ',')+1;
277 tmp=scan(raw_value1,i,',');
278 if cats(tmp) ne '.' and input(tmp, ?? 8.) eq . then do;
279 /* a SAS temporal literal is a valid value for a numeric column */
280 if prxmatch(re_temporal,cats(tmp))=0 then do;
281 if OPERATOR_NM ='BETWEEN' and subpad(upcase(tmp),1,1) in (
282 'A','B','C','D','E','F','G','H','I','J','K','L','M','N'
283 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z','_'
284 )
285 then do;
286 /* check if the raw_value contains a valid variable NAME */
287 /* is not valid syntax for IN or NOT IN */
288 vnum=varnum(dsid,subpad(tmp,1,32));
289 if vnum>0 then do;
290 /* now we can get the type */
291 vtype2=vartype(dsid,vnum);
292 /* check type matches */
293 if vtype2 ne vtype then do;
294 REASON_CD=cats("Compared Type (",vtype2,") is not (",vtype,")");
295 putlog REASON_CD= dsid=;
296 call symputx('reason_cd',reason_cd,'l');
297 call symputx('nobs',_n_,'l');
298 output;
299 goto endstep;
300 end;
301 end;
302 else do;
303 REASON_CD='Non Numeric value provided';
304 putlog REASON_CD= OPERATOR_NM= raw_value= raw_value1= ;
305 call symputx('reason_cd',reason_cd,'l');
306 call symputx('nobs',_n_,'l');
307 output;
308 end;
309 end;
310 else do;
311 REASON_CD='Non Numeric value provided';
312 putlog REASON_CD= OPERATOR_NM= raw_value= raw_value1= ;
313 call symputx('reason_cd',reason_cd,'l');
314 call symputx('nobs',_n_,'l');
315 output;
316 end;
317 end;
318 end;
319 end;
320 /* every value of a numeric IN / BETWEEN list is checked one by one above,
321 so a numeric list skips the generic check below - that would only flag
322 the list syntax itself. A character list is unchanged. */
323 if vtype='N' then return;
324 end;
325 else raw_value1=raw_value;
326
327 /* remove nested literals eg '' */
328 raw_value1=tranwrd(raw_value1,"''",'');
329
330 /* now match string literals (always single quotes) */
331 raw_value2=raw_value1;
332 regex = prxparse("s/(\').*?(\')//");
333 call prxchange(regex,-1,raw_value2);
334
335 /* remove commas and periods*/
336 raw_value3=compress(raw_value2,',.');
337
338 /* output records that contain values other than digits and spaces */
339 if notdigit(compress(raw_value3,' '))>0 then do;
340 if vtype='C' and subpad(upcase(raw_value),1,1) in (
341 'A','B','C','D','E','F','G','H','I','J','K','L','M','N'
342 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z','_'
343 )
344 then do;
345 /* check if the raw_value contains a valid variable NAME */
346 vnum=varnum(dsid,subpad(raw_value,1,32));
347 if vnum>0 then do;
348 /* now we can get the type */
349 vtype2=vartype(dsid,vnum);
350 /* check type matches */
351 if vtype2=vtype then do;
352 /* valid target var - exit loop */
353 return;
354 end;
355 else do;
356 REASON_CD=cats("Compared Char Type (",vtype2,") is not (",vtype,")");
357 putlog REASON_CD= dsid=;
358 call symputx('reason_cd',reason_cd,'l');
359 call symputx('nobs',_n_,'l');
360 output;
361 goto endstep;
362 end;
363 end;
364 end;
365
366 putlog raw_value3= $hex32.;
367 REASON_CD=cats('Invalid RAW_VALUE:',raw_value);
368 putlog (_all_)(=);
369 call symputx('reason_cd',reason_cd,'l');
370 call symputx('nobs',_n_,'l');
371 output;
372 end;
373
374 endstep:
375 if last then rc=close(dsid);
376run;
377
378
379data _null_;
380 set &outds end=last;
381 putlog (_all_)(=);
382run;
383
384%mp_abort(iftrue=(&abort=YES and &nobs>0),
385 mac=&sysmacroname,
386 msg=%str(Data issue: %superq(reason_cd))
387)
388
389%if &nobs>0 %then %do;
390 %let syscc=1008;
391 %return;
392%end;
393
394/**
395 * syntax checking passed but it does not mean the filter is valid
396 * for that we can run a proc sql validate query
397 */
398%local fref1;
399%let fref1=%mf_getuniquefileref();
400%mp_filtergenerate(&inds,outref=&fref1)
401
402/* this macro will also set syscc to 1008 if any issues found */
403%mp_filtervalidate(&fref1,&targetds,outds=&outds,abort=&abort)
404
405%mend mp_filtercheck;