2
votes

In my dbt model definition, I want to run a config block, but only if the database type is postgresql. Is there a way to do that? Example model below:

{{
  config(
    post_hook='create index if not exists "{{ this.name }}__idx_on_key" on {{ this }} ("key")'
  )
}}

select * from {{ ref('stg_customer') }}
1

1 Answers

2
votes

{{ target.type }} will compile to the name of the adapter you're using. See docs

You can wrap your hook in an {% if target.type == 'postgres' %}...{% endif %} block. That will likely get unweildy, so I recommend creating a macro that accepts a relation as an argument:

{% macro create_index_if_pg(relation, field) %}
{% if target.type == 'postgres' %}
create index if not exists "{{ relation.name }}__idx_on_{{ field }}" on {{ relation }} ("{{ field }}")
{% endif %}
{% endmacro %}

and then call the macro from the post-hook:

{{
  config(
    post_hook='{{ create_index_if_pg(this, "key") }}'
  )
}}