Search code examples
jinja2dbt

Top folder path in dbt


I want to link our dbt models to our data warehouse. I have a few session variables I can set with a pre-hook. I want to pass metadata to these variables including the top folder of a model.

If model.path returns "abc\def\xyz.sql", I can get these to work inside a sql file as:

set client_workstation_name to '{{ model.path}}';                 
-- set client_workstation_name to 'abc\def\xyz.sql'

set client_workstation_name to '{{ model.path.split("\\")[0] }}'; 
-- set client_workstation_name to 'abc'

but I can't for the life of me figure out how to pass the folder in the yml file

models:
  dbt_test:
    +pre-hook:
      - "set client_accounting_string to '{{ this.name}}';"                # works: table name
      - "set client_application_name to '{{ model.path }}';"               # works: full path
      - "set client_workstation_name to '{{ model.path.split('\\')[0] }}';" # fails: expected token ',', got ';'

Solution

  • You're attempting to use single quotes multiple times. Move your statement into a macro.

    {%- macro some_macro() -%}
      set client_workstation_name to '{{ model.path.split("\\")[0] }}';
    {%- endmacro -%}
    
    models:
      dbt_test:
        +pre-hook:
          - "{{ some_macro() }}"