Skip to content

Commit

Permalink
Add safe add macro (#191)
Browse files Browse the repository at this point in the history
* Add safe add macro

* Use do instead of set
  • Loading branch information
invinceyble authored Feb 17, 2020
1 parent 26958a5 commit b1a156c
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 0 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -498,6 +498,14 @@ Usage:
{{ dbt_utils.surrogate_key('field_a', 'field_b'[,...]) }}
```

#### safe_add ([source](macros/sql/safe_add.sql))
Implements a cross-database way to sum nullable fiellds using the fields specified.

Usage:
```
{{ dbt_utils.safe_add('field_a', 'field_b'[,...]) }}
```

#### pivot ([source](macros/sql/pivot.sql))
This macro pivots values from rows to columns.

Expand Down
5 changes: 5 additions & 0 deletions integration_tests/data/sql/data_safe_add.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
field_1,field_2,field_3,expected
1,2,3,6
1,,3,4
,,2,2
,,,0
6 changes: 6 additions & 0 deletions integration_tests/models/sql/schema.yml
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,12 @@ models:
tests:
- not_empty_string

- name: test_safe_add
tests:
- assert_equal:
actual: actual
expected: expected

- name: test_pivot
tests:
- dbt_utils.equality:
Expand Down
12 changes: 12 additions & 0 deletions integration_tests/models/sql/test_safe_add.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@

with data as (

select * from {{ ref('data_safe_add') }}

)

select
{{ dbt_utils.safe_add('field_1', 'field_2', 'field_3') }} as actual,
expected

from data
13 changes: 13 additions & 0 deletions macros/sql/safe_add.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{%- macro safe_add() -%}

{% set fields = [] %}

{%- for field in varargs -%}

{% do fields.append("coalesce(" ~ field ~ ", 0)") %}

{%- endfor -%}

{{ fields|join(' +\n ') }}

{%- endmacro -%}

0 comments on commit b1a156c

Please sign in to comment.