%macro doset( Revdate=%str(4/28/2015 11:29:32 AM), /* This macro is invoked once for each SAS dataset in a data library. It creates (or updates an existing) entry in the datasets dataset describing a single dataset in that data lib. It can also be used to create a template module, which is a pseudo-entry that serves as a model to be used when created regular dataset descriptive entries (observations). For complete documentation and examples of how to code the parms see the Word doc Summary of Coding Metadata Varaibles Via the doset Macro in the P:\mcdc directory at OSEDA. See also the datasets_attribs.sas module (included by this module when initializing) in the /pub/sascode directory. That module specified the lengths of the SAS variables correpsonding to the parms of the same name used to assign them values. Additional comments there as well. Only documentation is the comments there and here. Originally coded circa 2002 by John Blodgett, Missouri Census Data Center. Adding fixindex parm to insure the metaset has a valid index, 10-09. Added code to recognize todolist=all . 1-16-13. Added code to infer LatestYear from Years 3-31-15. Modified code when doing keyed read of the template data set so that we avoid using a variable interval starting with geouniv because it was causing us to lose description which got moved up in 2015 data set restructure. */ mode=, /* Values are initialize, append and update. Blank says to assign update or append depending on whether the observation already exists. */ libname=&libnameg., /* libref used to create/access. REQUIRED. Program will determine a number of metadata values by "looking up" the physical path associated with this libref. It MUST BE DEFINED prior to invoking the macro. Note that default value is reference to a global macro variable named libnameg. */ filetype=&libname, /* must specify filetype if and only if different from libname */ memname=, /* the member name (SAS dataset name, view name, etc. REQUIRED. So the dataset is referenced as &libname..&memname . Obviously, this member MUST EXIST */ memlabel=, /* if a value is specified then it will be used to specify a new label for the dataset (added using Proc Datasets / modify.) */ metaset=&libname..datasets, /* This is where the output metadata goes or is read from (for mode=append we add to the end and for mode=update we modify the existing dataset unless metasetout is specified. */ metasetout=&metaset, /* when mode=update you can specify a different output dataset. Use this to be careful when you are not sure what you are doing or want to test something. */ template=, /* Names a previously-defined special template observation (usually but not necessariy -- you can also use a reference to a non-template entry) in the datasets dataset. The value will typically begins with "_template". The program will create default values for the current dataset entry based upon the values specified in the template set. The template values will be converted using resolve(translate(template_value,'&','~')). So when building the template the tilde character is used when specifying values to indicate what you would normally use the ampersand for (to indicate a macro variable reference). This prevents there being resolution when the template values are stored but instead allows it to happen when the template is referenced. Template datasets must have names that begin with "_template". */ GeoUniv=, /* Geographic Universe */ Universe=, /* Alias for GeoUniv */ SortPrio=, /* Sort priority code, single character. Defaults are assigned based on value of geouniv as follows: Missouri ==> 1 UnitedStates ==> 3 Kansas | Illinois ==> 5 (otherwise) ==> 7 */ Units=, /* Observation units. Such as State, County, Tract, ZIP, etc. Use singular. */ Unit=, /* Alias for Units */ Years=, /* One or more 4-digit years in descending order, OR, a numeric interval with dashes (1989-2001) */ Year=, /* Alias for Years */ KeyWords=, /* Not really doing anything with these yet. But has potential for future search apps.*/ description=, /* Detailed description of the data set */ KeyVars=, /* This and the following 3 parms are passed on to the %genkeys macro for generating an html-format report summarizing values of key variables for the dataset. Its a judgement call as to what the keyvars should be. */ KeyQuals=, /* Key qualifiers. See the genkeys macro for description */ KeyFmats=, /* SAS permanent format codes used to provide value labels for value of the key variables. See genkeys macro */ KeyIdvars=, /* Passed as value of idvars parm to genkeys. */ Means=, /* List of variables that are not simply aggregatable - they require being handled as weighted averages when aggregating (per the agg macro). See MeanWts parm. */ Mweights=, /* List of weight vars corresponding to Means. The values of these 2 twin parms are intended for use with the agg macro (in /pub/sas/macros/agg.sas) */ UsageNotes=, /* Special notes regarding the set. */ DataSource=, /* Source of the data */ SortedBy=, /* Optional list of variables by which the set is sorted. */ IndexedBy=, /* List of simple and compound indices, separated by vertical bars. E.g. Logrecno | slgeo=(SumLev Geocode) */ CreatePgm=, /* name of the SAS program that created it. Without the .sas extension. Will be assumed to be in the Tools subdirectory. (Normally the value of &pgm in our scheme) */ CreateLib=, /* The path of the directory where the Create program was run. If not specified then the program will see if the file exists in the &datadir/&filetype/Tools directory and, if it does, it will assign the special value "Tools" to indicate the default location. */ Subtype=, /* Sub-filetype */ contactEmail=riceg@missouri.edu, /* e-mail address of person responsible for responding to questions */ contactName=Glenn Rice, /* name of contact person */ SetGroup=, VarSet=, /* If there is a Variables dataset that describes variables in this dataset then this parm will point to it. If a 1-level name is specified then the first level is assumed to be the value of libname */ urlmeta=, /* URL for a page containing metadata regarding this set. */ filters=, /* Not sure just yet how these will work. */ fixindex=0, /* specify fixindex=1 in order to do an elimdups and redefine of the data sets key before attempting to process the update */ debug=0); %local null; %let null=%str(); %local errmsg; %global todo; %*---this global parm reference added 8/23/2005. Allow using this parm to indicate which of perhaps very many invocations of this macro are actually supposed to be run. If todo is not null then each memname is "looked up" in the "to do list" to see if it is to be run.----; %if %superq(todolist) ne %str() %then %let todo=&todolist; %if %superq(todo) ne %str() and %superq(todolist) ne %str(all) and &mode ne initialize %then %do; %if %index(&todo,&memname) = 0 %then %do; %put ***Not executed because &memname is not on todo list*** ; %goto endmac; %end; %end; %local dset; %let dset=&libname..&memname; %let mode=%lowcase(&mode); %if &debug %then %put doset macro, revised &revdate, begin execution with mode=&mode libname=&libname memname=&memname; %*---Process aliases-----; %if %nrbquote(&unit) ne &null %then %let units=&unit; %if %nrbquote(&year) ne &null %then %let years=&year; %if %index(&metaset,%str(.))=0 %then %do; %*--when the libname parm is assigned using the libnameg global parm then the default metasets does not get assigned properly -- it loses the period separating the libref and the member name. So this code checks for that and inserts the period.--; %local _ix; %let _ix=%index(%lowcase(&metaset),datasets); %if _ix gt 1 %then %let metaset=%substr(&metaset,1,%eval(&_ix-1)).datasets; %end; %if &mode=initialize %then %do; %let memname=datasets; %let dset=&libname..datasets; %if %sysfunc(exist(&metaset))=1 %then %let errmsg=%str(Initialize mode specified but &metaset already exists); %else %goto _init; %end; %local template_flag; %if %substr(&memname.xxxxxxxxx,1,9) eq _template %then %let template_flag=1; %else %let template_flag=0; %if &libname eq &null or &memname eq &null %then %let errmsg=%str(Required parameters libname, memname not both specified); %else %if not &template_flag and %sysfunc(exist(&dset))=0 and %sysfunc(exist(&dset,view))=0 %then %let errmsg=%str(Specified input dataset, &dset, does not exist); %else %if (&mode ne initialize and %sysfunc(exist(&metaset))=0) %then %let errmsg=%str(Specified meta dataset, &metaset, does not exist); %if %superq(errmsg) ne &null %then %do; %*<======================; %let errword_=ERROR; %put *****&errword_.: Detected by doset macro: ; %put &errmsg; %put %str( ) *****No output will be generated*****; %goto endmac; %end; %if &fixindex %then %do; %*--new, 10-27-09. Having problems with corrupted datasets with dup obs and missing indices. So if user tells us to fix the index we do it here. Note that we begin by eliminating any duplicate observations. --; proc sort data=&metaset out=_tempmeta; by libname memname modified; run; data &metaset; set _tempmeta; by libname memname; if last.memname; *--most recently modified one kept-; run; proc datasets library=&libname nolist; modify datasets; index delete memname dataset; index create memname; index create dataset=(libname memname)/unique; %put *****Indices have been replaced on &libname..datasets *****; %end; %if &mode eq &null %then %do; %*---assign mode as either append or update depending on whether the dataset already has an entry on the metadata set--; data _null_; libname="&libname"; memname="&memname"; *set &metaset key=dataset; set &metaset ; if _iorc_=0 then mode='update'; else do; _error_=0; mode='append'; end; call symput('mode',mode); put 'Mode has been assigned as ' mode; stop; run; %end; %_init: %if &mode=initialize %then %do; data &metaset(label="Meta data re datasets in this data library"); %include sascode('code/datasets_attribs.sas'); put / '***The notes regarding uninitialized variables in this step can be safely ignored***'/; stop; run; proc datasets lib=%scan(&metaset,1) nolist; modify %scan(&metaset,2); index create dataset=(libname memname) / unique; quit; %goto endmac; %end; %*--if we get here we have data to process------------------------------------; %if not &template_flag %then %do; %let editmemlabel=1; proc contents data=&dset out=contents(drop=sortedby) noprint; run; %end; %else %let editmemlabel=0; data _&memname; %*---Create the metadata for this one dataset, libname.memname --; %*include sascode('code/datasets_attribs.sas'); if 0 then set &metaset; %*<---does what commented-out include stmt does but does it faster with less log clutter. It does not really read any data from &metaset but it does establish the PDV with variable characteristics per the set we want to update.-; retain _newfirst '0' Nlabels 0; length _errmsg $512; %if not &template_flag %then %do; set contents end=last; Nvars+1; Obslen+length; if label ne ' ' then Nlabels+1; if not last then delete; *---We only output a single observation describing the dataset---; memtype=memtype; Nidx=idxcount; engine=engine; memlabel=memlabel; if "&memlabel" ne " " and "&memlabel" ne memlabel then do; memlabel="&memlabel"; call symput('editmemlabel','1'); end; else call symput('editmemlabel','0'); Nobs=nobs; if nobs then Kbytes= round (obslen*nobs*.001); if upcase(compress)="NO" then compressed='n'; else compressed='y'; Created=crdate; Modified=modate; libpath=pathname("&libname"); if libpath=" " then do; _errmsg="Unable to assign libpath"; goto flagerr; end; call symput('libpath',trim(libpath)); _nlvls=length(libpath) - length (compress(libpath,'/')); *--counts the slashes-; if _nlvls ge 3 then do; DataDir='/'||trim(scan(libpath,1,'/'))||'/'||trim(scan(libpath,2,'/')); Filetype=scan(libpath,3,'/'); if filetype ne "&filetype" then do; _errmsg="Value of filetype parm (&filetype) is not the same as "|| "3rd directory level of the path (" ||trim(libpath)|| ") associated with &libname data library. "; link flagerr; end; if _nlvls ge 4 then do; SubDir=substr(libpath,length(DataDir)+length(filetype)+ 3); put SubDir=; end; end; *--_nlvls ge 3 do--; else put '***Note: Less than 3 levels for libpath found. DataDir, Filetype and SubDir will ' 'not be assigned****' / libpath=; length _fileext $8; if Memtype='DATA' then if engine in('V8','V9') then _fileext='sas7bdat'; else if engine='V6' then _fileext='ssd01'; else _fileext='????????'; if Memtype='VIEW' then if engine in('SQLVIEW','SASDSV') then _fileext='sas7bvew'; else _fileext='ssv01'; Filename=trim(lowcase(memname))||'.'||_fileext; %*--end processing when it is NOT a template---; %end; %else %do; %*--when we ARE processing a template module--; libpath=pathname("&libname"); if libpath=" " then do; _errmsg="Unable to assign libpath"; goto flagerr; end; call symput('libpath',trim(libpath)); %end; libname="&libname"; memname="&memname"; memlabel="&memlabel"; %if %superq(universe) ne %str() %then %let GeoUniv=&universe; *---Ready to see if we have a template entry specified and, if so, read the obs for that template and bring those metavar values in as defaults before we start assigning values from the parameters coded--; %if &template ne &null %then %do; _savelib=libname; _savemem=memname; %let templmem=%scan(&template,2,'.'); %if &templmem eq &null %then %do; memname="&template"; *<---and libname stays as it is---; %end; %else %do; libname=scan("&template",1,'.'); memname="&templmem"; %end; *----We change the first var of the double-dash list from GeoUniv to Filename to allow for change in var order 2015-; *set &metaset(keep=libname memname memlabel filename --URLMeta rename=(memlabel=memlabref)) key=dataset; *--only keep the non-automated variables--; set &metaset(keep=libname memname memlabel filename --URLMeta rename=(memlabel=memlabref)); *--only keep the non-automated variables--; if _iorc_ then do; _errmsg="Unable to find an obs for template (&template) in the " || "metaset (&metaset) dataset. "; goto flagerr; end; if sortprio='X' then sortprio=' '; *---3-23-10: do not allow inheriting a value of X (delete-this-obs flag)--; *-----Resolve global variables references specified on template dataset.-----; if "&description"=" " then description=resolve(translate(description,'&','~')); else if "&description"=:'+' then description=trim(resolve(translate(description,'&','~')))|| " "|| substr("&description",2); else description="&description"; ***if &debug then put description= ; if "&usagenotes"=" " then usagenotes=resolve(translate(usagenotes,'&','~')); else if "&usagenotes"=:'+' then usagenotes=trim(resolve(translate(usagenotes,'&','~')))|| " "||substr("&usagenotes",2); else if "&usagenotes"=:'-' then usagenotes=trim(substr("&usagenotes",2))||' '|| trim(resolve(translate(usagenotes,'&','~'))); else usagenotes="&usagenotes"; UsageNotes=translate(UsageNotes,'~','`'); *--we use backquotes as literal tildes in the usage notes only; if "&KeyWords"=" " then KeyWords=resolve(translate(KeyWords,'&','~')); else if "&KeyWords"=:'+' then KeyWords=trim(resolve(translate(KeyWords,'&','~')))|| " &KeyWords"; if "&memlabel"=" " and memlabref ne ' ' then do; memlabel=resolve(translate(memlabref,'&','~')); call symput('editmemlabel','1'); call symput('memlabel',trim(memlabel)); *<--new 12-14-04--; end; if "&geouniv"=" " then geouniv=resolve(translate(geouniv,'&','~')); if "&units"=" " then units=resolve(translate(units,'&','~')); if "&years"=" " then years=resolve(translate(years,'&','~')); if "&KeyVars"=" " then KeyVars=resolve(translate(KeyVars,'&','~')); if "&KeyFmats"=" " then KeyFmats=resolve(translate(KeyFmats,'&','~')); if "&KeyQuals"=" " then KeyQuals=resolve(translate(KeyQuals,'&','~')); if "&DataSource"=" " then DataSource=resolve(translate(DataSource,'&','~')); if "&SortedBy"=" " then SortedBy=resolve(translate(SortedBy,'&','~')); if "&createpgm"=" " then createpgm=resolve(translate(createpgm,'&','~')); if "&subtype"=" " then subtype=resolve(translate(subtype,'&','~')); if "&SetGroup"=" " then SetGroup=resolve(translate(SetGroup,'&','~')); if "&varset"=" " then varset=resolve(translate(varset,'&','~')); if "&urlmeta"=" " then urlmeta=resolve(translate(urlmeta,'&','~')); ***if "&filters"=" " then filters=resolve(translate(filters,'&','~')); *--restore values of id vars--; libname=_savelib; memname=_savemem; %if &debug %then %put ***Template lookup processing complete***; %end; %*--code to process template dataset reference---------------------; %*----Assign variables from parm values. We check for null values because we do not want to replace values inherited from the template with unspecified parm vars---------; %if &debug %then %put ***Assignments proceeding***; if "&geouniv" ne " " then GeoUniv="&geouniv"; if "&SortPrio" ne " " then SortPrio="&sortprio"; else if SortPrio='X' then SortPrio=' '; *-cannot inherit an X value-; if SortPrio=" " and not (memname=:'_template') then select(GeoUniv); when("Missouri","MISSOURI") SortPrio="1"; when("UnitedStates","United_States","United States") SortPrio="3"; when ("Illinois","Kansas","ILLINOIS","KANSAS") SortPrio="5"; otherwise SortPrio="7"; end; if "&units" ne " " then Units="&units"; if "&years" ne " " then Years="&Years"; *--New code added 3-31-15 --; if years ne " " then do; if length(years)=4 then LatestYear=Years; else do; length _lastwd $4; _lastwd=scan(years,-1,' ,-'); drop _lastwd; if length(_lastwd)=4 and verify(_lastwd,'1234567890')=0 then LatestYear=_lastwd; end; end; UsageNotes=translate(UsageNotes,'~','`'); *--we use backquotes as literal tildes in the usage notes only; if "&keywords" ne " " then KeyWords="&keywords"; %*---description and usagenotes parms are processed above when a template is being referenced, to check for a beginning "+" which indicates appending value to template value. Otherwise process the parm values here. --; %if &template eq &null %then %do; if "&description" ne " " then Description="&description"; if "&usagenotes" ne " " then UsageNotes="&usagenotes"; %end; if "&keyvars" ne " " then do; KeyVars="&keyvars"; KeyQuals="&keyquals"; KeyFmats="&keyfmats"; KeyIdvars="&keyidvars"; end; if "&means" ne " " then Means="&means"; if "&mweights" ne " " then Mweights="&mweights"; if "&datasource" ne " " then DataSource="&datasource"; if "&sortedby" ne " " then SortedBy="&sortedby"; if "&indexedby" ne " " then IndexedBy="&indexedby"; if "&createpgm" ne " " then CreatePgm="&createpgm"; if CreatePgm=" " and not ("&pgm"=:"invoke_dosets" or "&pgm"=" ") then CreatePgm="&pgm"; if "&createlib" ne " " then CreateLib="&Createlib"; if CreateLib =" " and CreatePgm ne " " then do; length _trylib $96 _tryfile $128; _trylib=trim(datadir)||'/'||trim(filetype)||"/Tools"; _tryfile=trim(_trylib)||"/"||trim(CreatePgm)||".sas"; if fileexist(_tryfile) then CreateLib=_trylib; if &debug then put createlib= datadir= filetype= _tryfile= CreateLib=; end; if "&subtype" ne " " then Subtype="&subtype"; if "&contactname" ne " " then contactName="&contactname"; if "&contactEmail" ne " " then contactEmail="&contactemail"; if "&setgroup" ne " " then SetGroup="&setgroup"; if "&varset" ne " " then VarSet="&varset"; if libpath ne " " and datadir="/pub/data" then do; URLdirect="https://mcdc.missouri.edu" ||trim(substr(libpath,5))||'/'||filename; end; else do; URLdirect=' '; end; if "&urlmeta" ne " " then URLmeta="&urlmeta"; ***If "&filters" ne " " then filters="&filters"; if "&template" ne " " then refset="&template"; output; retain _newlast 0; drop _newfirst -- _newlast; *--So all vars that are "new" (not on the meta dataset) are dropped on this dataset.--; stop; flagerr: put /'********Error detected -- no metadata output will be generated. ERR' 'OR:' / _errmsg ; abort; run; %if &editmemlabel %then %do; proc datasets nolist library=&libname; modify &memname(label="&memlabel"); quit; %end; %if &mode=append %then %do; %if &debug %then %put New metadata will be appended to &metasetout; proc append data=_&memname base=&metaset; run; %end; %else %if &mode=update %then %do; data &metasetout(label="Meta data re datasets in this data library"); update &metaset _&memname; by libname memname; run; %end; %*--Check to see if an index (presumably the dataset index) exists for the datasets dataset and, if not, create it--; %let _indxfilename=&libpath/datasets.sas7bndx; %put _indxfilename= &_indxfilename; %if %sysfunc(fileexist(&_indxfilename))=0 %then %do; proc datasets lib=%scan(&metaset,1) nolist; modify %scan(&metaset,2); index create dataset=(libname memname) / unique; quit; %end; %endmac: %mend doset;