The most common use of Jinja in data models is to apply row-level security using the security context, like so:
cubes:
- name: customers
title: My customers
sql: >
select *
from public.customers
where organisationId = '{ COMPILE_CONTEXT.securityContext.organisationId }'
The {
and }
syntax is not actually a syntax that your database is expected to understand. This is the syntax for a pre-processor called Jinja (official documentation).
The above SQL will actually be compiled to something like the below, before being sent to your database:
select *
from public.customers
where organisationId = 'abc123'
The nice thing about jinja is that it can also be used to handle more complex use cases like:
cubes:
- name: customers
title: My customers
sql: >
select *
from public.customers
{% if COMPILE_CONTEXT.securityContext.superUser %}
where 1 = 1
{% else %}
where organisationId = '{ COMPILE_CONTEXT.securityContext.organisationId }'
{% endif %}
which will compile to the following for super users:
select *
from public.customers
where 1 = 1
For cases where your security context contains an array of items:
- name: Example customer 1
securityContext:
countries:
- United States
- Canada
- Mexico
You can use our list
helper function like so:
cubes:
- name: customers
title: My customers
sql: >
select *
from public.customers
where country in {{ list(COMPILE_CONTEXT.securityContext.countries) }}
which will generate SQL like so:
select *
from public.customers
where country in ('United States', 'Canada', 'Mexico')