Calling a macro in a pre-hook

Hi all,

version: 2
models:
  - name: my_model
    config:
      pre-hook: "{{ assert_udf_test() }}"
Compilation Error
  Could not render {{ assert_udf_test() }}: 'assert_udf_test' is undefined

dbt-core version

Core:
  - installed: 1.5.0

Can anyone please advice me on this error.

@Sam777
yes the github issue is for calling a macro in pre-hooks from the config property in yaml files.

But if you define prehook in the model file it will work fine, for now u can go with the below approach

in your my_model.sql

{{ config(pre_hook= "{{ assert_udf_test() }}" ) }}

SELECT * FROM TABLE
1 Like

Hi @Surya
Thanks for pointing out the different approach :smiley:.

When I tried to define like this

{{ config(pre_hook= "{{ assert_udf_test() }}" ) }}

SELECT * FROM TABLE

Macro assert_udf_test

{% macro assert_udf_test()%}
    {% set input = '16' %}
    {% set expected_value = 16 %}
    {% set query = 'select  assert_udf_test (' ~ input ~ ') as result' %}
    {%- set actual_list = dbt_utils.get_query_results_as_dict(query) -%}
    {% set actual_value = actual_list['RESULT'][0] %}
    {% if actual_value != expected_value %}
        {{ exceptions.raise_compiler_error('The test is failed') }}
    {% else %}
            {{ log('Test Passed', info=True) }}
    {% endif %}
{% endmacro %}

Facing some Problem
getting this error message

Compilation Error in models (models\models.sql)
  'dict object' has no attribute 'RESULT'

But when I run the macro separately i am not facing any issues weirdly

 dbt run-operation assert_udf_test 

Please advice on this approach :smiley:

@Sam777 can you try this
i have added if execute at actual_list[‘RESULT’][0]

{% macro assert_udf_test()%}
    {% set input = '16' %}
    {% set expected_value = 16 %}
    {% set query = 'select  assert_udf_test (' ~ input ~ ') as result' %}
    {%- set actual_list = dbt_utils.get_query_results_as_dict(query) -%}
    {%- if execute -%}
            {% set actual_value = actual_list['RESULT'][0] %}
    {%- endif -%}
    {% if actual_value != expected_value %}
        {{ exceptions.raise_compiler_error('The test is failed') }}
    {% else %}
            {{ log('Test Passed', info=True) }}
    {% endif %}
{% endmacro %}
2 Likes

Hey @Surya

I Wrapped the {%- if execute -%} around the macro and it worked
awesome

{% macro assert_udf_test()%}
{%- if execute -%}
    {% set input = '16' %}
    {% set expected_value = 16 %}
    {% set query = 'select  assert_udf_test (' ~ input ~ ') as result' %}
    {%- set actual_list = dbt_utils.get_query_results_as_dict(query) -%}
    {% set actual_value = actual_list['RESULT'][0] %}
    {% if actual_value != expected_value %}
        {{ exceptions.raise_compiler_error('The test is failed') }}
    {% else %}
            {{ log('Test Passed', info=True) }}
    {% endif %}
 {% endif %}
{% endmacro %}

Thank you :smiley:

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.