I know that it's possible to reference the database, schema and tables inside a SQL file/model in dbt. Example:
select
'{{ this }}' as full_path,
'{{ this.schema }}' as schema_name,
'{{ this.database }}' as db_name,
'{{ this.table }}' as table_name
However, I was looking for a way to also get the folder where a certain .sql file is inside. In my mind, I'd guess something like this: {{ this.folder }}
. But unfortunately, It does not work.
Any ideas?
CodePudding user response:
this
is a Relation, which is a reference to an object in your database, not a reference to the Model that produced the Relation (which is a file in your project).
The graph
context variable contains the path for each model; it used to be hard to access the current model's node programmatically, since it's keyed by the project and model name, but dbt solved that by adding in the model
variable, which does just that.
{{ model.path }}
will give you the full path to the model file (relative to the models folder, so marts/marketing/orders.sql
if your file is in /models/marts/marketing/orders.sql
). You can also use {{ model.root_path }}
for the path to your project root (e.g., /home/tco/open/jaffle_shop
)
If you just want the folder, you'll have to munge the path
a bit:
{% if execute %}
{% set path = model.path %} -- e.g. 'marts/marketing/orders.sql'
{% set path_list = path.split('/') %} -- e.g. ['marts', 'marketing', 'orders.sql']
{% set folder = path_list[:-1] | join('/') %} -- e.g., 'marts/marketing'
{% endif %}