Search code examples
snowflake-cloud-data-platformdbt

How to rename the model in DBT During the DBT run


I need to rename the model name of the DBT during the excuion ther is a config alias property in DBt but it is not rename in a dynamic way for example if we build a macro to do that rename and used it in config alias It give erro of undefind name

using macro but did not work as expected with config alias


Solution

  • This what I did for the same issue , created macro that execute the alter view rename

    {% macro alter_view_name(filter1,filter2,alt_name) %}

    USE SCHEMA SVS_PSO ;
       EXECUTE IMMEDIATE $$
        DECLARE
        CustomName    STRING;
        QUERY        STRING;
        BEGIN
        CustomName:= ( select '{{ alt_name }}'||'_'||to_char(max(DATA_CREATE_DT),'yyyymmdd')  
            from {{ ref('yourtable')}}
            where col1 ilike '%{{ filter1 }}%' and col2 ilike  '%{{ filter2 }}%' );
        QUERY:= REPLACE(
                'drop View if exists <cust_name> ;'
                ,'<cust_name>', :CustomName);    
        EXECUTE IMMEDIATE :QUERY;     
        QUERY:= REPLACE(
                'alter View if exists {{ this }} rename to <cust_name> ;'
                ,'<cust_name>', :CustomName);    
        EXECUTE IMMEDIATE :QUERY;  
        RETURN :QUERY;
        END;
       $$;
    

    {% endmacro %}

    then I added this macro as post_hook at the desired view:

    {{ config ( materialized='view',
        post_hook = [" {{ alter_view_name('filter1','filter2','alternative_name') }}"]) 
    }}
    

    hope this be helpful