How to alias the model being built only?

Hello!

Is it possible to automatically alias only the model that is being built (using generate_alias_name) and not all models?

For example, if I run dbt run -m model_name I want model_name model to have database identifier as dbtuser_model_name so multiple data analysts can build the same model in the playground schema without collisions?

Basically I want to conditionally override the name of the model. Is it possible to extract some JInja variable that tells that this or that model is a model that is being build (not ref’ed).

pass a variable form dbt command and return alias name based on the variable in generate_alias_name macro

dbt run -m model_name --vars 'add_database_to_model_name: true'

{% macro generate_alias_name(custom_alias_name=none, node=none) -%}

    {%- if custom_alias_name is none -%}

        {{ node.name }}

    {%- elif  var(add_database_to_model_name, false) == true -%}

        {{ "dbtuser_{}".fromat(custom_alias_name ) }}

    {%- else -%}
        {{ custom_alias_name | trim }}
    {%- endif -%}

{%- endmacro %}

Thank you for your reply.

In this case all tables will be aliased with dbtuser_ prefix (not only the model that is being built). For example if we build target_model that references source_model with {{ ref('source_model') then dbt run -m target_model --vars 'add_database_to_model_name: true' will fail with the error that there is no table in the database with dbtuser_source_model identifier.

Is there a way to not alias source tables but only the model that is being built?

@evgeniy
I understood ur requirement

This can be achieved using invocation_args_dict jinja variable and node.name in the generate_alias_name macro.

I have tried with the below code, looks like its working

{% macro generate_alias_name(custom_alias_name=none, node=none) -%}

    {%- if node.name in invocation_args_dict['select'] -%}

        {%- set database_identifier = 'dbtuser_{}'.format(node.name) -%}
        {{ database_identifier }}
        
    {%- elif custom_alias_name is none -%}

        {{ node.name }}

    {%- else -%}

        {{ custom_alias_name | trim }}

    {%- endif -%}

{%- endmacro %}

Wow, this is advanced. It works! Thank you!

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