|
119 | 119 | on {{ unique_key_join_on(strategy.unique_key, "snapshotted_data", "source_data") }}
|
120 | 120 | where {{ unique_key_is_null(strategy.unique_key, "snapshotted_data") }}
|
121 | 121 | or ({{ unique_key_is_not_null(strategy.unique_key, "snapshotted_data") }} and ({{ strategy.row_changed }})
|
122 |
| - |
| 122 | + {%- if strategy.hard_deletes == 'new_record' -%} |
| 123 | + or ({{ unique_key_is_not_null(strategy.unique_key, "snapshotted_data") }} and snapshotted_data.{{ columns.dbt_is_deleted }} = 'True') |
| 124 | + {%- endif %} |
123 | 125 | )
|
124 | 126 |
|
125 | 127 | ),
|
|
140 | 142 | where (
|
141 | 143 | {{ strategy.row_changed }}
|
142 | 144 | )
|
| 145 | + {%- if strategy.hard_deletes == 'new_record' -%} |
| 146 | + or snapshotted_data.{{ columns.dbt_is_deleted }} = 'True' |
| 147 | + {%- endif %} |
143 | 148 | )
|
144 | 149 |
|
145 | 150 | {%- if strategy.hard_deletes == 'invalidate' or strategy.hard_deletes == 'new_record' -%}
|
|
162 | 167 | left join deletes_source_data source_data
|
163 | 168 | on {{ unique_key_join_on(strategy.unique_key, "snapshotted_data", "source_data") }}
|
164 | 169 | where {{ unique_key_is_null(strategy.unique_key, "source_data") }}
|
| 170 | + {%- if strategy.hard_deletes == 'new_record' %} |
| 171 | + and not ( |
| 172 | + --avoid updating the record's valid_to if the latest entry is marked as deleted |
| 173 | + snapshotted_data.{{ columns.dbt_is_deleted }} = 'True' |
| 174 | + and |
| 175 | + {% if config.get('dbt_valid_to_current') %} |
| 176 | + {% set source_unique_key = columns.dbt_valid_to | trim %} |
| 177 | + {% set target_unique_key = config.get('dbt_valid_to_current') | trim %} |
| 178 | + ( {{ equals(source_unique_key, target_unique_key) }} or {{ source_unique_key }} is null ) |
| 179 | + {% else %} |
| 180 | + {{ columns.dbt_valid_to }} is null |
| 181 | + {% endif %} |
| 182 | + ) |
| 183 | + {%- endif %} |
| 184 | + |
165 | 185 | )
|
166 | 186 | {%- endif %}
|
167 | 187 |
|
|
191 | 211 | left join deletes_source_data source_data
|
192 | 212 | on {{ unique_key_join_on(strategy.unique_key, "snapshotted_data", "source_data") }}
|
193 | 213 | where {{ unique_key_is_null(strategy.unique_key, "source_data") }}
|
194 |
| - |
| 214 | + and not ( |
| 215 | + --avoid inserting a new record if the latest one is marked as deleted |
| 216 | + snapshotted_data.{{ columns.dbt_is_deleted }} = 'True' |
| 217 | + and |
| 218 | + {% if config.get('dbt_valid_to_current') %} |
| 219 | + {% set source_unique_key = columns.dbt_valid_to | trim %} |
| 220 | + {% set target_unique_key = config.get('dbt_valid_to_current') | trim %} |
| 221 | + ( {{ equals(source_unique_key, target_unique_key) }} or {{ source_unique_key }} is null ) |
| 222 | + {% else %} |
| 223 | + {{ columns.dbt_valid_to }} is null |
| 224 | + {% endif %} |
| 225 | + ) |
195 | 226 | )
|
196 | 227 | {%- endif %}
|
197 | 228 |
|
|
0 commit comments