Custom materialization: Fail if table already exists

The problem I’m having

The default table materialization will recreate the target table if it already exists. I would like to create a custom materialization (or hear about any alternatives) that will fail if that table already exists.

FYI: we are using dbt-bigquery, in case that’s relevant.

What I’ve already tried

I have tried following the create new materializations guide and read the materialization source code, but there is so much redirection and macros that I can’t figure out what portion of the code would need to be modified.

Ended up solving this by creating a macro that checks if the table exists, rather than creating a custom materialization :slight_smile:

{% macro fail_if_model_exists() %}

    {% set relation = adapter.get_relation(this.database, this.schema, this.name) %}
    {% if relation is not none %}
        {{ exceptions.raise_compiler_error("model " ~ relation ~ " already exists!") }}
    {% endif %}

{% endmacro %}
# dbt_project.py
models:
    pre-hook:
        - "{{ fail_if_model_exists() }}"

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