Can dbt macros accept other macros as arguments?
Asked Answered
H

2

9

I am curious if I can pass macros into another macro like this:

{% macro my_macro(a, b, another_macro) %}
  ...
  {{ another_macro(a,b) }}
  ...
{% endmacro %}

BONUS: If dbt's framework can allow it am able to how can I pass arguments to it?

In R it would look like

my_callable_function <- function(another_function, ...) {
  another_function(...)
}
Hiccup answered 6/9, 2021 at 18:54 Comment(0)
H
12

A conversation on dbt cloud's slack and a bit of poking and prodding yielded me the answer.

Yes you can pass nested macros into a macro much like nested functions in different languages!

An example could look like this!

{% macro base_macro(func1, arg1, arg2) %}
  {{ func1(arg1, arg2) }}
{% endmacro %}
Hiccup answered 7/9, 2021 at 21:3 Comment(0)
F
2

i am not sure but if you are calculating something in dbt for example

{% macro sum_of_two_columns(a, b) %}
  a + b
 
{% endmacro %}

then in your model file you will have something like

select 
revenue1,
revenue2,
{{ sum_of_two_columns('revenue1','revenue2') }} as total_revenue

from [table]

now you can pass the total_revenue in your second macro that you would like to create: for example:

{% macro subtracting_column(a) %}
  a - 100
{% endmacro %}

finally you can use it :

    select 
    revenue1,
    revenue2,
    {{ sum_of_two_columns('revenue1','revenue2') }} as total_revenue,
    {{ subtracting_column('total_revenue') }} as adjusted_revenue
    
    from [table]

In short you will be passing the results of one macro to another which is what you want

Fourdimensional answered 6/9, 2021 at 19:17 Comment(3)
Unsure I follow your final example. Your subtracting_column is not accepting the expected total_revenue argument for your example.Hiccup
Yes that's a typo, fixed nowFourdimensional
@ReidWilliams did you checkFourdimensional

© 2022 - 2024 — McMap. All rights reserved.