Loading...
Searching...
No Matches
bitemporal_dataloader.sas
Go to the documentation of this file.
1/**
2 @file
3 @brief Routine supporting multiple load types
4 @details Generic loader for multiple load types (UPDATE, SCD2, BITEMPORAL).
5
6 Handles all elements including metadata validation, PK checking, closeouts,
7 locking, logging, etc.
8
9 The staging table must be prepared with a unique business key. For bitemporal
10 this means a snapshot at both technical AND business time.
11
12ASSUMPTIONS:
13 - Base table has relevant datetime vars: 2xTechnical, 2xBusiness, 1xProcessed
14 - Staging table omits Technical or Processed datetimes (has Business only)
15 - Base table has no column names containing the string "___TMP___"
16 - Base &tech_from variable is not nullable. This should always be the case
17 anyway whenbuilding permanent bitemporal datasets.. But the point is that
18 this field is used to identify new records after the initial left join
19 from staging to base table.
20
21NOTES:
22 - All queries against BiTemporal tables need two filter conditions, as such:
23
24 where &bus_from LE [tstamp] LT &bus_to
25 AND &tx_from LE [tstamp] LT &tx_to
26
27 One cannot use BETWEEN
28 One cannot use &xx_from LE [tstamp] LE &xx_from (equivalent to above).
29 Background: https://stackoverflow.com/questions/20005950
30
31Areas for optimisation
32 - loading temporal history (currently experimental)
33
34 ## Supporting tables
35
36 Supporting tables must exist in the library specified in the `dclib` param.
37
38 ### MPE_DATALOADS
39
40 This table is updated every time a successful load occurs, and includes
41 information such as:
42
43 @li library
44 @li dataset
45 @li message (supplied in the ETLSOURCE param)
46 @li new rows
47 @li deleted rows
48 @li changed rows
49 @li timestamp
50 @li the user making the load
51 @li the version of (this) macro used to make the load
52
53
54 @param [in] APPEND_DSN= (APPENDTABLE) Name of STAGING table
55 @param [in] CONFIG_TABLE= (&dclib..MPE_CONFIG) The table containing library
56 engine specific config. The following scopes are supported:
57 @li DCBL_REDSH
58 @param [in] LOADTYPE= (BITEMPORAL) Supported types:
59 @li TXTEMPORAL - loads a buskey with version times
60 @li BUSTEMPORAL - loads buskey with bus + ver times
61 @li UPDATE - updates a buskey with NO history
62 @param [in] PROCESSED= (0) This column obtains a current timestamp for changed
63 records when loading the target table. Default is 0 (not set). If the
64 target table contains a variable called PROCESSED_DTTM, and processed=0,
65 then this column will be used for applying the current timestamp.
66 @param RK_MAXKEYTABLE= (mpe_maxkeyvalues) The maxkeytable to use (must exist
67 in DCLIB)
68 @param [in] PK= Business key, space separated. Should NOT include temporal
69 fields.
70 @param [in] RK_UNDERLYING= If supplied will generate an RK based on these
71 (space separated) business key fields. In this case only ONE PK field should
72 be supplied, which is assumed to be the RK. The RK field, plus underlying
73 fields, should all exist on the base table. The underlying fields should
74 exist on the staging table (the RK / PK field will be overwritten).
75 The staging table should also be unique on its PK.
76
77 @param [in] dclib= (&dc_libref) The library containing DC configuration tables
78 @param [out] outds_del= (work.outds_del) Output table containing
79 deleted records
80 @param [out] outds_add= (work.outds_add) Output table containing
81 appended records
82 @param [out] outds_mod= (work.outds_mod) Output table containing
83 changed records
84 @param [out] outds_audit= (0) Load detailed changes to an audit table. Uses
85 the mp_storediffs.sas macro. Provide the base table here, to load.
86
87 <h4> Global Variables </h4>
88 The following global macro variables are used. These should be replaced by
89 macro parameters in future releases.
90
91 @li `dc_dttmtfmt`
92
93 <h4> SAS Macros </h4>
94 @li bitemporal_closeouts.sas
95 @li dc_assignlib.sas
96 @li mf_existds.sas
97 @li mf_existvar.sas
98 @li mf_fmtdttm.sas
99 @li mf_getattrn.sas
100 @li mf_getengine.sas
101 @li mf_getquotedstr.sas
102 @li mf_getschema.sas
103 @li mf_getuniquefileref.sas
104 @li mf_getuniquename.sas
105 @li mf_getuser.sas
106 @li mf_getvarlist.sas
107 @li mf_verifymacvars.sas
108 @li mf_wordsinstr1butnotstr2.sas
109 @li mp_abort.sas
110 @li mp_dropmembers.sas
111 @li mp_lockanytable.sas
112 @li mp_lockfilecheck.sas
113 @li mp_retainedkey.sas
114 @li mp_storediffs.sas
115 @li mp_rowhash.sas
116
117 @version 9.3
118 @author 4GL Apps Ltd.
119 @copyright 4GL Apps Ltd. This code may only be used within Data Controller
120 and may not be re-distributed or re-sold without the express permission of
121 4GL Apps Ltd.
122
123 @warning multitemporal loads (bitemporal for multiple points in business time)
124 are in experimental stage
125
126 @sasjslint {"noBannedStrings": false, "maxLineLength": 87}
127
128**/
129
130%macro bitemporal_dataloader(
131 bus_from= /* Business FROM datetime variable. Req'd on
132 STAGING & BASE tables.*/
133 ,bus_to = /* Business TO datetime variable. Req'd on
134 STAGING & BASE tables. */
135 ,bus_from_override= /* Provide a hard coded BUS_FROM datetime value.*/
136 ,bus_to_override= /* provide a hard coded BUS_TO datetime value */
137 ,tech_from= /* Technical FROM datetime variable. Req'd on
138 BASE table only. */
139 ,tech_to = /* Technical TO datetime variable. Req'd on BASE
140 table only. */
141 ,processed= 0
142 ,base_lib=WORK /* Libref of the BASE table. */
143 ,base_dsn=BASETABLE /* Name of BASE table. */
144 ,append_lib=WORK /* Libref of the STAGING table. */
145 ,append_dsn=APPENDTABLE
146 ,high_date='01JAN5999:00:00:00'dt /* High date to close out records */
147 ,PK= name sex
148 ,RK_UNDERLYING=
149 ,KEEPVARS= /* Provides option for removing unwanted vars from append table */
150 ,RK_UPDATE_MAXKEYTABLE=NO /* If switching (or mix matching) with regular
151 SCD2 loader then set this switch to YES to
152 ensure the MAXKEYTABLE is updated with the
153 current maximum RK value for the target table
154 */
155 ,CHECK_UNIQUENESS=YES /* Perform a check of the APPEND table to ensure it is
156 unique on its business key */
157 ,ETLSOURCE=demo /* supply a value ($50.) to show as ETLSOURCE in
158 &dclib..DATALOADS */
159 ,LOADTYPE=BITEMPORAL
160 ,RK_MAXKEYTABLE= mpe_maxkeyvalues
161 ,LOG=1 /* Switch to 0 to prevent records being added to
162 &mpelib..mpe_DATALOADS (ie when testing)*/
163 ,DELETE_COL= _____DELETE__THIS__RECORD_____
164 /* If this variable is found in the append dataset
165 then records are closed out (or deleted) in the
166 append table where that variable= "Yes" */
167 ,LOADTARGET=YES /* set to anything but uppercase YES to switch off
168 target table load and generate temp tables only */
169 ,CLOSE_VARS=
170/*a problem with regular SCD2 or TXTEMPORAL loads is that there is
171 no facility to close out removed records (all records are
172 assumed new or changed). But how does one determine which
173 records are removed? Short of loading the entire table
174 each time? This parameter allows a set of variables
175 (this should be a subset of the PK) to be declared, and
176 the macro will determine which records in the base table
177 need to be closed out ahead of the load.
178
179 For instance, given the following:
180
181 Base Table Staging Table
182 DATE ENTITY AMOUNT DATE ENTITY AMOUNT
183 JAN ACME4 66 JAN ACME4 66
184 FEB ACME4 99 FEB ACME4 99
185 FEB ACME1 22
186
187 By supplying DATE in CLOSE_VARS and DATE ENTITY as the PK,
188 the "FEB PAG 22" record would get closed out.
189 */
190 ,config_table=&dclib..MPE_CONFIG
191 ,dclib=&dc_libref
192 ,outds_del=work.outds_del
193 ,outds_add=work.outds_add
194 ,outds_mod=work.outds_mod
195 ,outds_audit=0
196 );
197
198/* when changing this macro, update the version num here */
199%local ver;
200%let ver=33;
201%put &sysmacroname entry vars:;
202%put _local_;
203
204%dc_assignlib(WRITE,&base_lib) /* may not already be assigned */
205
206/* return straight away if nothing to load */
207%let nobs= %mf_getattrn(&append_lib..&append_dsn,NLOBS);
208%if &nobs=-1 %then %do;
209 proc sql noprint; select count(*) into: nobs from &append_lib..&append_dsn;
210%end;
211%if &nobs=0 %then %do;
212 %put NOTE:; %put NOTE-;%put NOTE-;%put NOTE-;
213 %put NOTE- Base dataset &append_lib..&append_dsn is empty. Nothing to upload!;
214 %put NOTE-;%put NOTE-;%put NOTE-;
215 %return;
216%end;
217
218/* hard exit if err condition exists */
219%mp_abort(iftrue= (&syscc > 0)
220 ,mac=bitemporal_dataloader
221 ,msg=%str(Bitemporal transform / job aborted due to SYSCC=&SYSCC status;)
222)
223
224%local engine_type;
225%let engine_type=%mf_getengine(&base_lib);
226%if %length(&CLOSE_VARS)>0 and (&engine_type=REDSHIFT or &engine_type=POSTGRES
227or &engine_type=SNOW or &engine_type=SASIOSNF)
228%then %do;
229 %put NOTE:; %put NOTE-;%put NOTE-;%put NOTE-;
230 %put NOTE- CLOSE_VARS functionality not yet supported in &engine_type;
231 %put NOTE-;%put NOTE-;%put NOTE-;
232 %return;
233%end;
234
235/**
236 * The metadata functions (eg mf_existvar) will fail if the base table has a
237 * SAS lock. So, make a snapshot of the base table for further use.
238 * Also, make output tables (regardless).
239 */
240%local basecopy;
241%let basecopy=%mf_getuniquename(prefix=basecopy);
242
243data &basecopy &outds_mod &outds_add &outds_del;
244 set &base_lib..&base_dsn;
245 stop;
246run;
247%mp_abort(iftrue= (&syscc > 0)
248 ,mac=&_program
249 ,msg=%str(syscc=&syscc after base table copy - aborting due to table lock)
250)
251
252
253%local cols idx_pk md5_col hash_char_vars hash_num_vars ;
254%let md5_col=___TMP___md5;
255%let check_uniqueness=%upcase(&check_uniqueness);
256%let RK_UPDATE_MAXKEYTABLE=%upcase(&RK_UPDATE_MAXKEYTABLE);
257%let high_date=%unquote(&high_date);
258%let loadtype=%upcase(&loadtype);
259
260/* ensure irrelevant variables are cleared */
261%if &loadtype=BUSTEMPORAL %then %do;
262 %let tech_from=;
263 %let tech_to=;
264%end;
265%else %if &loadtype=TXTEMPORAL or &loadtype=UPDATE %then %do;
266 %let bus_from=;
267 %let bus_to=;
268%end;
269
270/* ensure relevant variables are supplied */
271%mp_abort(iftrue=(&loadtype=BITEMPORAL & %mf_verifymacvars(bus_from bus_to)=0)
272 ,mac=bitemporal_dataloader
273 ,msg=%str(Missing BUS_FROM / BUS_TO)
274)
275%mp_abort(iftrue=(&loadtype=TXTEMPORAL & %mf_verifymacvars(tech_from tech_to)=0)
276 ,mac=bitemporal_dataloader
277 ,msg=%str(Missing TECH_FROM / TECH_TO)
278)
279
280/**
281 * drop any tables (may be defined as views or vice versa preventing overwrite)
282 */
283%mp_dropmembers(append bitemp0_append bitemp_cols)
284
285/* SQL Server requires its own time values */
286/* 9.2 will only give picture format down to seconds. 9.3 allows
287 milliseconds by using lower S and defining the decimal in the format name..*/
288PROC FORMAT;
289 picture MyMSdt other='%0Y-%0m-%0dT%0H:%0M:%0S' (datatype=datetime);
290RUN;
291%local dbnow;
292%let dbnow="%sysfunc(datetime(),%mf_fmtdttm())"dt;
293
294data _null_;
295 /* convert space separated macvar to comma separated for SQL processing */
296 call symputx('PK_COMMA',tranwrd(compbl("&pk"),' ',','),'L');
297 call symputx('PK_CNT',countw("&pk",' '),'L');
298 now=&dbnow;
299 call symputx('NOW',now,'L');
300 call symputx('SQLNOW',cats("'",put(now,MyMSdt.),"'"),'L');
301 length etlsource $100;
302 etlsource=subpad(symget('etlsource'),1,100);
303 call symputx('etlsource',etlsource,'l');
304run;
305
306/**
307 * Even if no PROCESSED var provided, assume that any variable named
308 * PROCESSED_DTTM should be updated
309 */
310%if &processed=0 %then %do;
311 %if %mf_existvar(&basecopy,PROCESSED_DTTM)
312 %then %let processed=PROCESSED_DTTM;
313 %else %let processed=;
314%end;
315
316
317/* extract colnames for md5 creation / change tracking */
318proc contents noprint data=&base_lib..&base_dsn
319 out=work.bitemp_cols (keep=name type length varnum format:);
320run;
321proc sql noprint;
322select name into: cols separated by ','
323 from work.bitemp_cols
324 where upcase(name) not in
325 (%upcase("&bus_from","&bus_to"
326 ,"&tech_from","&tech_to"
327 ,"&processed","&delete_col")) ;
328/* Character variables are hashed separately from numerics so that the
329 iterative hash can be built with arrays rather than by concatenating
330 hundreds of 32-byte hex strings. */
331select name into: hash_char_vars separated by ' '
332 from work.bitemp_cols
333 where type in (2,6)
334 and upcase(name) not in
335 (%upcase("&bus_from","&bus_to"
336 ,"&tech_from","&tech_to"
337 ,"&processed","&delete_col")) ;
338select name into: hash_num_vars separated by ' '
339 from work.bitemp_cols
340 where type not in (2,6)
341 and upcase(name) not in
342 (%upcase("&bus_from","&bus_to"
343 ,"&tech_from","&tech_to"
344 ,"&processed","&delete_col")) ;
345
346/* set default formats*/
347%let bus_from_fmt = datetime19.;
348%let bus_to_fmt = datetime19.;
349%let processed_fmt = datetime19.;
350
351%let tech_from_fmt = format=datetime19.;
352%let tech_to_fmt = format=datetime19.;
353
354
355%put &=hash_char_vars;
356%put &=hash_num_vars;
357%put &=pk;
358
359data _null_;
360 set work.bitemp_cols;
361 if type=2 or type=6 then do;
362 length fmt $49.;
363 if format='' then fmt=cats('$',length,'.');
364 else fmt=cats(format,formatl,'.');
365 end;
366 else do;
367 if format='' then fmt=cats(length,'.');
368 else fmt=cats(format,formatl,'.',formatd);
369 end;
370 if upcase(name)="%upcase(&bus_from)" then
371 call symputx('bus_from_fmt',fmt,'L');
372 else if upcase(name)="%upcase(&bus_to)" then
373 call symputx('bus_to_fmt',fmt,'L');
374 else if upcase(name)="%upcase(&tech_from)" then
375 call symputx('tech_from_fmt',"format="!!fmt,'L');
376 else if upcase(name)="%upcase(&tech_to)" then
377 call symputx('tech_to_fmt',"format="!!fmt,'L');
378 else if upcase(name)="%upcase(&processed)" then
379 call symputx('processed_fmt',fmt,'L');
380run;
381
382%if %index(%quote(&cols),___TMP___) or %index(%quote(&cols),_____) %then %do;
383 %let msg=%str(Table contains a variable name containing "___TMP___" or "_____".%trim(
384 ) This may conflict with temp variable generation!!);
385 %mp_abort(msg=&msg,mac=bitemporal_dataloader);
386 %let syscc=5;
387 %return;
388%end;
389
390/* if transaction dates appear on the APPEND table, need to remove them */
391%local drop_tx_dates /* used in append table */
392 drop_tx_dates_noobs /* used to take the base table structure */;
393%if %mf_existvar(&append_lib..&append_dsn, &tech_from)
394 %then %let drop_tx_dates=&tech_from;
395%if %mf_existvar(&append_lib..&append_dsn, &tech_to)
396 %then %let drop_tx_dates=&drop_tx_dates &tech_to;
397%if %length(%trim(&drop_tx_dates))>0
398 %then %let drop_tx_dates=(drop=&drop_tx_dates);
399
400%if %mf_existvar(&basecopy, &tech_from)
401 %then %let drop_tx_dates_noobs=&tech_from;
402%if %mf_existvar(&basecopy, &tech_to)
403 %then %let drop_tx_dates_noobs=&drop_tx_dates_noobs &tech_to;
404%if %length(%trim(&drop_tx_dates_noobs))>0
405 %then %let drop_tx_dates_noobs=(drop=&drop_tx_dates_noobs obs=0);
406%else %let drop_tx_dates_noobs=(obs=0);
407
408
409/**
410 * Lock the table. This is necessary as we are doing a two part update (first
411 * closing records then appending new records). It is theoretically possible
412 * that an upload may occur whilst preparing the staging tables. And the
413 * staging tables are about to be prepared..
414 */
415%if &LOADTARGET = YES %then %do;
416 %put locking &base_lib..&base_dsn;
417 %mp_lockanytable(LOCK,
418 lib=&base_lib,ds=&base_dsn,ref=&ETLSOURCE,ctl_ds=&dclib..mpe_lockanytable
419 )
420 %if "&outds_audit" ne "0" %then %do;
421 %put locking &outds_audit;
422 %mp_lockanytable(LOCK
423 ,lib=%scan(&outds_audit,1,.)
424 ,ds=%scan(&outds_audit,2,.)
425 ,ref=&ETLSOURCE
426 ,ctl_ds=&dclib..mpe_lockanytable
427 )
428 %end;
429%end;
430%else %do;
431 /* not an actual load, so avoid updating the max key table in next step. */
432 %let rk_update_maxkeytable=NO;
433%end;
434
435%if %length(&RK_UNDERLYING)>0 %then %do;
436 %mp_retainedkey(
437 base_lib=&base_lib
438 ,base_dsn=&base_dsn
439 ,append_lib=&append_lib
440 ,append_dsn=&append_dsn
441 ,retained_key=&pk
442 ,business_key=&rk_underlying
443 ,check_uniqueness=&CHECK_UNIQUENESS
444 ,outds=work.append
445 %if &rk_update_maxkeytable=NO %then %do;
446 ,maxkeytable=0
447 %end;
448 %else %do;
449 ,maxkeytable=&dclib..&RK_MAXKEYTABLE
450 %end;
451 ,locktable=&dclib..mpe_lockanytable
452 %if &loadtype=BITEMPORAL or &loadtype=TXTEMPORAL %then %do;
453 ,filter_str=%str( (where=( &now < &tech_to)) )
454 %end;
455 )
456%end;
457%else %do;
458 proc sql;
459 create view work.append as select * from &append_lib..&append_dsn;
460%end;
461/**
462* generate md5 for append table
463*/
464/* it is possible the source dataset has additional (unwanted) columns.
465 Drop if specified; */
466%if %length(&keepvars)>0 %then %do;
467 /* remove tech dates from keepvars as they are generated later */
468 %let keepvars=%sysfunc(tranwrd(%str( &keepvars ),%str( &tech_from ),%str( )));
469 %let keepvars=%sysfunc(tranwrd(%str( &keepvars ),%str( &tech_to ),%str( )));
470 %let keepvars=(keep=&keepvars &bus_from &bus_to &processed &md5_col);
471%end;
472
473/* CAS varchar types cause append issues here, so perform autoconvert
474 by creating empty local table first */
475data;
476 set &base_lib..&base_dsn &drop_tx_dates_noobs;
477run;
478%local emptybasetable; %let emptybasetable=&syslast;
479
480data work.bitemp0_append &keepvars &outds_del(drop=&md5_col )
481 %if "%substr(&sysver,1,1)" ne "4" and "%substr(&sysver,1,1)" ne "5" %then %do;
482 /nonote2err
483 %end;
484 ;
485 /* apply formats for bitemporal vars but not tx dates which are added later */
486 %if %length(&keepvars)>0 and &loadtype=BITEMPORAL %then %do;
487 format &bus_from &bus_from_fmt;
488 format &bus_to &bus_to_fmt;
489 %end;
490 set &emptybasetable /* base table reqd in case append has fewer cols */
491 work.append &drop_tx_dates;
492 %if %length(%str(&bus_from_override))>0 %then %do;
493 &bus_from= %unquote(&bus_from_override) ;
494 %end;
495 %if %length(%str(&bus_to_override))>0 %then %do;
496 &bus_to= %unquote(&bus_to_override) ;
497 %end;
498 length &md5_col $32;
499 %mp_rowhash(md5_col=&md5_col
500 ,cvars=&hash_char_vars
501 ,nvars=&hash_num_vars
502 )
503 %if %length(&processed)>0 %then %do;
504 format &processed &processed_fmt;
505 &processed=&now;
506 %end;
507
508/**
509 * If a delete column exists then create the delete dataset
510 */
511%if %mf_existvar(&append_lib..&append_dsn, &delete_col) %then %do;
512 drop &delete_col;
513 if upcase(&delete_col) = "YES" then output &outds_del ;
514 else output work.bitemp0_append ;
515 run;
516
517 %if %mf_getattrn(&outds_del,NLOBS)>0 %then %do;
518 %bitemporal_closeouts(
519 tech_from=&tech_from
520 ,tech_to = &tech_to
521 ,base_lib=&base_lib
522 ,base_dsn=&base_dsn
523 ,append_lib=work
524 ,append_dsn=%scan(&outds_del,-1,.)
525 ,PK=&bus_from &pk
526 ,NOW=&dbnow
527 ,loadtarget=&loadtarget
528 ,loadtype=&loadtype
529 ,AUDITFOLDER=&dc_staging_area/&ETLSOURCE
530 )
531 %end;
532%end;
533%else %do;
534 output work.bitemp0_append;
535 run;
536%end;
537
538%mp_abort(iftrue= (&syscc gt 0 at line 494)
539 ,mac=&_program
540 ,msg=%str(syscc=&syscc)
541)
542
543%if %length(&close_vars)>0 %then %do;
544 /**
545 * need to close out records that are not provided
546 */
547 proc sql;
548 create table bitemp1_closevars1 as
549 select distinct a.%mf_getquotedstr(in_str=&pk,dlm=%str(,a.),quote=)
550 from &base_lib..&base_dsn a
551 inner join work.bitemp0_append b
552 on 1=1
553 /* join on closevars key */
554 %do idx_pk=1 %to %sysfunc(countw(&close_vars));
555 %let idx_val=%scan(&close_vars,&idx_pk);
556 and a.&idx_val=b.&idx_val
557 %end;
558 /* filter base on tech dates if necessary */
559 %if &loadtype=TXTEMPORAL %then %do;
560 where a.&tech_from <=&now and &now < a.&tech_to
561 %end;
562 ;
563 create table bitemp1_closevars2 as
564 select distinct a.*
565 from bitemp1_closevars1 a
566 left join work.bitemp0_append b
567 on 1=1
568 /* join on primary key */
569 %do idx_pk=1 %to %sysfunc(countw(&pk));
570 %let idx_val=%scan(&pk,&idx_pk);
571 and a.&idx_val=b.&idx_val
572 %end;
573 /* identify removed records by null value in a field in PK but not close_vars
574 */
575 where b.%scan(
576 %mf_wordsInStr1ButNotStr2(Str1=&pk,Str2=&close_vars),1,%str( )
577 ) IS NULL
578 ;
579
580 %if %mf_getattrn(bitemp1_closevars2,NLOBS)>0 %then %do;
581 %bitemporal_closeouts(
582 tech_from=&tech_from
583 ,tech_to = &tech_to
584 ,base_lib=&base_lib
585 ,base_dsn=&base_dsn
586 ,append_lib=work
587 ,append_dsn=bitemp1_closevars2
588 ,PK=&bus_from &pk
589 ,NOW=&dbnow
590 ,loadtarget=&loadtarget
591 ,loadtype=&loadtype
592 ,AUDITFOLDER=&dc_staging_area/&ETLSOURCE
593 )
594 %end;
595%end;
596
597/* return if nothing to load (was just deletes) */
598%if %mf_getattrn(work.bitemp0_append,NLOBS)=0 %then %do;
599 %put NOTE:; %put NOTE-;%put NOTE-;%put NOTE-;
600 %put NOTE- No updates - just deletes!;
601 %put NOTE-;%put NOTE-;%put NOTE-;
602%end;
603
604
605/**
606 * If applying manual overrides to business dates, then the input table MUST
607 * be unique on the PK. Check, and if not - abort.
608 */
609%local msg;
610%if %length(&bus_from_override.&bus_to_override)>0 or &CHECK_UNIQUENESS=YES
611%then %do;
612 proc sort data=work.bitemp0_append out=work.bitemp0_check nodupkey;
613 by &pk;
614 run;
615 %if %mf_getattrn(work.bitemp0_check,NLOBS)
616 ne %mf_getattrn(work.bitemp0_append,NLOBS)
617 %then %do;
618 %let msg=INPUT table &append_lib..&append_dsn is not unique on PK (&pk);
619 %mp_lockanytable(UNLOCK,lib=&base_lib,ds=&base_dsn,ref=&ETLSOURCE (&msg),
620 ctl_ds=&dclib..mpe_lockanytable
621 )
622 %mp_lockanytable(UNLOCK
623 ,lib=%scan(&outds_audit,1,.)
624 ,ds=%scan(&outds_audit,2,.)
625 ,ref=&ETLSOURCE
626 ,ctl_ds=&dclib..mpe_lockanytable
627 )
628 %mp_abort(msg=&msg,mac=bitemporal_dataloader.sas);
629 %end;
630%end;
631
632
633/**
634* extract from BASE table. Only want matching records, as could be very BIG.
635* New records are subsequently identified via left join and test for nulls.
636*/
637%local temp_table temp_table2 base_table baselib_schema;
638%put DCNOTE: Extracting matching observations from &base_lib..&base_dsn;
639
640%if &engine_type=OLEDB %then %do;
641 %let temp_table=##%mf_getuniquefileref(prefix=BTMP);
642 %if &loadtype=BITEMPORAL or &loadtype=TXTEMPORAL %then
643 %let base_table=(select * from [dbo].&base_dsn
644 where convert(datetime,&SQLNOW) < &tech_to );
645 %else %let base_table=[dbo].&base_dsn;
646 proc sql;
647 create table &base_lib.."&temp_table"n as
648 select * from work.bitemp0_append;
649 /* open up a connection for pass through SQL */
650 %dc_assignlib(WRITE,&base_lib,passthru=myAlias)
651 create table work.bitemp0_base as select * from connection to myAlias(
652%end;
653%else %if &engine_type=REDSHIFT or &engine_type=POSTGRES or &engine_type=SNOW
654or &engine_type=SASIOSNF
655%then %do;
656 /* grab schema */
657 %let baselib_schema=%mf_getschema(&base_lib);
658 %if &baselib_schema.X ne X %then %let baselib_schema=&baselib_schema..;
659
660 /* grab redshift config */
661 %local redcnt; %let redcnt=0;
662 %if &engine_type=REDSHIFT %then %do;
663 data _null_;
664 set &config_table(where=(var_scope='DCBL_REDSH' and var_active=1));
665 x+1;
666 call symputx(cats('rednm',x),var_value,'l');
667 call symputx(cats('redval',x),var_value,'l');
668 call symputx('redcnt',x,'l');
669 run;
670 %end;
671 %let temp_table=%upcase(%mf_getuniquename(prefix=XDCTEMP));
672 %if &loadtype=BITEMPORAL or &loadtype=TXTEMPORAL %then
673 %let base_table=(select * from &baselib_schema.&base_dsn
674 where timestamp &sqlnow < &tech_to );
675 %else %let base_table=&baselib_schema.&base_dsn;
676 /* make in-db empty table with PK + MD5 only */
677 %dc_assignlib(WRITE,&base_lib,passthru=myAlias)
678 %if &engine_type=SNOW or &engine_type=SASIOSNF %then %do;
679 exec (create transient table &baselib_schema.&temp_table
680 like &baselib_schema.&base_dsn
681 ) by myAlias;
682 %end;
683 %else %do;
684 /* cannot persist temp tables so must create a temporary permanent table */
685 exec (create table &temp_table (like &baselib_schema.&base_dsn)) by myAlias;
686 %if &engine_type=REDSHIFT %then %do;
687 exec (alter table &temp_table alter sortkey none) by myAlias;
688 %end;
689 %end;
690 %local dropcols;
691 %let dropcols=%mf_wordsinstr1butnotstr2(
692 str1=%upcase(%mf_getvarlist(&basecopy))
693 ,str2=%upcase(&pk)
694 );
695 %if %length(&dropcols>0) %then %do idx_pk=1 %to %sysfunc(countw(&dropcols));
696 %put &=dropcols;
697 %let idx_val=%scan(&dropcols,&idx_pk);
698 exec(alter table &temp_table drop column &idx_val;) by myAlias;
699 %end;
700 exec (alter table &temp_table add column &md5_col varchar(32);) by myAlias;
701 /* create view to strip formats and avoid warns in log */
702 data work.vw_bitemp0/view=work.vw_bitemp0;
703 /* inherit remote length to handle byte expansion */
704 if 0 then set &base_lib..&temp_table(keep=&md5_col);
705 set work.bitemp0_append(keep=&pk &md5_col);
706 format _all_;
707 run;
708
709 proc append base=&base_lib..&temp_table
710 %if &engine_type=REDSHIFT %then %do;
711 (
712 %do idx_pk=1 %to &redcnt;
713 &&rednm&idx_pk = &&redval&idxpk
714 %end;
715 )
716 %end;
717 data=work.vw_bitemp0 force nowarn;
718 run;
719 /* open up a connection for pass through SQL */
720 %dc_assignlib(WRITE,&base_lib,passthru=myAlias)
721 create table work.bitemp0_base as select * from connection to myAlias(
722%end;
723%else %if &engine_type=CAS %then %do;
724 %if &loadtype=BITEMPORAL or &loadtype=TXTEMPORAL %then
725 %let base_table=&base_lib..&base_dsn
726 (where=(&tech_from <=&now and &now < &tech_to));
727 %else %let base_table=&base_lib..&base_dsn;
728 %let temp_table=CASUSER.%mf_getuniquename(prefix=DC);
729 data &temp_table;
730 set work.bitemp0_append;
731 run;
732 %let bitemp0base=CASUSER.%mf_getuniquename(prefix=DC);
733 proc fedsql sessref=dcsession;
734 create table &bitemp0base{options replace=true} as
735%end;
736%else %do;
737 %let temp_table=work.bitemp0_append;
738 %if &loadtype=BITEMPORAL or &loadtype=TXTEMPORAL %then
739 %let base_table=&base_lib..&base_dsn
740 (where=(&tech_from <=&now and &now < &tech_to));
741 %else %let base_table=&base_lib..&base_dsn;
742 proc sql;
743 create table work.bitemp0_base as
744%end;
745
746 select a.&md5_col /* this identifies NEW records */
747 , b.*
748 /* assume first PK field cannot be null (if defined in a PK constraint then
749 it definitely cannot be null) */
750 , case when b.%scan(&pk,1) IS NULL then 1 else 0 end as ___TMP___NEW_FLG
751 from &baselib_schema.&temp_table a
752 left join &base_table b
753 on 1=1
754%do idx_pk=1 %to &pk_cnt;
755 %let idx_val=%scan(&pk,&idx_pk);
756 and a.&idx_val=b.&idx_val
757%end;
758
759
760%if &engine_type=OLEDB or &engine_type=REDSHIFT or &engine_type=POSTGRES
761or &engine_type=SNOW or &engine_type=SASIOSNF
762%then %do;
763 ); proc sql; drop table &base_lib.."&temp_table"n;
764%end;
765%else %if &engine_type=CAS %then %do;
766 ;
767 quit;
768 data work.bitemp0_base;
769 set &bitemp0base;
770 run;
771 proc sql;
772 drop table &temp_table;
773 drop table &bitemp0base;
774%end;
775%else %do;
776 ;
777%end;
778
779/**
780* matching & changed records are those without NULL key values
781* &idx_val resolves to rightmost PK value (loop above)
782*/
783%put syscc (line525)=&syscc, sqlrc=&sqlrc;
784%mp_abort(iftrue= (&syscc gt 0 or &sqlrc>0)
785 ,mac=&_program
786 ,msg=%str(syscc=&syscc sqlrc=&sqlrc)
787)
788
789%put hash_char_vars=&hash_char_vars;
790%put hash_num_vars=&hash_num_vars;
791data work.bitemp1_current(drop=___TMP___NEW_FLG);
792 set work.bitemp0_base(drop=&md5_col);
793 if ___TMP___NEW_FLG=0;
794 length &md5_col $32;
795 %mp_rowhash(md5_col=&md5_col
796 ,cvars=&hash_char_vars
797 ,nvars=&hash_num_vars
798 )
799run;
800
801/**
802* NEW records were identified in ___TMP___NEW_FLG in bitemp0_base
803*/
804proc sql;
805create table &outds_add
806 (drop=&md5_col
807 %if %mf_existvar(work.bitemp0_base, &delete_col) %then %do;
808 &delete_col
809 %end;
810 )
811 as select a.*
812 %if &loadtype=BITEMPORAL or &loadtype=TXTEMPORAL %then %do;
813 ,&now as &tech_from &tech_from_fmt
814 ,&high_date as &tech_to &tech_to_fmt
815 %end;
816 from work.bitemp0_append a /* STAGING records (mix of existing & new) */
817 , work.bitemp0_base b /* BASE records (contains null values for new) */
818 where a.&md5_col=b.&md5_col /* took staging md5 across in left join */
819 and b.___TMP___NEW_FLG=1; /* NEW records also identified in bitemp0_base */
820
821
822/**
823* identify INSERTS. These are records with the same business key but
824* the bus_from and bus_to value are higher / lower (respectively)
825* such that the existing record needs to be SPLIT to surround the new
826* record.
827* eg: OLD RECORD from=1 to=10
828* NEW RECORD from=5 to=7
829*
830* APPENDED RECORDS:
831* - from=1 to=5
832* - from=5 to=7
833* - from=7 to=10
834*/
835
836/* inserts cannot happen with TXTEMPORAL */
837%if &loadtype=BITEMPORAL or &loadtype=BUSTEMPORAL %then %do;
838 /* IDENTIFY */
839 create table work.bitemp3_inserts as
840 select b.*
841 ,a.&bus_from as ___TMP___from
842 ,a.&bus_to as ___TMP___to
843 from work.bitemp0_append a
844 ,work.bitemp1_current b
845 where a.&bus_from > b.&bus_from
846 and a.&bus_to < b.&bus_to
847 %do idx_pk=1 %to &pk_cnt;
848 %let idx_val=%scan(&pk,&idx_pk);
849 and a.&idx_val=b.&idx_val
850 %end;
851 order by
852 /* compress blanks and then insert commas (as the datetime fields may
853 not be in use) */
854 %sysfunc(tranwrd(%sysfunc(compbl(
855 &pk &bus_from &bus_to &processed
856 )),%str( ), %str(,)))
857 ;
858
859 /* SPLIT */
860 data work.bitemp3a_inserts (drop=___TMP___from ___TMP___retain ___TMP___to) ;
861 set work.bitemp3_inserts;
862 by &pk &bus_from &bus_to &processed;
863 if first.&idx_val then do;
864 ___TMP___retain=&bus_to;
865 &bus_to=___TMP___from;
866 output;
867 &bus_to=___TMP___retain;
868 end;
869 if last.&idx_val then do;
870 &bus_from=___TMP___to;
871 output;
872 end;
873 run;
874%end;
875%else %do;
876 /* TX temporal load */
877 data work.bitemp3a_inserts;
878 set work.bitemp1_current;
879 stop;
880 run;
881%end;
882/* APPEND */
883proc sql;
884create view work.bitemp3a_view as
885 select * from work.bitemp1_current
886 where &md5_col not in (select &md5_col from work.bitemp3a_inserts);
887
888data bitemp3b_newbase;
889 set work.bitemp3a_inserts work.bitemp3a_view;
890run;
891
892/** do not use! this converts short numerics into 8 bytes
893proc sql;
894create table work.bitemp3b_newbase as
895 select * from work.bitemp3a_inserts
896union corr
897 select * from work.bitemp1_current
898 where &md5_col not in (select &md5_col from work.bitemp3a_inserts);
899*/
900
901/**
902* identify CHANGED records from staging.
903* Same business key with different temporal dates or md5 value
904* This table must be overlayed onto / into existing business history
905*/
906proc sql;
907create table work.bitemp4_updated as select distinct a.*
908 from work.bitemp0_append a
909 ,work.bitemp3b_newbase b
910 where 1=1
911 %do idx_pk=1 %to &pk_cnt;
912 %let idx_val=%scan(&pk,&idx_pk);
913 and a.&idx_val=b.&idx_val
914 %end;
915 and ( a.&md5_col ne b.&md5_col
916 %if &loadtype=BITEMPORAL or &loadtype=BUSTEMPORAL %then %do;
917 OR (a.&bus_from ne b.&bus_from or a.&bus_to ne b.&bus_to)
918 %end;
919 )
920;
921
922/**
923 * This section would have been one simple step with union all
924 * but that converts short numerics into 8 bytes!
925 * so, convoluted alternative to retain the same functionality.
926 */
927
928/* base records */
929create view work.bitemp4_prep1 as
930 select 'BASE' as ___TMP___
931 ,b.*
932 from work.bitemp4_updated a
933 ,work.bitemp3b_newbase b
934 where 1
935 %do idx_pk=1 %to &pk_cnt;
936 %let idx_val=%scan(&pk,&idx_pk);
937 and a.&idx_val=b.&idx_val
938 %end;
939 ;
940/* updated records */
941create view work.bitemp4_prep2 as
942 select 'STAG' as ___TMP___ ,*
943 from work.bitemp4_updated;
944/* ensure we only keep columns that appear in both */
945%local bp1 bp2 bp3 bp4;
946%let bp1=%mf_getvarlist(bitemp4_prep1);
947%let bp2=%mf_getvarlist(bitemp4_prep2);
948%let bp3=%mf_wordsInStr1ButNotStr2(Str1=&bp1,Str2=&bp2);
949%let bp4=%mf_wordsInStr1ButNotStr2(Str1=&bp2,Str2=&bp1);
950data work.bitemp4_prep3/view=bitemp4_prep3;
951 set bitemp4_prep1 bitemp4_prep2;
952%if %length(XX&bp3&bp4)>2 %then %do;
953 drop &bp3 &bp4 ;
954%end;
955run;
956/* remove duplicates */
957proc sql;
958create table work.bitemp4a_allrecs as
959 select distinct *
960 from work.bitemp4_prep3
961 order by
962 /* compress blanks and then insert commas (as the datetime fields
963 may not be in use) */
964 %sysfunc(tranwrd(%sysfunc(compbl(
965 &pk &bus_from &bus_to &processed
966 )),%str( ), %str(,)))
967 ;
968
969%if &loadtype=BITEMPORAL or &loadtype=BUSTEMPORAL %then %do;
970 /* this section aligns the business dates
971 (eg for inserts or overlaps in the range) */
972 data work.bitemp4b_firstpass (drop=___TMP___cond ___TMP___from ___TMP___to );
973 set work.bitemp4a_allrecs;
974 by &pk &bus_from &bus_to &processed;
975 retain ___TMP___cond 'Name of Condition';
976 retain ___TMP___from ___TMP___to 0;
977 ___TMP___md5lag=lag(&md5_col);
978 /* reset retained variables */
979 if first.&idx_val then do;
980 call missing (___TMP___cond, ___TMP___from, ___TMP___to,___TMP___md5lag);
981 end;
982 else do;
983 /* if record is identical, carry forward bus_from (and bus_to if higher)*/
984 if &md5_col=___TMP___md5lag then do;
985 &bus_from=___TMP___from;
986 if &bus_to<___TMP___to then &bus_to=___TMP___to;
987 end;
988 end;
989
990 if ___TMP___='STAG' then do;
991 /* need to carry forward the closing record */
992 ___TMP___cond='Condition 1';
993 end;
994 else if ___TMP___cond='Condition 1' then do;
995 /* else ensure bus_from starts from prior record bus_to */
996 if &md5_col ne ___TMP___md5lag and &bus_from <= ___TMP___to
997 then &bus_from= ___TMP___to;
998 /* new record may replace old record entirely */
999 if &bus_to <= &bus_from then delete;
1000 else call missing (___TMP___cond, ___TMP___from, ___TMP___to);
1001 end;
1002 ___TMP___from=&bus_from;
1003 ___TMP___to=&bus_to;
1004 run;
1005%end;
1006%else %do;
1007 /* keep staged records only */
1008 data work.bitemp4b_firstpass;
1009 set work.bitemp4a_allrecs;
1010 if ___TMP___='STAG';
1011 run;
1012%end;
1013
1014/* next phase is to pass through in reverse - so set up the sort statement */
1015%local byvar;
1016%do idx_pk=1 %to &pk_cnt;
1017 %let byvar=&byvar descending %scan(&pk,&idx_pk);
1018%end;
1019%if &loadtype=BITEMPORAL or &loadtype=BUSTEMPORAL
1020%then %let byvar=&byvar descending &bus_from descending &bus_to;
1021/* if matching bus dates supplied, need to ensure we also have a sort
1022 between BASE and STAGING tables */
1023%let byvar=&byvar descending ___TMP___;
1024
1025proc sort data=work.bitemp4b_firstpass out=work.bitemp4c_sort ;
1026 by &byvar;
1027run;
1028
1029/**
1030* Now (in reverse) pass back business start dates
1031*/
1032data work.bitemp4d_secondpass;
1033%if &loadtype=BITEMPORAL or &loadtype=TXTEMPORAL %then %do;
1034 &tech_from=&now;
1035 &tech_to=&high_date;
1036%end;
1037 set work.bitemp4c_sort ;
1038 by &byvar;
1039 retain ___TMP___cond 'Name of Condition';
1040 retain ___TMP___from ___TMP___to 0;
1041%if &loadtype=BITEMPORAL or &loadtype=BUSTEMPORAL %then %do;
1042/* put / _all_ /;*/
1043 ___TMP___md5lag=lag(&md5_col);
1044 if first.&idx_val then do;
1045 /* reset retained variables */
1046 call missing (___TMP___cond,___TMP___from,___TMP___to,___TMP___md5lag);
1047 end;
1048 else do;
1049 /* if record is identical, carry back bus_to */
1050 if &md5_col=___TMP___md5lag then &bus_to=___TMP___to;
1051 end;
1052
1053 if ___TMP___='STAG' then do;
1054 /* need to carry forward the closing record */
1055 ___TMP___cond='Condition 2';
1056 end;
1057 else if ___TMP___cond='Condition 2' then do;
1058 /* else ensure bus_to stops at subsequent record bus_from */
1059 if &md5_col ne ___TMP___md5lag and &bus_to >= ___TMP___from
1060 then &bus_to= ___TMP___from;
1061 /* new record may replace old record entirely */
1062 if &bus_from >= &bus_to then delete;
1063 if &bus_from=___TMP___from and &bus_to=___TMP___to then delete;
1064 else call missing (___TMP___cond, ___TMP___from, ___TMP___to);
1065 end;
1066 ___TMP___from=&bus_from;
1067 ___TMP___to=&bus_to;
1068
1069%end;
1070run;
1071%put syscc (line600)=&syscc;
1072/**
1073 There may still be some records (eg old business history) which have not
1074 changed.
1075 Need to identify these and remove from the append so they are not updated
1076 unnecessarily. This is done by generating a new md5 (which INCLUDES the
1077 business key) and any matching / identical records are split out (from those
1078 that need to be updated).
1079*/
1080
1081%if &loadtype=BITEMPORAL %then %do;
1082 /* For bitemporal we also include the business dates in the comparison hash.
1083 The business dates are passed as prefix numerics so that both lookup and
1084 update tables use exactly the same hashing order. */
1085
1086 data work.bitemp5a_lkp (keep=&md5_col)
1087 %if "%substr(&sysver,1,1)" ne "4" & "%substr(&sysver,1,1)" ne "5" %then %do;
1088 /nonote2err
1089 %end;
1090 ;
1091 set work.bitemp0_base;
1092 %mp_rowhash(md5_col=&md5_col
1093 ,cvars=&hash_char_vars
1094 ,nvars=&bus_from &bus_to &hash_num_vars
1095 )
1096 run;
1097
1098 data bitemp5b_updates;
1099 set bitemp4d_secondpass;
1100 if _n_=1 then do;
1101 dcl hash md5_lkp(dataset:'bitemp5a_lkp');
1102 md5_lkp.definekey("&md5_col");
1103 md5_lkp.definedone();
1104 end;
1105 /* drop old md5 col as will rebuild with new business dates */
1106 %mp_rowhash(md5_col=&md5_col
1107 ,cvars=&hash_char_vars
1108 ,nvars=&bus_from &bus_to &hash_num_vars
1109 )
1110 if md5_lkp.check()=0 then delete;
1111 run;
1112
1113 proc sql;
1114 /* get min bus from as will update (close out) all records from this point
1115 (for that PK)*/
1116 create table work.bitemp5d_subquery as
1117 select &pk_comma, min(&bus_from)as &bus_from, max(&bus_to) as &bus_to
1118 from work.bitemp5b_updates
1119 group by &pk_comma;
1120 /* index has a huge efficiency impact on upcoming nested subquery */
1121 create index index1 on work.bitemp5d_subquery(&pk_comma,&bus_from, &bus_to);
1122
1123 %let lastds=work.bitemp5b_updates;
1124%end;
1125%else %if &loadtype=TXTEMPORAL or &loadtype=UPDATE %then %do;
1126 proc sql;
1127 create table work.bitemp5d_subquery as
1128 select distinct &pk_comma
1129 from bitemp4d_secondpass;
1130 %let lastds=work.bitemp4d_secondpass;
1131%end;
1132%else %let lastds=work.bitemp4d_secondpass;
1133
1134/* create single append table (an overlapped pre-sert may be classed as
1135 both an update AND a new record). Also create temp views that may be
1136 used for pre-load analysis. */
1137data &outds_mod;
1138 set &lastds(drop=___TMP___: &md5_col);
1139run;
1140
1141data bitemp6_allrecs / view=bitemp6_allrecs;
1142 set &outds_mod /* UPDATED records */
1143 &outds_add /* NEW records */;
1144run;
1145
1146proc sort data=work.bitemp6_allrecs
1147 out=work.bitemp6_unique
1148 noduprec
1149 dupout=work.xx_BADBADBAD;
1150by _all_;
1151run;
1152
1153/* we have all our temp tables now so exit if this is all that is needed */
1154%if &LOADTARGET ne YES %then %return;
1155
1156/* also exit if an err condition exists */
1157
1158%if &syscc>0 %then %do;
1159 %put syscc=&syscc;
1160 %mp_lockanytable(UNLOCK,lib=&base_lib,ds=&base_dsn,ref=&ETLSOURCE,
1161 ctl_ds=&dclib..mpe_lockanytable
1162 )
1163 %if "&outds_audit" ne "0" %then %do;
1164 %mp_lockanytable(UNLOCK
1165 ,lib=%scan(&outds_audit,1,.)
1166 ,ds=%scan(&outds_audit,2,.)
1167 ,ref=&ETLSOURCE
1168 ,ctl_ds=&dclib..mpe_lockanytable
1169 )
1170 %end;
1171%end;
1172%mp_abort(iftrue= (&syscc>0)
1173 ,mac=&sysmacroname in &_program
1174 ,msg=%str(Bitemporal transform / job aborted due to SYSCC=&SYSCC status)
1175)
1176
1177/* final check - abort if a lock has appeared on the target or audit table */
1178%mp_lockfilecheck(libds=&base_lib..&base_dsn)
1179%if %mf_existds(&outds_audit) %then %do;
1180 %mp_lockfilecheck(libds=&outds_audit)
1181%end;
1182
1183/**
1184* STAGING TABLES PREPARED, ERR CONDITION TESTED FOR.. NOW TO LOAD!!
1185*/
1186
1187/**
1188* First, CLOSE OUT changed records (if not a REPLACE)
1189* Note that SAS does not support ANSI standard for UPDATE with a join condition.
1190* However - this can be worked around using a nested subquery..
1191*/
1192data _null_;
1193 putlog "&sysmacroname: CLOSEOUTS commencing";
1194run;
1195
1196%if %mf_getattrn(&lastds,NLOBS)=0 %then %do;
1197 data _null_;
1198 putlog "&sysmacroname: No closeouts needed";
1199 run;
1200%end;
1201%else %if &engine_type=CAS %then %do;
1202 %mp_abort(iftrue= (&loadtype=BITEMPORAL or &loadtype=TXTEMPORAL)
1203 ,mac=&sysmacroname in &_program
1204 ,msg=%str(&loadtype not yet supported in CAS engine)
1205 )
1206 /* create temp table for deletions */
1207 %local delds;%let delds=%mf_getuniquename(prefix=DC);
1208 data casuser.&delds;
1209 set work.bitemp5d_subquery;
1210 run;
1211 /* delete the records */
1212 proc cas ;
1213 table.deleteRows / table={
1214 caslib="&base_lib",
1215 name="&base_dsn",
1216 where="1=1",
1217 whereTable={caslib='CASUSER',name="&delds"}
1218 };
1219 quit;
1220 /* drop temp table */
1221 proc sql;
1222 drop table CASUSER.&delds;
1223%end;
1224%else %if (&loadtype=BITEMPORAL or &loadtype=TXTEMPORAL or &loadtype=UPDATE)
1225%then %do;
1226 data _null_;
1227 putlog "&sysmacroname: &loadtype operation using *&engine_type* engine";
1228 run;
1229 %local flexinow;
1230 proc sql;
1231 /* if OLEDB then create a temp table for efficiency */
1232 %local innertable;
1233 %if &engine_type=OLEDB %then %do;
1234 %let innertable=[&temp_table];
1235 %let top_table=[dbo].&base_dsn;
1236 %let flexinow=&SQLNOW;
1237 create table &base_lib.."&temp_table"n as
1238 select * from work.bitemp5d_subquery;
1239 /* open up a connection for pass through SQL */
1240 %dc_assignlib(WRITE,&base_lib,passthru=myAlias)
1241 execute(
1242 %end;
1243 %else %if &engine_type=REDSHIFT or &engine_type=POSTGRES or &engine_type=SNOW
1244 or &engine_type=SASIOSNF
1245 %then %do;
1246 %let innertable=%upcase(%mf_getuniquename(prefix=XDCTEMP));
1247 %let top_table=&baselib_schema.&base_dsn;
1248 %let flexinow=timestamp &SQLNOW;
1249 /* make empty table first - must clone & drop extra cols
1250 as autoload is bad */
1251 %dc_assignlib(WRITE,&base_lib,passthru=myAlias)
1252 %if &engine_type=SNOW or &engine_type=SASIOSNF %then %do;
1253 exec (create transient table &baselib_schema.&innertable
1254 like &baselib_schema.&base_dsn
1255 ) by myAlias;
1256 %end;
1257 %else %do;
1258 exec (create table &innertable
1259 (like &baselib_schema.&base_dsn)
1260 ) by myAlias;
1261 %if &engine_type=REDSHIFT %then %do;
1262 exec (alter table &innertable alter sortkey none) by myAlias;
1263 %end;
1264 %end;
1265 %let dropcols=%mf_wordsinstr1butnotstr2(
1266 str1=%upcase(%mf_getvarlist(&basecopy))
1267 ,str2=%upcase(%mf_getvarlist(work.bitemp5d_subquery))
1268 );
1269 %if %length(&dropcols>0) %then %do idx_pk=1 %to %sysfunc(countw(&dropcols));
1270 %put &=dropcols;
1271 %let idx_val=%scan(&dropcols,&idx_pk);
1272 exec(alter table &innertable drop column &idx_val;) by myAlias;;
1273 %end;
1274 /* create view to strip formats and avoid warns in log */
1275 data work.vw_bitemp5d/view=work.vw_bitemp5d;
1276 set work.bitemp5d_subquery;
1277 format _all_;
1278 run;
1279 proc append base=&base_lib..&innertable (
1280 %do idx_pk=1 %to &redcnt;
1281 &&rednm&idx_pk = &&redval&idxpk
1282 %end;
1283 )
1284 data=work.vw_bitemp5d force nowarn;
1285 run;
1286 /* open up a connection for pass through SQL */
1287 %dc_assignlib(WRITE,&base_lib,passthru=myAlias)
1288 execute(
1289 %end;
1290 %else %do;
1291 %put Not using passthrough for *&engine_type* engine;
1292 %let innertable=bitemp5d_subquery;
1293 %let top_table=&base_lib..&base_dsn;
1294 %let flexinow=&now;
1295 %end;
1296
1297
1298 %if &loadtype=BITEMPORAL or &loadtype=TXTEMPORAL %then %do;
1299 update &top_table set &tech_to=&flexinow
1300 %if %length(&processed)>0 %then %do;
1301 ,&processed=&flexinow
1302 %end;
1303 where &tech_from <= &flexinow and &flexinow < &tech_to and
1304 %end;
1305 %else %if &loadtype=UPDATE %then %do;
1306 /* changed records are deleted then re-appended when doing UPDATEs */
1307 delete from &top_table where
1308 %end;
1309 %else %do;
1310 %put %str(ERR)OR: BUSTEMPORAL NOT YET SUPPORTED;
1311 %let syscc=5;
1312 %mp_lockanytable(UNLOCK,lib=&base_lib,ds=&base_dsn,ref=&ETLSOURCE,
1313 ctl_ds=&dclib..mpe_lockanytable
1314 )
1315 %mp_lockanytable(UNLOCK
1316 ,lib=%scan(&outds_audit,1,.)
1317 ,ds=%scan(&outds_audit,2,.)
1318 ,ref=&ETLSOURCE
1319 ,ctl_ds=&dclib..mpe_lockanytable
1320 )
1321 %goto end_of_macro;
1322 %end;
1323
1324 /* perform join inside query as per
1325 http://stackoverflow.com/questions/24629793/update-with-a-proc-sql */
1326
1327 exists( select 1 from &baselib_schema.&innertable where
1328
1329 /* loop PK join */
1330 %do idx_pk=1 %to &pk_cnt;
1331 %let idx_val=%scan(&pk,&idx_pk);
1332 &base_dsn..&idx_val=&innertable..&idx_val and
1333 %end;
1334 %if &loadtype=BITEMPORAL %then %do;
1335 &base_dsn..&bus_from >= &innertable..&bus_from
1336 and &base_dsn..&bus_to <= &innertable..&bus_to and
1337 %end;
1338
1339 /* close the statement */
1340
1341 1=1);
1342
1343 %if &engine_type=OLEDB or &engine_type=REDSHIFT or &engine_type=POSTGRES
1344 or &engine_type=SNOW or &engine_type=SASIOSNF
1345 %then %do;
1346 ) by myAlias;
1347 execute (drop table &baselib_schema.&innertable) by myAlias;
1348 %end;
1349%end;
1350quit;
1351data _null_;
1352 putlog "&sysmacroname: Closeout complete";
1353run;
1354/**
1355 * Append the new / updated records
1356 */
1357%if &engine_type=CAS %then %do;
1358
1359 /* get varchar variables ready for casting */
1360 %local vcfmt vcrename vcassign vcdrop;
1361 data _null_;
1362 set work.bitemp_cols(where=(type=6)) end=last;
1363 length vcrename vcassign vcdrop vcfmt $32767 rancol $32;
1364 retain vcrename vcassign vcdrop vcfmt;
1365 if _n_=1 then vcrename='(rename=(';
1366 rancol=resolve('%mf_getuniquename()');
1367 vcfmt=trim(vcfmt)!!'length '!!cats(name)!!' varchar(*);';
1368 vcrename=trim(vcrename)!!' '!!cats(name,'=',rancol);
1369 vcassign=cats(vcassign,name,'=',rancol,';');
1370 vcdrop=cats(vcdrop,'drop '!!rancol,';');
1371 if last then do;
1372 vcrename=cats(vcrename,'))');
1373 call symputx('vcfmt',vcfmt);
1374 call symputx('vcrename',vcrename);
1375 call symputx('vcassign',vcassign);
1376 call symputx('vcdrop',vcdrop);
1377 end;
1378 run;
1379
1380 /* prepare a temp cas table with varchars casted */
1381 %let tmp=%mf_getuniquename();
1382 data casuser.&tmp ;
1383 &vcfmt
1384 set work.bitemp6_unique &vcrename;
1385 &vcassign
1386 &vcdrop
1387 run;
1388
1389 /* load the table with varchars applied*/
1390 data &base_lib..&base_dsn (append=yes )/sessref=dcsession ;
1391 set casuser.&tmp;
1392 run;
1393
1394 /* drop temp table */
1395 proc sql;
1396 drop table CASUSER.&tmp;
1397
1398 /* this code will not work as regular tables do not have varchars */
1399 /*
1400 proc casutil;
1401 load data=work.bitemp6_unique
1402 outcaslib="&base_lib" casout="&base_dsn" append ;
1403 quit;
1404 */
1405%end;
1406%else %if &engine_type=REDSHIFT or &engine_type=POSTGRES %then %do;
1407 proc append base=&base_lib..&base_dsn
1408 %if &engine_type=REDSHIFT %then %do;
1409 (
1410 %do idx_pk=1 %to &redcnt;
1411 &&rednm&idx_pk = &&redval&idxpk
1412 %end;
1413 )
1414 %end;
1415 data=bitemp6_unique force nowarn;
1416 run;
1417%end;
1418%else %do;
1419 proc append base=&base_lib..&base_dsn data=bitemp6_unique force nowarn; run;
1420%end;
1421
1422%mp_lockanytable(UNLOCK,lib=&base_lib,ds=&base_dsn,ref=&ETLSOURCE,
1423 ctl_ds=&dclib..mpe_lockanytable
1424)
1425
1426/* final check on syscc */
1427%mp_abort(iftrue= (&syscc >4)
1428 ,mac=&_program
1429 ,msg=%str(!!Upload NOT successful!! Failed on actual update / append stage..)
1430)
1431
1432%if &outds_audit ne 0 and &LOADTARGET=YES %then %do;
1433 data work.vw_outds_orig /view=work.vw_outds_orig;
1434 set work.bitemp0_base (drop=&md5_col);
1435 where ___TMP___NEW_FLG=0;
1436 drop ___TMP___NEW_FLG;
1437 run;
1438 /* update the AUDIT table */
1439 %if %mf_existds(&outds_audit) %then %do;
1440 options mprint;
1441 %mp_storediffs(&base_lib..&base_dsn
1442 ,work.vw_outds_orig
1443 ,&pk &bus_from
1444 ,delds=&outds_del
1445 ,modds=&outds_mod
1446 ,appds=&outds_add
1447 ,outds=work.mp_storediffs
1448 ,processed_dttm=&now
1449 ,loadref=%superq(etlsource)
1450 )
1451 /* exclude unchanged values in modified rows */
1452 data work.mp_storediffs;
1453 set work.mp_storediffs;
1454 if MOVE_TYPE="M" and IS_PK=0 and IS_DIFF=0 then delete;
1455 /* putlog load_ref= libref= dsn= key_hash= tgtvar_nm=; */
1456 run;
1457 proc append base=&outds_audit data=work.mp_storediffs;
1458 run;
1459 %mp_lockanytable(UNLOCK
1460 ,lib=%scan(&outds_audit,1,.)
1461 ,ds=%scan(&outds_audit,2,.)
1462 ,ref=&ETLSOURCE
1463 ,ctl_ds=&dclib..mpe_lockanytable
1464 )
1465 %end;
1466%end;
1467%mp_abort(iftrue= (&syscc >4)
1468 ,mac=bitemporal_dataloader
1469 ,msg=%str(Problem in audit stage (&outds_audit))
1470)
1471
1472%let user=%mf_getUser();
1473/**
1474 Notify as appropriate EMAILS DISABLED
1475
1476%sumo_alerts(ALERT_EVENT=UPDATE
1477 , ALERT_TARGET=&base_lib..&base_dsn
1478 , from_user= &user);
1479*/
1480/* monitor BiTemporal usage */
1481%if &log=1 %then %do;
1482 %put syscc=&syscc;
1483 /* do not perform duration calc in pass through */
1484 %local dur;
1485 data _null_;
1486 now=symget('now');
1487 dur=%sysfunc(datetime())-&now;
1488 call symputx('dur',dur,'l');
1489 run;
1490 proc sql;
1491 insert into &dclib..mpe_dataloads
1492 set libref=%upcase("&base_lib")
1493 ,DSN=%upcase("&base_dsn")
1494 ,ETLSOURCE="&ETLSOURCE"
1495 ,LOADTYPE="&loadtype"
1496 ,CHANGED_RECORDS=%mf_getattrn(&lastds,NLOBS)
1497 ,NEW_RECORDS=%mf_getattrn(&outds_add,NLOBS)
1498 ,DELETED_RECORDS=%mf_getattrn(&outds_del,NLOBS)
1499 ,DURATION=&dur
1500 ,MAC_VER="v&ver"
1501 ,user_nm="&user"
1502 ,PROCESSED_DTTM=&now;
1503 quit;
1504 %put syscc=&syscc;
1505%end;
1506%end_of_macro:
1507%mend bitemporal_dataloader;