-
Notifications
You must be signed in to change notification settings - Fork 0
/
create.sql.j2
662 lines (553 loc) · 33 KB
/
create.sql.j2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
{#
Copyright (c) 2023 Coalesce. All rights reserved.
This script and its associated documentation are confidential and proprietary to Coalesce.
Unauthorized reproduction, distribution, or disclosure of this material is strictly prohibited.
Coalesce permits you to copy and modify this script for the purposes of using with Coalsce but
does not permit copying or modification for any other purpose.
#}
{# == Node Type Version : 1 == #}
{# == Node Type Name : Fact With Task == #}
{# == Node Type Description : This node creates a fact table and a task to insert/merge data into fact table == #}
{# Create / Alter Table first #}
{% if desiredState == currentState %}
{{ stage('No table edits.') }}
select 1 = 0
{% elif desiredState %}
{% set targetTableDatabase = ref_no_link(desiredState.node.location.name, desiredState.node.name).split('.')[0] %}
{% set targetTableSchema = ref_no_link(desiredState.node.location.name, desiredState.node.name).split('.')[1] %}
{% set fullyQualifiedTargetTableName = ref_no_link(desiredState.node.location.name, desiredState.node.name) %}
{# Test if Business Key changed #}
{% set nsVariables = namespace(businessKeyChanges=0) %}
{% if currentState != undefined %}
{% for businessKeyCol in currentState.columns if nsVariables.colchanges == 0 %}
{% if businessKeyCol.id in desiredState.columns | map(attribute="id") %}
{% set currentBusinessKeyCol = businessKeyCol.isBusinessKey %}
{% set desiredBusinessKeyCol = desiredState.columns | selectattr('id', "equalto", businessKeyCol.id) | map(attribute='isBusinessKey') | first %}
{% if currentBusinessKeyCol != desiredBusinessKeyCol %}
{% set nsVariables.businessKeyChanges = 1 %}
{% endif %}
{% endif %}
{% endfor %}
{% for businessKeyCol in desiredState.columns if nsVariables.businessKeyChanges == 0 %}
{% if businessKeyCol.id in currentState.columns | map(attribute="id") %}
{% set desiredBusinessKeyCol = businessKeyCol.isBusinessKey %}
{% set currentBusinessKeyCol = currentState.columns | selectattr('id', "equalto", businessKeyCol.id) | map(attribute='isBusinessKey') | first %}
{% if currentBusinessKeyCol != desiredBusinessKeyCol %}
{% set nsVariables.businessKeyChanges = 1 %}
{% endif %}
{% endif %}
{% endfor %}
{% endif %}
{# Figure out cluster key #}
{% set nsVariables = namespace(finalClusterKey="") %}
{% if desiredState.config.clusterKey == true %}
{% if desiredState.config.clusterKeyExpressions == true %}
{% set column, expression = desiredState.config.clusterKeyConfigExpressions.get('items') | map(attribute='columnNameExpressions.name') | list, desiredState.config.clusterKeyConfigExpressions.get('items') | map(attribute='sqlExpression') | list %}
{%- set nsVariables = namespace(clusterValues=[]) %}
{% for r in column %}
{% if expression[loop.index0] == "" %}
{% set nsVariables.clusterValues = nsVariables.clusterValues + [r] %}
{% else %}
{% set nsVariables.clusterValues = nsVariables.clusterValues + [expression[loop.index0]] %}
{% endif %}
{% endfor %}
{% set nsVariables.finalClusterKey = 'CLUSTER BY (' + nsVariables.clusterValues | join(',') + ')' %}
{% else %}
{% set column = desiredState.config.clusterKeyConfig.get('items') | map(attribute='columnName.name') | list %}
{%- set nsVariables = namespace(clusterValues=[]) %}
{% for r in column %}
{% set nsVariables.clusterValues = nsVariables.clusterValues + [r] %}
{% endfor %}
{% set nsVariables.finalClusterKey = 'CLUSTER BY (' + nsVariables.clusterValues | join(',') + ')' %}
{% endif %}
{% endif %}
{% if currentState == undefined or nsVariables.colchanges == 1 or currentState.storageLocations | length == 0%}
{{ stage('Create Fact Table', true, "sql", "alter") }}
CREATE OR REPLACE TABLE {{ fullyQualifiedTargetTableName }}
(
{% for col in desiredState.columns %}
"{{ col.name }}" {{ col.dataType }}
{% if col.isSurrogateKey %}
identity
{% endif %}
{%- if not col.nullable %} NOT NULL
{%- if col.defaultValue | length > 0 %} DEFAULT {{ col.defaultValue }}{% endif %}
{% endif %}
{%- if col.description | length > 0 %} COMMENT '{{ col.description | escape }}'{% endif %}
{%- if not loop.last -%}, {% endif %}
{% endfor %}
)
{%- if desiredState.node.description | length > 0 %}
COMMENT = '{{ desiredState.node.description | escape }}'
{% endif %}
{% if desiredState.config.clusterKey == true %}
{{ stage('Apply Table Clustering', true, "sql", "create") }}
ALTER TABLE {{ ref_no_link(desiredState.node.location.name, desiredState.node.name) }} {{ nsVariables.finalClusterKey }}
{{ stage('Resume Recluster Table', true, "sql", "create") }}
ALTER TABLE {{ ref_no_link(desiredState.node.location.name, desiredState.node.name) }} RESUME RECLUSTER
{% endif %}
{% elif currentState != undefined %}
{# Change Node Name or Change Storage Location #}
{# Storage Location Tests #}
{# Only need to account for updated Storage Location mappings #}
{# Current Namespace Varialbes #}
{% set nsVariables = namespace(nsCurrentDepStorageLocations="") %}
{% set nsVariables = namespace(nsCurrentSourceStorageLocations="") %}
{% set nsVariables = namespace(nsCurrentTargetStorageLocations="") %}
{% set nsVariables = namespace(nsCurrentUsedStorageLocations="") %}
{# Current State Storage Location Info #}
{% for source in currentState.sources %}
{% for dep in source.dependencies %}
{% set depSourceLocation = dep.node.location.name %}
{% if loop.first %}
{% set nsVariables.nsCurrentDepStorageLocations = depSourceLocation %}
{% else %}
{% set nsVariables.nsCurrentDepStorageLocations = nsVariables.nsCurrentDepStorageLocations + ',' + depSourceLocation %}
{% endif %}
{% endfor %}
{% if loop.first %}
{% set nsVariables.nsCurrentSourceStorageLocations = nsVariables.nsCurrentDepStorageLocations %}
{% else %}
{% set nsVariables.nsCurrentSourceStorageLocations = nsVariables.nsCurrentSourceStorageLocations + ',' + nsVariables.nsCurrentDepStorageLocations %}
{% endif %}
{% endfor %}
{% set nsVariables.nsCurrentTargetStorageLocations = currentState.node.location.name %}
{% set nsVariables.nsCurrentUsedStorageLocations = nsVariables.nsCurrentSourceStorageLocations + ',' + nsVariables.nsCurrentTargetStorageLocations %}
{% set currentStorageLocations = (nsVariables.nsCurrentUsedStorageLocations).split(',') | list %}
{% set currentUniqueStorageLocations = currentStorageLocations | unique | sort | list %}
{# Desired Namespace Variables #}
{% set nsVariables = namespace(nsDesiredDepStorageLocations="") %}
{% set nsVariables = namespace(nsDesiredSourceStorageLocations="") %}
{% set nsVariables = namespace(nsDesiredTargetStorageLocations="") %}
{% set nsVariables = namespace(nsDesiredUsedStorageLocations="") %}
{% set nsVariables = namespace(storageLocationTest="") %}
{# Desired State Storage Location Info #}
{% for source in desiredState.sources %}
{% for dep in source.dependencies %}
{% set depSourceLocation = dep.node.location.name %}
{% if loop.first %}
{% set nsVariables.nsDesiredDepStorageLocations = depSourceLocation %}
{% else %}
{% set nsVariables.nnsDesiredDepStorageLocations = nsVariables.nsDesiredDepStorageLocations + ',' + depSourceLocation %}
{% endif %}
{% endfor %}
{% if loop.first %}
{% set nsVariables.nsDesiredSourceStorageLocations = nsVariables.nsDesiredDepStorageLocations %}
{% else %}
{% set nsVariables.nsDesiredSourceStorageLocations = nsVariables.nsDesiredSourceStorageLocations + ',' + nsVariables.nsDesiredDepStorageLocations %}
{% endif %}
{% endfor %}
{% set nsVariables.nsDesiredTargetStorageLocations = desiredState.node.location.name %}
{% set nsVariables.nsDesiredUsedStorageLocations = nsVariables.nsDesiredSourceStorageLocations + ',' + nsVariables.nsDesiredTargetStorageLocations %}
{% set desiredStorageLocations = (nsVariables.nsDesiredUsedStorageLocations).split(',') | list %}
{% set desiredUniqueStorageLocations = desiredStorageLocations | unique | sort | list %}
{# Test #}
{% set nsVariables.storageLocationTest = true %}
{% set nodeCommentTest = currentState.node.description == desiredState.node.description %}
{% for name in desiredUniqueStorageLocations if nsVariables.storageLocationTest == true %}
{# Current mappings #}
{% set currentDatabase = currentState.storageLocations | selectattr('name', 'equalto', name) | map(attribute='database') | first %}
{% set currentSchema = currentState.storageLocations | selectattr('name', 'equalto', name) | map(attribute='schema') | first %}
{% set currentDatabaseSchema = currentDatabase + '.' + currentSchema %}
{# Desired mappings #}
{% set desiredDatabase = desiredState.storageLocations | selectattr('name', 'equalto', name) | map(attribute='database') | first %}
{% set desiredSchema = desiredState.storageLocations | selectattr('name', 'equalto', name) | map(attribute='schema') | first %}
{% set desiredDatabaseSchema = desiredDatabase + '.' + desiredSchema %}
{% if currentDatabaseSchema != desiredDatabaseSchema %}
{% set nsVariables.storageLocationTest = false %}
{% endif %}
{% endfor %}
{# Clustering Test #}
{% set clusterKeyTest = currentState.config.clusterKey == desiredState.config.clusterKey %}
{% set clusterKeyExpressionsTest = currentState.config.clusterKeyExpressions == desiredState.config.clusterKeyExpressions %}
{% set clusterKeyConfigTest = currentState.config.clusterKeyConfig == desiredState.config.clusterKeyConfig %}
{% set clusterKeyConfigExpressionsTest = currentState.config.clusterKeyConfigExpressions == desiredState.config.clusterKeyConfigExpressions %}
{% if
clusterKeyTest == false or
clusterKeyExpressionsTest == false or
clusterKeyConfigTest == false or
clusterKeyConfigExpressionsTest == false %}
{% set clusterTest = false %}
{% else %}
{% set clusterTest = true %}
{% endif %}
{# Rename / Move Object #}
{% if (nsVariables.storageLocationTest == false or currentState.node.name != desiredState.node.name) %}
{{ stage('Rename and / or Move Table', true, "sql", "alter") }}
ALTER TABLE {{ ref_no_link(currentState.node.location.name, currentState.node.name) }}
RENAME TO {{ ref_no_link(desiredState.node.location.name, desiredState.node.name) }}
{% endif %}
{# Change table description #}
{% if (nsVariables.nodeCommentTest == false or currentState.node.description != desiredState.node.description) %}
{{ stage('Change table description', true, "sql", "alter") }}
ALTER TABLE {{ ref_no_link(desiredState.node.location.name, desiredState.node.name) }}
SET COMMENT = '{{ desiredState.node.description | escape }}'
{% endif %}
{# Drop Columns #}
{% set nsVariables = namespace(colchanges=0) %}
{% for dropCurCol in currentState.columns %}
{% if dropCurCol.id not in desiredState.columns | map(attribute="id") %}
{% set nsVariables.colchanges = nsVariables.colchanges + 1 %}
{% if nsVariables.colchanges == 1 %}
{{ stage('Drop Columns', true, "sql", "alter") }}
ALTER TABLE {{ ref_no_link(desiredState.node.location.name, desiredState.node.name) }}
DROP COLUMN
{% else %}
,
{% endif %}
"{{ dropCurCol.name }}"
{% endif %}
{% endfor %}
{# Add Columns #}
{% set nsVariables = namespace(colchanges=0) %}
{% for addDesCol in desiredState.columns %}
{% if addDesCol.id not in currentState.columns | map(attribute="id") %}
{% set nsVariables.colchanges = nsVariables.colchanges + 1 %}
{% if nsVariables.colchanges == 1 %}
{{ stage('Add Columns', true, "sql", "alter") }}
ALTER TABLE {{ ref_no_link(desiredState.node.location.name, desiredState.node.name) }}
ADD COLUMN
{% else %}
,
{% endif %}
"{{ addDesCol.name }}" {{ addDesCol.dataType }}
{%- if not addDesCol.nullable %} NOT NULL
{%- if addDesCol.defaultValue | length > 0 %} DEFAULT {{ addDesCol.defaultValue }}{% endif %}
{% endif %}
{%- if addDesCol.description | length > 0 %} COMMENT '{{ addDescol.description | escape }}'{% endif %}
{% endif %}
{% endfor %}
{# Rename Columns #}
{% for renameCurCol in currentState.columns %}
{% if renameCurCol.id in desiredState.columns | map(attribute="id") %}
{% set desiredColumnName = desiredState.columns | selectattr('id', 'equalto', renameCurCol.id) | map(attribute='name') | first %}
{% if renameCurCol.name != desiredColumnName %}
{{ stage('Rename Column ' + renameCurCol.name, true, "sql", "alter") }}
ALTER TABLE {{ ref_no_link(desiredState.node.location.name, desiredState.node.name) }}
RENAME COLUMN "{{ renameCurCol.name }}"
TO "{{ desiredColumnName }}"
{% endif %}
{% endif %}
{% endfor %}
{# Change data types or other column level chnages #}
{% set nsVariables.colchanges = 0 %}
{% for alterCurCol in currentState.columns %}
{% if alterCurCol.id in desiredState.columns | map(attribute="id") %}
{% set currentDatatype = alterCurCol.dataType %}
{% set currentNullable = alterCurCol.nullable %}
{% set currentDefaultValue = alterCurCol.defaultValue %}
{% set currentDescription = alterCurCol.description %}
{% set desiredColumnName = desiredState.columns | selectattr('id', "equalto", alterCurCol.id) | map(attribute='name') | first %}
{% set desiredDatatype = desiredState.columns | selectattr('id', "equalto", alterCurCol.id) | map(attribute='dataType') | first %}
{% set desiredNullable = desiredState.columns | selectattr('id', "equalto", alterCurCol.id) | map(attribute='nullable') | first %}
{% set desiredDefaultValue = desiredState.columns | selectattr('id', "equalto", alterCurCol.id) | map(attribute='defaultValue') | first %}
{% set desiredDescription = desiredState.columns | selectattr('id', "equalto", alterCurCol.id) | map(attribute='description') | first %}
{% set datatypeTest = currentDatatype == desiredDatatype %}
{% set nullableTest = currentNullable == desiredNullable %}
{% set defaultValueTest = currentDefaultValue == desiredDefaultValue %}
{% set descriptionTest = currentDescription == desiredDescription %}
{% if (datatypeTest == false or
nullableTest == false or
defaultValueTest == false or
descriptionTest == false) %}
{% set nsVariables.colchanges = nsVariables.colchanges + 1 %}
{% if nsVariables.colchanges == 1 %}
{{ stage('Change Column Attributes', true, "sql", "alter") }}
ALTER TABLE {{ ref_no_link(desiredState.node.location.name, desiredState.node.name) }}
MODIFY
{% endif %}
{% if datatypeTest == false %}
{% if nsVariables.colchanges > 1 %},{% endif %}
COLUMN "{{ desiredColumnName }}"
SET DATA TYPE {{ desiredDatatype }}
{% set nsVariables.colchanges = nsVariables.colchanges + 1 %}
{% endif %}
{% if nullableTest == false %}
{% if nsVariables.colchanges > 1 %},{% endif %}
COLUMN "{{ desiredColumnName }}"
{% if currentNullable == true %}
SET
{% else %}
DROP
{% endif %}
NOT NULL
{% set nsVariables.colchanges = nsVariables.colchanges + 1 %}
{% endif %}
{% if descriptionTest == false %}
{% if nsVariables.colchanges > 1 %},{% endif %}
COLUMN "{{ desiredColumnName }}"
COMMENT '{{ desiredDescription }}'
{% set nsVariables.colchanges = nsVariables.colchanges + 1 %}
{% endif %}
{% if defaultValueTest == false %}
{% if nsVariables.colchanges > 1 %},{% endif %}
COLUMN "{{ desiredColumnName }}"
{% if desiredDefaultValue == '' %}
DROP DEFAULT
{% else %}
SET DEFAULT {{ desiredDefaultValue }}
{% endif %}
{% set nsVariables.colchanges = nsVariables.colchanges + 1 %}
{% endif %}
{% else %}
{% endif %}
{% endif %}
{% endfor %}
{# Figure out cluster key #}
{% set nsVariables = namespace(finalClusterKey="") %}
{% if clusterTest == false %}
{% if desiredState.config.clusterKeyExpressions == true %}
{% set column, expression = desiredState.config.clusterKeyConfigExpressions.get('items') | map(attribute='columnNameExpressions.name') | list, desiredState.config.clusterKeyConfigExpressions.get('items') | map(attribute='sqlExpression') | list %}
{%- set nsVariables = namespace(clusterValues=[]) %}
{% for r in column %}
{% if expression[loop.index0] == "" %}
{% set nsVariables.clusterValues = nsVariables.clusterValues + [r] %}
{% else %}
{% set nsVariables.clusterValues = nsVariables.clusterValues + [expression[loop.index0]] %}
{% endif %}
{% endfor %}
{% set nsVariables.finalClusterKey = 'CLUSTER BY (' + nsVariables.clusterValues | join(',') + ')' %}
{% elif desiredState.config.clusterKey == true %}
{% set column = desiredState.config.clusterKeyConfig.get('items') | map(attribute='columnName.name') | list %}
{%- set nsVariables = namespace(clusterValues=[]) %}
{% for r in column %}
{% set nsVariables.clusterValues = nsVariables.clusterValues + [r] %}
{% endfor %}
{% set nsVariables.finalClusterKey = 'CLUSTER BY (' + nsVariables.clusterValues | join(',') + ')' %}
{% else %}
{% set nsVariables.finalClusterKey = 'DROP CLUSTERING KEY' %}
{% endif %}
{{ stage('Recluster TABLE', true, "sql", "create") }}
ALTER TABLE {{ ref_no_link(desiredState.node.location.name, desiredState.node.name) }}
{{ nsVariables.finalClusterKey }}
{% endif %}
{% endif %}
{% elif currentState != undefined and desiredState == undefined %}
{# Table or View Name #}
{% set targetObjectDatabase = ref_no_link(currentState.node.location.name, currentState.node.name).split('.')[0] %}
{% set targetObjectSchema = ref_no_link(currentState.node.location.name, currentState.node.name).split('.')[1] %}
{% set fullyQualifiedTargetObjectName = ref_no_link(currentState.node.location.name, currentState.node.name) %}
{{ stage('Drop Table', true, "sql", "drop") }}
DROP {{ currentState.node.materializationType }} IF EXISTS {{ fullyQualifiedTargetObjectName }}
{%- else -%}
{{ stage('No table edits. Unknown state.') }}
select 1 = 0
{% endif %}
{# Create Task Second #}
{% if desiredState == currentState %}
{{ stage('No task edits.') }}
select 1 = 0
{% elif desiredState %}
{# Target Table Info #}
{% set targetTableDatabase = ref_no_link(desiredState.node.location.name, desiredState.node.name).split('.')[0] %}
{% set targetTableSchema = ref_no_link(desiredState.node.location.name, desiredState.node.name).split('.')[1] %}
{% set fullyQualifiedTargetTableName = ref_no_link(desiredState.node.location.name, desiredState.node.name) %}
{% if desiredState.config.devMode == false %}
{%- if desiredState.config.schedulePeriodOption == 'Predecessor' -%}
{%- set fullyQualifiedRootTaskName = targetTableDatabase + '.' + targetTableSchema + '."' + desiredState.config.rootTask + '"' -%}
{{ stage('Suspend Root Task', true, "sql", "alter") }}
ALTER TASK {{ fullyQualifiedRootTaskName }} SUSPEND
{%- endif -%}
{{ stage('Create Task', true, "sql", "alter") }}
{# Set Namespace Variables #}
{% set nsVariables = namespace(taskWhenRun="") %}
{% set nsVariables = namespace(poll="WHEN ") %}
{# Task Info #}
{% set taskName = desiredState.node.name + '_TASK' %}
{%- set fullyQualifiedTaskName = targetTableDatabase + '.' + targetTableSchema + '."' + taskName + '"' -%}
{# Task Type #}
{%- if desiredState.config.schedulingMode == 'Warehouse Task' -%}
{# Can be updated during deployment via a parameter to account for different warehouse names in different deployments #}
{% if desiredState.parameters.targetTaskWarehouse == 'DEV ENVIRONMENT' %}
{% set taskType = 'WAREHOUSE = ' + desiredState.config.whName %}
{% else %}
{% set taskType = 'WAREHOUSE = ' + desiredState.parameters.targetTaskWarehouse %}
{% endif %}
{%- else -%}
{%- set taskType = 'USER_TASK_MANAGED_INITIAL_WAREHOUSE_SIZE = ' + desiredState.config.serverlessSize -%}
{%- endif -%}
{# Schedule Type #}
{%- if desiredState.config.schedulePeriodOption == 'Minutes' -%}
{%- set nsVariables.taskWhenRun = 'SCHEDULE = ' + "'" + desiredState.config.schedulePeriod + ' MINUTE' + "'" -%}
{% elif desiredState.config.schedulePeriodOption == 'CRON' %}
{%- set nsVariables.taskWhenRun = 'SCHEDULE = ' + "'" + 'USING CRON ' + desiredState.config.scheduleCRON + "'" %}
{%- else -%}
{%- set nsVariables.taskWhenRun = 'AFTER ' -%}
{%- set predecessorTasks = (desiredState.config.predTask).split(",") -%}
{%- for p in predecessorTasks -%}
{%- set nsVariables.taskWhenRun = nsVariables.taskWhenRun + targetTableDatabase + '.' + targetTableSchema + '.' + p -%}
{%- if not loop.last -%}
{%- set nsVariables.taskWhenRun = nsVariables.taskWhenRun + ',' -%}
{%- endif %}
{% endfor %}
{%- endif -%}
{# When Stream has data logic #}
{# Source Stream Location and Name #}
{% if desiredState.config.flagSrcStream == true %}
{% for source in desiredState.sources %}
{% for dep in source.dependencies %}
{% if (dep.node.materializationType == 'stream') %}
{% set streamStorageLocation = dep.node.location.name %}
{% set streamSourceDatabase = desiredState.storageLocations | selectattr('name', 'equalto', streamStorageLocation) | map(attribute='database') | first %}
{% set streamSourceSchema = desiredState.storageLocations | selectattr('name', 'equalto', streamStorageLocation) | map(attribute='schema') | first %}
{% set streamSourceName = dep.node.name %}
{%- if nsVariables.poll == 'WHEN ' -%}
{% set nsVariables.poll = nsVariables.poll + 'SYSTEM$STREAM_HAS_DATA(\'"' + streamSourceDatabase + '"."' + streamSourceSchema + '"."' + streamSourceName + '"\')' %}
{% else %}
{% set nsVariables.poll = nsVariables.poll + desiredState.config.multiStreamBehavior + ' SYSTEM$STREAM_HAS_DATA(\'"' + streamSourceDatabase + '"."' + streamSourceSchema + '"."' + streamSourceName + '"\')' %}
{%- endif -%}
{%- endif -%}
{% endfor %}
{% endfor %}
{% endif -%}
{# To mimic truncate behavior #}
{% if desiredState.config.truncateBefore == true %}
{% set truncateBehavior = 'INSERT OVERWRITE' %}
{% else %}
{% set truncateBehavior = 'INSERT' %}
{% endif -%}
CREATE OR REPLACE TASK
{{ fullyQualifiedTaskName }}
{{ taskType}}
{{ nsVariables.taskWhenRun }}
{% if nsVariables.poll != 'WHEN ' %} {{ nsVariables.poll }} {% endif %}
AS
{% set has_business_key = desiredState.columns | selectattr('isBusinessKey') | list | length > 0 %}
{% if has_business_key %}
/* If has business key then MERGE */
MERGE INTO {{ fullyQualifiedTargetTableName }} "TGT" USING (
{% for source in desiredState.sources %}
/* Combine Sources if needed */
{% if loop.first %}
( SELECT {% if desiredState.config.selectDistinct %} DISTINCT {% endif %}
{% for col in source.columns %}
{% if (col.isSystemUpdateDate or col.isSystemCreateDate) %}
{{ col.transform }} AS "{{ col.name }}"
{% else %}
"{{ col.name }}" AS "{{ col.name }}"
{% endif %}
{% if not loop.last %}, {% endif %}
{% endfor %}
FROM (
{% endif %}
SELECT {% if desiredState.config.selectDistinct %} DISTINCT {% endif %}
{% for col in source.columns if not (col.isSurrogateKey or col.isSystemCreateDate or col.isSystemUpdateDate ) %}
{{ get_source_transform(col) }} AS "{{ col.name }}"{% if not loop.last %}, {% endif %}
{% endfor %}
{{ source.join }}
{% if not loop.last %}
{{ desiredState.config.insertStrategy }}
{% endif %}
{% if loop.last %}
)
{% endif %}
{% endfor %}
{% if desiredState.config.groupByAll %}GROUP BY ALL{% endif %}
{{sortorder_by_colv()}})
) AS "SRC"
ON
{% for col in desiredState.columns if col.isBusinessKey -%}
{% if not loop.first %}
AND
{% endif %}
"SRC"."{{ col.name }}" = "TGT"."{{ col.name }}"
{% endfor %}
WHEN MATCHED
{% for col in desiredState.columns if not (col.isBusinessKey or
col.isSystemUpdateDate or
col.isSystemCreateDate) %}
{% if loop.first %}
AND (
{% else %}
OR
{% endif %}
NVL( CAST("SRC"."{{ col.name }}" as STRING), '**NULL**') <> NVL( CAST("TGT"."{{ col.name }}" as STRING), '**NULL**')
{% if loop.last %}
)
{% endif %}
{% endfor %}
THEN UPDATE SET
{%- for col in desiredState.columns if not (col.isBusinessKey or col.isSystemCreateDate) %}
"TGT"."{{ col.name }}" = "SRC"."{{ col.name }}"
{% if not loop.last %}, {% endif %}
{% endfor %}
WHEN NOT MATCHED THEN
INSERT (
{%- for col in desiredState.columns if not col.isSurrogateKey %}
"{{ col.name }}"
{% if not loop.last %}, {% endif %}
{% endfor -%}
)
VALUES (
{%- for col in desiredState.columns if not col.isSurrogateKey %}
"SRC"."{{ col.name }}"
{% if not loop.last %}, {% endif %}
{% endfor -%}
)
{% else %}
/* No Business Key */
INSERT INTO {{ fullyQualifiedTargetTableName }}
(
{% for col in desiredState.columns %}
"{{ col.name }}"
{%- if not loop.last -%},{% endif %}
{% endfor %}
)
{% for source in desiredState.sources %}
/* Combine Sources if needed */
{% if loop.first %}
( SELECT {% if desiredState.config.selectDistinct %} DISTINCT {% endif %}
{% for col in desiredState.columns %}
"{{ col.name }}" AS "{{ col.name }}"
{% if not loop.last %}, {% endif %}
{% endfor %}
FROM
{% endif %}
( SELECT {% if desiredState.config.selectDistinct %} DISTINCT {% endif %}
{% for col in source.columns if not col.isSurrogateKey %}
{{ get_source_transform(col) }} AS "{{ col.name }}"{% if not loop.last %}, {% endif %}
{% endfor %}
{{ source.join }}
{% if desiredState.config.groupByAll %}GROUP BY ALL{% endif %}
{{ sortorder_by_colv() }})
{% if not loop.last %}
{{ desiredState.config.insertStrategy }}
{% endif %}
{% if loop.last %}
)
{% endif %}
{% endfor %}
{% endif %}
{%- if desiredState.config.schedulePeriodOption != 'Predecessor' -%}
{{ stage('Resume Created Task', true, "sql", "alter") }}
ALTER TASK {{ fullyQualifiedTaskName }} RESUME;
{%- endif -%}
{% else %}
{{ stage('Development Mode - No Task.') }}
select 1 = 0
{%- endif -%}
{% elif currentState != undefined and desiredState == undefined %}
{# Target Table Info #}
{% set targetTableDatabase = ref_no_link(currentState.node.location.name, currentState.node.name).split('.')[0] %}
{% set targetTableSchema = ref_no_link(currentState.node.location.name, currentState.node.name).split('.')[1] %}
{% set fullyQualifiedTargetTableName = ref_no_link(currentState.node.location.name, currentState.node.name) %}
{% if currentState.config.devMode == false %}
{# FQ Root Task name #}
{% set fullyQualifiedRootTaskName = targetTableDatabase + '.' + targetTableSchema + '."' + currentState.config.rootTask + '"'%}
{# Task Info #}
{% set taskName = currentState.node.name + '_TASK' %}
{%- set fullyQualifiedTaskName = targetTableDatabase + '.' + targetTableSchema + '."' + taskName + '"' -%}
{%- if currentState.config.schedulePeriodOption == 'Predecessor' -%}
{{ stage('Suspend Root Task', true, "sql", "drop") }}
ALTER TASK IF EXISTS {{ fullyQualifiedRootTaskName }} SUSPEND
{{ stage('Drop Current Task', true, "sql", "drop") }}
DROP TASK IF EXISTS {{ fullyQualifiedTaskName }}
{%- else -%}
{{ stage('Drop Current Task', true, "sql", "drop") }}
DROP TASK IF EXISTS {{ fullyQualifiedTaskName }}
{%- endif -%}
{%- endif -%}
{%- else -%}
{{ stage('No task edits. Unknown state.') }}
select 1 = 0
{% endif %}