@sasjs/core 3.11.1 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +7 -5
  2. package/base/mf_abort.sas +1 -1
  3. package/base/mf_dedup.sas +0 -1
  4. package/base/mf_existvar.sas +4 -4
  5. package/base/mf_getfilesize.sas +31 -14
  6. package/base/mf_wordsinstr1andstr2.sas +0 -1
  7. package/base/mf_wordsinstr1butnotstr2.sas +5 -5
  8. package/base/mp_abort.sas +3 -2
  9. package/base/mp_assertdsobs.sas +8 -9
  10. package/base/mp_assertscope.sas +39 -14
  11. package/base/mp_coretable.sas +27 -1
  12. package/base/mp_createwebservice.sas +10 -8
  13. package/base/mp_csv2ds.sas +0 -4
  14. package/base/mp_deletefolder.sas +1 -0
  15. package/base/mp_dirlist.sas +9 -2
  16. package/base/mp_ds2csv.sas +119 -14
  17. package/base/mp_ds2squeeze.sas +120 -0
  18. package/base/mp_getmaxvarlengths.sas +51 -18
  19. package/base/mp_guesspk.sas +245 -225
  20. package/base/mp_init.sas +39 -32
  21. package/base/mp_jsonout.sas +6 -2
  22. package/base/mp_stackdiffs.sas +592 -0
  23. package/base/mp_storediffs.sas +11 -29
  24. package/base/mp_testservice.sas +25 -11
  25. package/fcmp/mcf_init.sas +44 -0
  26. package/fcmp/mcf_length.sas +83 -0
  27. package/fcmp/mcf_stpsrv_header.sas +6 -2
  28. package/fcmp/mcf_string2file.sas +9 -0
  29. package/meta/mm_createstp.sas +1 -0
  30. package/meta/mm_createwebservice.sas +7 -3
  31. package/meta/mm_getgroupmembers.sas +15 -8
  32. package/meta/mm_getservercontexts.sas +11 -4
  33. package/meta/mm_updatestpsourcecode.sas +0 -11
  34. package/meta/mm_webout.sas +1 -1
  35. package/package.json +1 -1
  36. package/server/ms_webout.sas +1 -1
  37. package/viya/mv_createwebservice.sas +7 -3
  38. package/viya/mv_deletefoldermember.sas +1 -0
  39. package/viya/mv_deletejes.sas +1 -0
  40. package/viya/mv_webout.sas +1 -1
  41. package/viya/mv_getaccesstoken.sas +0 -32
  42. package/viya/mv_getapptoken.sas +0 -23
  43. package/viya/mv_getrefreshtoken.sas +0 -33
package/README.md CHANGED
@@ -125,6 +125,7 @@ filename mc url "https://raw.githubusercontent.com/sasjs/core/main/all.sas";
125
125
  - macro names must be lowercase
126
126
  - one macro per file
127
127
  - prefixes:
128
+ - _mcf_ for macro compiled functions (proc fcmp)
128
129
  - _mf_ for macro functions (can be used in open code).
129
130
  - _ml_ for macros that are used to compile LUA modules
130
131
  - _mm_ for metadata macros (interface with the metadata server).
@@ -166,7 +167,7 @@ SAS code can contain one of two types of dependency - SAS Macros, and SAS Includ
166
167
  @li someprogram.sas FREFTWO
