Principle:173TECH Sayn Jinja2 Compilation
| Knowledge Sources | |
|---|---|
| Domains | Template_Engine, Data_Engineering |
| Last Updated | 2026-10-17 00:00 GMT |
Overview
Technique for compiling SQL templates with project-specific macros for database object resolution, configuration overrides, and parameter substitution.
Description
Jinja2 compilation in SAYN provides three key macros within SQL templates:
src(): Resolves a source database object name with dev/prod naming rules appliedout(): Resolves an output database object name with dev/prod naming rules appliedconfig(): Allows Jinja-time overrides of task configuration (materialisation, destination, etc.)
Additionally, the compiler injects:
- Parameters: Project and task parameters as Jinja globals
- Run arguments:
start_dt,end_dt,full_loadas globals - Task context:
task.nameandtask.groupavailable in templates
The two-pass compilation pattern: SQL files are compiled first with stub src/out functions to collect referenced objects, then re-compiled with real resolvers that apply dev/prod naming.
Usage
Use this principle when SQL files need to reference database objects that may have different names in dev vs prod, or when SQL configuration needs to be specified within the SQL file itself.
Theoretical Basis
The compilation system uses the Jinja2 Environment with:
FileSystemLoaderrooted at the project directoryStrictUndefinedto catch undefined variables- Two environments:
env(dev parameters) andprod_env(prod parameters)
The two-pass compilation for SQL tasks:
- Pass 1 (stub):
src()/out()collect object strings without resolving;config()captures overrides - Pass 2 (real):
src()/out()resolve names with dev/prod stringify rules
The Prepared class enables deferred compilation: a template is prepared once but can be compiled multiple times with different globals (for from_prod recompilation).
Practical Guide
-- sql/model_orders.sql
-- Use src() for source tables, out() not needed (destination is in config)
{{ config(materialisation='incremental', delete_key='order_id') }}
SELECT
o.order_id,
o.user_id,
u.user_name,
o.order_date
FROM {{ src('raw.orders') }} o
JOIN {{ src('analytics.users') }} u
ON o.user_id = u.user_id
WHERE o.order_date >= {{ start_dt }}
Using parameters in SQL:
-- Parameters are injected as Jinja globals
SELECT * FROM {{ src('raw.events') }}
WHERE event_date >= '{{ start_date }}'