167
168
  ```
168
169
 
169
- The CLI can then extract all the dependencies and insert as precode (SAS Macros) or in a temp engine fileref (SAS Includes) when creating SAS Jobs and Services.
170
+ The CLI can then extract all the dependencies and insert as precode (SAS Macros) or in a temp engine fileref (SAS Includes) when creating SAS Jobs and Services (and Tests).
170
171
 
171
172
  When contributing to this library, it is therefore important to ensure that all dependencies are listed in the header in this format.
172
173
 
@@ -180,9 +181,11 @@ When contributing to this library, it is therefore important to ensure that all
180
181
  - The closing `%mend;` should **not** contain the macro name.
181
182
  - All macros should be defined with brackets, even if no variables are needed - ie `%macro x();` not `%macro x;`
182
183
  - Mandatory parameters should be positional, all optional parameters should be keyword (var=) style.
183
- - All dataset references must be 2 level (eg `work.blah`, not `blah`). This is to avoid contention when options [DATASTMTCHK](https://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a000279064.htm)=ALLKEYWORDS is in effect.
184
+ - All dataset references must be 2 level (eg `work.blah`, not `blah`). This is to avoid contention when options [DATASTMTCHK](https://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a000279064.htm)=ALLKEYWORDS is in effect, or the [USER](https://documentation.sas.com/doc/en/pgmsascdc/9.4_3.5/lrcon/n18m1vkqmeo4esn1moikt23zhp8s.htm) library is active.
184
185
  - Avoid naming collisions! All macro variables should be local scope. Use system generated work tables where possible - eg `data ; set sashelp.class; run; data &output; set &syslast; run;`
186
+ - Where global macro variables are absolutely necessary, they should make use of `&sasjs_prefix` - see mp_init.sas
185
187
  - The use of `quit;` for `proc sql` is optional unless you are looking to benefit from the timing statistics.
188
+ - Use [sasjs lint](https://github.com/sasjs/lint)!
186
189
 
187
190
  ## General Notes
188
191
 
@@ -190,10 +193,9 @@ When contributing to this library, it is therefore important to ensure that all
190
193
 
191
194
  ## Breaking Changes
192
195
 
193
- We are currently on major release v3. The following changes are planned when the next major (breaking) release becomes necessary:
196
+ We are currently on major release v4. Breaking changes should be marked with the [deprecated](https://www.doxygen.nl/manual/commands.html#cmddeprecated) doxygen tag. The following changes are planned when the next major (breaking) release becomes necessary:
194
197
 
195
- * Remove `dbg` parameter from mp_jsonout.sas (implement mdebug instead)
196
- * Remove `END_DTTM` and `START_DTTM` from mx_webout JSON
198
+ * mp_testservice.sas to be renamed as mp_execute.sas (as it doesn't actually test anything)
197
199
 
198
200
  ## Star Gazing
199
201
 
package/base/mf_abort.sas CHANGED
@@ -11,7 +11,7 @@
11
11
  @cond
12
12
  **/
13
13
 
14
- %macro mf_abort(mac=mf_abort.sas, type=deprecated, msg=, iftrue=%str(1=1)
14
+ %macro mf_abort(mac=mf_abort.sas, msg=, iftrue=%str(1=1)
15
15
  )/*/STORE SOURCE*/;
16
16
 
17
17
  %if not(%eval(%unquote(&iftrue))) %then %return;
package/base/mf_dedup.sas CHANGED
@@ -23,7 +23,6 @@
23
23
 
24
24
  <h4> Related Macros </h4>
25
25
  @li mf_trimstr.sas
26
- @li mf_wordsinstr1butnotstr2.sas
27
26
 
28
27
  @version 9.2
29
28
  @author Allan Bowe
@@ -1,11 +1,11 @@
1
1
  /**
2
2
  @file
3
3
  @brief Checks if a variable exists in a data set.
4
- @details Returns 0 if the variable does NOT exist, and return the position of
5
- the var if it does.
6
- Usage:
4
+ @details Returns 0 if the variable does NOT exist, and the position of the var
5
+ if it does.
6
+ Usage:
7
7
 
8
- %put %mf_existvar(work.someds, somevar)
8
+ %put %mf_existvar(work.someds, somevar)
9
9
 
10
10
  @param [in] libds 2 part dataset or view reference
11
11
  @param [in] var variable name
@@ -5,18 +5,19 @@
5
5
 
6
6
  %put %mf_getfilesize(fpath=C:\temp\myfile.txt);
7
7
 
8
- or
8
+ or, provide a libds value as follows:
9
9
 
10
10
  data x;do x=1 to 100000;y=x;output;end;run;
11
11
  %put %mf_getfilesize(libds=work.x,format=yes);
12
12
 
13
- gives:
13
+ Which gives:
14
14
 
15
- 2mb
15
+ > 2mb
16
+
17
+ @param [in] fpath= Full path and filename. Provide this OR the libds value.
18
+ @param [in] libds= (0) Library.dataset value (assumes library is BASE engine)
19
+ @param [in] format= (NO) Set to yes to apply sizekmg. format
16
20
 
17
- @param fpath= full path and filename. Provide this OR the libds value.
18
- @param libds= library.dataset value (assumes library is BASE engine)
19
- @param format= set to yes to apply sizekmg. format
20
21
  @returns bytes
21
22
 
22
23
  @version 9.2
@@ -26,16 +27,32 @@
26
27
  %macro mf_getfilesize(fpath=,libds=0,format=NO
27
28
  )/*/STORE SOURCE*/;
28
29
 
30
+ %local rc fid fref bytes dsid lib vnum;
31
+
29
32
  %if &libds ne 0 %then %do;
30
- %let fpath=%sysfunc(pathname(%scan(&libds,1,.)))/%scan(&libds,2,.).sas7bdat;
33
+ %let libds=%upcase(&libds);
34
+ %if %index(&libds,.)=0 %then %let lib=WORK;
35
+ %else %let lib=%scan(&libds,1,.);
36
+ %let dsid=%sysfunc(open(
37
+ sashelp.vtable(where=(libname="&lib" and memname="%scan(&libds,-1,.)")
38
+ keep=libname memname filesize
39
+ )
40
+ ));
41
+ %if (&dsid ^= 0) %then %do;
42
+ %let vnum=%sysfunc(varnum(&dsid,FILESIZE));
43
+ %let rc=%sysfunc(fetch(&dsid));
44
+ %let bytes=%sysfunc(getvarn(&dsid,&vnum));
45
+ %let rc= %sysfunc(close(&dsid));
46
+ %end;
47
+ %else %put &sysmacroname: &libds could not be opened! %sysfunc(sysmsg());
48
+ %end;
49
+ %else %do;
50
+ %let rc=%sysfunc(filename(fref,&fpath));
51
+ %let fid=%sysfunc(fopen(&fref));
52
+ %let bytes=%sysfunc(finfo(&fid,File Size (bytes)));
53
+ %let rc=%sysfunc(fclose(&fid));
54
+ %let rc=%sysfunc(filename(fref));
31
55
  %end;
32
-
33
- %local rc fid fref bytes;
34
- %let rc=%sysfunc(filename(fref,&fpath));
35
- %let fid=%sysfunc(fopen(&fref));
36
- %let bytes=%sysfunc(finfo(&fid,File Size (bytes)));
37
- %let rc=%sysfunc(fclose(&fid));
38
- %let rc=%sysfunc(filename(fref));
39
56
 
40
57
  %if &format=NO %then %do;
41
58
  &bytes
@@ -30,7 +30,6 @@
30
30
 
31
31
  %local count_base count_extr i i2 extr_word base_word match outvar;
32
32
  %if %length(&str1)=0 or %length(&str2)=0 %then %do;
33
- %put %str(WARN)ING: empty string provided!;
34
33
  %put base string (str1)= &str1;
35
34
  %put compare string (str2) = &str2;
36
35
  %return;
@@ -3,6 +3,9 @@
3
3
  @brief Returns words that are in string 1 but not in string 2
4
4
  @details Compares two space separated strings and returns the words that are
5
5
  in the first but not in the second.
6
+
7
+ Note - case sensitive!
8
+
6
9
  Usage:
7
10
 
8
11
  %let x= %mf_wordsInStr1ButNotStr2(
@@ -13,10 +16,8 @@
13
16
  returns:
14
17
  > sss bram boo
15
18
 
16
- @param str1= string containing words to extract
17
- @param str2= used to compare with the extract string
18
-
19
- @warning CASE SENSITIVE!
19
+ @param [in] str1= string containing words to extract
20
+ @param [in] str2= used to compare with the extract string
20
21
 
21
22
  @version 9.2
22
23
  @author Allan Bowe
@@ -30,7 +31,6 @@
30
31
 
31
32
  %local count_base count_extr i i2 extr_word base_word match outvar;
32
33
  %if %length(&str1)=0 or %length(&str2)=0 %then %do;
33
- %put %str(WARN)ING: empty string provided!;
34
34
  %put base string (str1)= &str1;
35
35
  %put compare string (str2) = &str2;
36
36
  %return;
package/base/mp_abort.sas CHANGED
@@ -173,7 +173,8 @@
173
173
  if symexist('_debug') then debug=quote(trim(symget('_debug')));
174
174
  else debug='""';
175
175
  put '>>weboutBEGIN<<';
176
- put '{"START_DTTM" : "' "%sysfunc(datetime(),datetime20.3)" '"';
176
+ put '{"SYSDATE" : "' "&SYSDATE" '"';
177
+ put ',"SYSTIME" : "' "&SYSTIME" '"';
177
178
  put ',"sasjsAbort" : [{';
178
179
  put ' "MSG":' msg ;
179
180
  put ' ,"MAC": "' "&mac" '"}]';
@@ -202,7 +203,7 @@
202
203
  put ',"SYSVLONG" : ' sysvlong;
203
204
  syswarningtext=quote(trim(symget('syswarningtext')));
204
205
  put ",""SYSWARNINGTEXT"" : " syswarningtext;
205
- put ',"END_DTTM" : "' "%sysfunc(datetime(),datetime20.3)" '" ';
206
+ put ',"END_DTTM" : "' "%sysfunc(datetime(),E8601DT26.6)" '" ';
206
207
  put "}" @;
207
208
  put '>>weboutEND<<';
208
209
  run;
@@ -12,10 +12,6 @@
12
12
 
13
13
  %mp_assertdsobs(sashelp.class,test=ATMOST 20) %* pass if <21 obs present;
14
14
 
15
- <h4> SAS Macros </h4>
16
- @li mf_nobs.sas
17
- @li mp_abort.sas
18
-
19
15
 
20
16
  @param [in] inds input dataset to test for presence of observations
21
17
  @param [in] desc= (Testing observations) The user provided test description
@@ -33,6 +29,11 @@
33
29
  |---|---|---|
34
30
  |User Provided description|PASS|Dataset &inds has XX obs|
35
31
 
32
+ <h4> SAS Macros </h4>
33
+ @li mf_getuniquename.sas
34
+ @li mf_nobs.sas
35
+ @li mp_abort.sas
36
+
36
37
  <h4> Related Macros </h4>
37
38
  @li mp_assertcolvals.sas
38
39
  @li mp_assert.sas
@@ -49,9 +50,10 @@
49
50
  outds=work.test_results
50
51
  )/*/STORE SOURCE*/;
51
52
 
52
- %local nobs;
53
+ %local nobs ds;
53
54
  %let nobs=%mf_nobs(&inds);
54
55
  %let test=%upcase(&test);
56
+ %let ds=%mf_getuniquename(prefix=mp_assertdsobs);
55
57
 
56
58
  %if %substr(&test.xxxxx,1,6)=EQUALS %then %do;
57
59
  %let val=%scan(&test,2,%str( ));
@@ -84,7 +86,7 @@
84
86
  )
85
87
  %end;
86
88
 
87
- data;
89
+ data &ds;
88
90
  length test_description $256 test_result $4 test_comments $256;
89
91
  test_description=symget('desc');
90
92
  test_result='FAIL';
@@ -110,9 +112,6 @@
110
112
  %end;
111
113
  run;
112
114
 
113
- %local ds;
114
- %let ds=&syslast;
115
-
116
115
  proc append base=&outds data=&ds;
117
116
  run;
118
117
 
@@ -1,18 +1,25 @@
1
1
  /**
2
2
  @file
3
3
  @brief Used to capture scope leakage of macro variables
4
- @details A common 'difficult to detect' bug in macros is where a nested
5
- macro over-writes variables in a higher level macro.
4
+ @details
6
5
 
7
- This assertion takes a snapshot of the macro variables before and after
8
- a macro invocation. This makes it easy to detect whether any macro
9
- variables were modified or changed.
6
+ A common 'difficult to detect' bug in macros is where a nested macro
7
+ over-writes variables in a higher level macro.
10
8
 
11
- Currently, the macro only checks for global scope variables. In the future
12
- it may be extended to work at multiple levels of nesting.
9
+ This assertion takes a snapshot of the macro variables before and after
10
+ a macro invocation. Differences are captured in the `&outds` table. This
11
+ makes it easy to detect whether any macro variables were modified or
12
+ changed.
13
13
 
14
- If you would like this feature, feel free to contribute / raise an issue /
15
- engage the SASjs team directly.
14
+ The following variables are NOT tested (as they are known, global variables
15
+ used in SASjs):
16
+
17
+ @li &sasjs_prefix._FUNCTIONS
18
+
19
+ Global variables are initialised in mp_init.sas - which will also trigger
20
+ "strict mode" in your SAS session. Whilst this is a default in SASjs
21
+ produced apps, if you prefer not to use this mode, simply instantiate the
22
+ following variable to prevent the macro from running: `SASJS_PREFIX`
16
23
 
17
24
  Example usage:
18
25
 
@@ -24,12 +31,17 @@
24
31
  desc=Checking macro variables against previous snapshot
25
32
  )
26
33
 
34
+ This macro is designed to work alongside `sasjs test` - for more information
35
+ about this facility, visit [cli.sasjs.io/test](https://cli.sasjs.io/test).
36
+
27
37
  @param [in] action (SNAPSHOT) The action to take. Valid values:
28
38
  @li SNAPSHOT - take a copy of the current macro variables
29
39
  @li COMPARE - compare the current macro variables against previous values
30
40
  @param [in] scope= (GLOBAL) The scope of the variables to be checked. This
31
41
  corresponds to the values in the SCOPE column in `sashelp.vmacro`.
32
- @param [in] desc= (Testing variable scope) The user provided test description
42
+ @param [in] desc= (Testing scope leakage) The user provided test description
43
+ @param [in] ignorelist= Provide a list of macro variable names to ignore from
44
+ the comparison
33
45
  @param [in,out] scopeds= (work.mp_assertscope) The dataset to contain the
34
46
  scope snapshot
35
47
  @param [out] outds= (work.test_results) The output dataset to contain the
@@ -38,6 +50,10 @@
38
50
  |---|---|---|
39
51
  |User Provided description|PASS|No out of scope variables created or modified|
40
52
 
53
+ <h4> SAS Macros </h4>
54
+ @li mf_getquotedstr.sas
55
+ @li mp_init.sas
56
+
41
57
  <h4> Related Macros </h4>
42
58
  @li mp_assert.sas
43
59
  @li mp_assertcols.sas
@@ -51,12 +67,21 @@
51
67
  **/
52
68
 
53
69
  %macro mp_assertscope(action,
54
- desc=0,
70
+ desc=Testing Scope Leakage,
55
71
  scope=GLOBAL,
56
72
  scopeds=work.mp_assertscope,
73
+ ignorelist=,
57
74
  outds=work.test_results
58
75
  )/*/STORE SOURCE*/;
59
- %local ds test_result test_comments del add mod;
76
+ %local ds test_result test_comments del add mod ilist;
77
+ %let ilist=%upcase(&sasjs_prefix._FUNCTIONS &ignorelist);
78
+
79
+ /**
80
+ * this sets up the global vars, it will also enter STRICT mode. If this
81
+ * behaviour is not desired, simply initiate the following global macro
82
+ * variable to prevent the macro from running: SASJS_PREFIX
83
+ */
84
+ %mp_init()
60
85
 
61
86
  /* get current variables */
62
87
  %if &action=SNAPSHOT %then %do;
@@ -64,7 +89,7 @@
64
89
  create table &scopeds as
65
90
  select name,offset,value
66
91
  from dictionary.macros
67
- where scope="&scope"
92
+ where scope="&scope" and name not in (%mf_getquotedstr(&ilist))
68
93
  order by name,offset;
69
94
  %end;
70
95
  %else %if &action=COMPARE %then %do;
@@ -73,7 +98,7 @@
73
98
  create table _data_ as
74
99
  select name,offset,value
75
100
  from dictionary.macros
76
- where scope="&scope"
101
+ where scope="&scope" and name not in (%mf_getquotedstr(&ilist))
77
102
  order by name,offset;
78
103
 
79
104
  %let ds=&syslast;
@@ -10,6 +10,8 @@
10
10
  %mp_coretable(LOCKTABLE,libds=work.locktable)
11
11
 
12
12
  @param [in] table_ref The type of table to create. Example values:
13
+ @li DIFFTABLE - Used to store changes to tables. Used by mp_storediffs.sas
14
+ and mp_stackdiffs.sas
13
15
  @li FILTER_DETAIL - For storing detailed filter values. Used by
14
16
  mp_filterstore.sas.
15
17
  @li FILTER_SUMMARY - For storing summary filter values. Used by
@@ -25,6 +27,8 @@
25
27
  @li mp_filterstore.sas
26
28
  @li mp_lockanytable.sas
27
29
  @li mp_retainedkey.sas
30
+ @li mp_storediffs.sas
31
+ @li mp_stackdiffs.sas
28
32
 
29
33
  @version 9.2
30
34
  @author Allan Bowe
@@ -36,7 +40,29 @@
36
40
  %local outds ;
37
41
  %let outds=%sysfunc(ifc(&libds=0,_data_,&libds));
38
42
  proc sql;
39
- %if &table_ref=LOCKTABLE %then %do;
43
+ %if &table_ref=DIFFTABLE %then %do;
44
+ create table &outds(
45
+ load_ref char(36) label='unique load reference',
46
+ processed_dttm num format=E8601DT26.6 label='Processed at timestamp',
47
+ libref char(8) label='Library Reference (8 chars)',
48
+ dsn char(32) label='Dataset Name (32 chars)',
49
+ key_hash char(32) label=
50
+ 'MD5 Hash of primary key values (pipe seperated)',
51
+ move_type char(1) label='Either (A)ppended, (D)eleted or (M)odified',
52
+ is_pk num label='Is Primary Key Field? (1/0)',
53
+ is_diff num label=
54
+ 'Did value change? (1/0/-1). Always -1 for appends and deletes.',
55
+ tgtvar_type char(1) label='Either (C)haracter or (N)umeric',
56
+ tgtvar_nm char(32) label='Target variable name (32 chars)',
57
+ oldval_num num format=best32. label='Old (numeric) value',
58
+ newval_num num format=best32. label='New (numeric) value',
59
+ oldval_char char(32765) label='Old (character) value',
60
+ newval_char char(32765) label='New (character) value',
61
+ constraint pk_mpe_audit
62
+ primary key(load_ref,libref,dsn,key_hash,tgtvar_nm)
63
+ );
64
+ %end;
65
+ %else %if &table_ref=LOCKTABLE %then %do;
40
66
  create table &outds(
41
67
  lock_lib char(8),
42
68
  lock_ds char(32),
@@ -24,20 +24,22 @@ Usage:
24
24
  %webout(OBJ,example2) * Object format, easier to work with ;
25
25
  %webout(CLOSE)
26
26
  ;;;;
27
- %mp_createwebservice(path=/Public/app/common,name=appInit,code=ft15f001,replace=YES)
27
+ %mp_createwebservice(path=/Public/app/common,name=appInit,replace=YES)
28
28
 
29
29
  <h4> SAS Macros </h4>
30
30
  @li mf_getplatform.sas
31
31
  @li mm_createwebservice.sas
32
32
  @li mv_createwebservice.sas
33
33
 
34
- @param path= The full folder path where the service will be created
35
- @param name= Service name. Avoid spaces.
36
- @param desc= The description of the service (optional)
37
- @param precode= Space separated list of filerefs, pointing to the code that
38
- needs to be attached to the beginning of the service (optional)
39
- @param code= Space seperated fileref(s) of the actual code to be added
40
- @param replace= select YES to replace any existing service in that location
34
+ @param [in,out] path= The full folder path where the service will be created
35
+ @param [in,out] name= Service name. Avoid spaces.
36
+ @param [in] desc= The description of the service (optional)
37
+ @param [in] precode= Space separated list of filerefs, pointing to the code
38
+ that needs to be attached to the beginning of the service (optional)
39
+ @param [in] code= (ft15f001) Space seperated fileref(s) of the actual code to
40
+ be added
41
+ @param [in] replace= (YES) Select YES to replace any existing service in that
42
+ location
41
43
 
42
44
 
43
45
  @version 9.2
@@ -49,10 +49,6 @@
49
49
  ,mac=&sysmacroname
50
50
  ,msg=%str(the BASEDS variable must be provided)
51
51
  )
52
- %mp_abort(iftrue=( &baseds=0 )
53
- ,mac=&sysmacroname
54
- ,msg=%str(the BASEDS variable must be provided)
55
- )
56
52
  %mp_abort(iftrue=( %mf_existds(&baseds)=0 )
57
53
  ,mac=&sysmacroname
58
54
  ,msg=%str(the BASEDS dataset (&baseds) needs to be assigned, and to exist)
@@ -51,6 +51,7 @@
51
51
  data _null_;
52
52
  set work.&tempds end=last;
53
53
  length fref $8;
54
+ fref='';
54
55
  rc=filename(fref,filepath);
55
56
  rc=fdelete(fref);
56
57
  if rc then do;
@@ -82,7 +82,8 @@ data &out_ds(compress=no
82
82
  keep=file_or_folder filepath filename ext msg directory level
83
83
  );
84
84
  length directory filepath $500 fref fref2 $8 file_or_folder $6 filename $80
85
- ext $20 msg $200;
85
+ ext $20 msg $200 foption $16;
86
+ if _n_=1 then call missing(of _all_);
86
87
  retain level &level;
87
88
  %if &fref=0 %then %do;
88
89
  rc = filename(fref, "&path");
@@ -93,7 +94,13 @@ data &out_ds(compress=no
93
94
  %end;
94
95
  if rc = 0 then do;
95
96
  did = dopen(fref);
96
- directory=dinfo(did,'Directory');
97
+ /* attribute is OS-dependent - could be "Directory" or "Directory Name" */
98
+ numopts=doptnum(did);
99
+ do i=1 to numopts;
100
+ foption=doptname(did,i);
101
+ if foption=:'Directory' then i=numopts;
102
+ end;
103
+ directory=dinfo(did,foption);
97
104
  if did=0 then do;
98
105
  putlog "NOTE: This directory is empty - " directory;
99
106
  msg=sysmsg();
@@ -1,23 +1,57 @@
1
1
  /**
2
2
  @file
3
- @brief Export a dataset to a CSV file
4
- @details Export to a file or a fileref
3
+ @brief Export a dataset to a CSV file WITH leading blanks
4
+ @details Export a dataset to a file or fileref, retaining leading blanks.
5
+
5
6
  Usage:
6
7
 
7
8
  %mp_ds2csv(sashelp.class,outref="%sysfunc(pathname(work))/file.csv")
8
9
 
9
- @param ds The dataset to be exported
10
- @param outfile= The output filename - should be quoted.
11
- @param outref= The output fileref (takes precedence if provided)
12
- @param outencoding= The output encoding to use (unquoted)
10
+ Why use mp_ds2csv over, say, proc export?
11
+
12
+ 1. Ability to retain leading blanks (this is a major one)
13
+ 2. Control the header format
14
+ 3. Simple one-liner
15
+
16
+ @param [in] ds The dataset to be exported
17
+ @param [in] dlm= (COMMA) The delimeter to apply. For SASJS, will always be
18
+ COMMA. Supported values:
19
+ @li COMMA
20
+ @li SEMICOLON
21
+ @param [in] headerformat= (LABEL) The format to use for the header section.
22
+ Valid values:
23
+ @li LABEL - Use the variable label (or name, if blank)
24
+ @li NAME - Use the variable name
25
+ @li SASJS - Used to create sasjs-formatted input CSVs, eg for use in
26
+ mp_testservice.sas
27
+ @param [out] outfile= The output filename - should be quoted.
28
+ @param [out] outref= (0) The output fileref (takes precedence if provided)
29
+ @param [in] outencoding= (0) The output encoding to use (unquoted)
30
+ @param [in] termstr= (CRLF) The line seperator to use. For SASJS, will
31
+ always be CRLF. Valid values:
32
+ @li CRLF
33
+ @li LF
34
+
35
+ <h4> SAS Macros </h4>
36
+ @li mf_getuniquename.sas
37
+ @li mf_getvarlist.sas
38
+ @li mf_getvartype.sas
13
39
 
14
40
  @version 9.2
15
41
  @author Allan Bowe (credit mjsq)
16
42
  **/
17
43
 
18
- %macro mp_ds2csv(ds, outref=0, outfile=, outencoding=0
44
+ %macro mp_ds2csv(ds
45
+ ,dlm=COMMA
46
+ ,outref=0
47
+ ,outfile=
48
+ ,outencoding=0
49
+ ,headerformat=LABEL
50
+ ,termstr=CRLF
19
51
  )/*/STORE SOURCE*/;
20
52
 
53
+ %local outloc delim i varlist var vcnt vat dsv vcom vmiss;
54
+
21
55
  %if not %sysfunc(exist(&ds)) %then %do;
22
56
  %put %str(WARN)ING: &ds does not exist;
23
57
  %return;
@@ -28,31 +62,102 @@
28
62
  %if &outencoding=0 %then %let outencoding=;
29
63
  %else %let outencoding=encoding="&outencoding";
30
64
 
31
- %local outloc;
32
65
  %if &outref=0 %then %let outloc=&outfile;
33
66
  %else %let outloc=&outref;
34
67
 
68
+ %if &headerformat=SASJS %then %do;
69
+ %let delim=",";
70
+ %let termstr=CRLF;
71
+ %end;
72
+ %else %if &dlm=COMMA %then %let delim=",";
73
+ %else %let delim=";";
74
+
35
75
  /* credit to mjsq - https://stackoverflow.com/a/55642267 */
36
76
 
37
77
  /* first get headers */
38
78
  data _null_;
39
- file &outloc dlm=',' dsd &outencoding lrecl=32767;
40
- length header $ 2000;
79
+ file &outloc &outencoding lrecl=32767 termstr=&termstr;
80
+ length header $ 2000 varnm $32 dlm $1;
41
81
  dsid=open("&ds.","i");
42
82
  num=attrn(dsid,"nvars");
83
+ dlm=&delim;
43
84
  do i=1 to num;
44
- header = cats(coalescec(varlabel(dsid,i),varname(dsid,i)));
85
+ varnm=upcase(varname(dsid,i));
86
+ if i=num then dlm='';
87
+ %if &headerformat=NAME %then %do;
88
+ header=cats(varnm,dlm);
89
+ %end;
90
+ %else %if &headerformat=LABEL %then %do;
91
+ header = cats(coalescec(varlabel(dsid,i),varnm),dlm);
92
+ %end;
93
+ %else %if &headerformat=SASJS %then %do;
94
+ if vartype(dsid,i)='C' then header=cats(varnm,':$char',varlen(dsid,i),'.');
95
+ else header=cats(varnm,':best.');
96
+ %end;
97
+ %else %do;
98
+ %put &sysmacroname: Invalid headerformat value (&headerformat);
99
+ %return;
100
+ %end;
45
101
  put header @;
46
102
  end;
47
103
  rc=close(dsid);
48
104
  run;
49
105
 
106
+ %let varlist=%mf_getvarlist(&ds);
107
+ %let vcnt=%sysfunc(countw(&varlist));
108
+
109
+ /**
110
+ * The $quote modifier (without a width) will take the length from the variable
111
+ * and increase by two. However this will lead to truncation where the value
112
+ * contains double quotes (which are doubled up). To get around this, scan the
113
+ * data to see the max number of double quotes, so that the appropriate width
114
+ * can be applied in the subsequent step.
115
+ */
116
+ data _null_;
117
+ set &ds end=last;
118
+ %do i=1 %to &vcnt;
119
+ %let var=%scan(&varlist,&i);
120
+ %if %mf_getvartype(&ds,&var)=C %then %do;
121
+ %let dsv1=%mf_getuniquename(prefix=csvcol1_);
122
+ %let dsv2=%mf_getuniquename(prefix=csvcol2_);
123
+ retain &dsv1 0;
124
+ &dsv2=length(&var)+countc(&var,'"');
125
+ if &dsv2>&dsv1 then &dsv1=&dsv2;
126
+ if last then call symputx(
127
+ "vlen&i"
128
+ /* should be no shorter than varlen, and no longer than 32767 */
129
+ ,cats('$quote',min(&dsv1+2,32767),'.')
130
+ ,'l'
131
+ );
132
+ %end;
133
+ %end;
134
+
135
+ %let vat=@;
136
+ %let vcom=&delim;
137
+ %let vmiss=%mf_getuniquename(prefix=csvcol3_);
50
138
  /* next, export data */
51
139
  data _null_;
52
140
  set &ds.;
53
- file &outloc mod dlm=',' dsd &outencoding lrecl=32767;
54
- put (_all_) (+0);
141
+ file &outloc mod dlm=&delim dsd &outencoding lrecl=32767 termstr=&termstr;
142
+ if _n_=1 then &vmiss=' ';
143
+ %do i=1 %to &vcnt;
144
+ %let var=%scan(&varlist,&i);
145
+ %if &i=&vcnt %then %do;
146
+ %let vat=;
147
+ %let vcom=;
148
+ %end;
149
+ %if %mf_getvartype(&ds,&var)=N %then %do;
150
+ /* must use period - in order to work in both 9.4 and Viya 3.5 */
151
+ if missing(&var) and &var ne %sysfunc(getoption(MISSING)) then do;
152
+ &vmiss=cats('.',&var);
153
+ put &vmiss &vat;
154
+ end;
155
+ else put &var &vat;
156
+ %end;
157
+ %else %do;
158
+ put &var &&vlen&i &vcom &vat;
159
+ %end;
160
+ %end;
55
161
  run;
56
162
 
57
-
58
163
  %mend mp_ds2csv;