Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Principle:173TECH Sayn Jinja2 Compilation

From Leeroopedia
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 applied
  • out(): Resolves an output database object name with dev/prod naming rules applied
  • config(): 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_load as globals
  • Task context: task.name and task.group available 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:

  • FileSystemLoader rooted at the project directory
  • StrictUndefined to catch undefined variables
  • Two environments: env (dev parameters) and prod_env (prod parameters)

The two-pass compilation for SQL tasks:

  1. Pass 1 (stub): src()/out() collect object strings without resolving; config() captures overrides
  2. 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 }}'

Related Pages

Implemented By

Uses Heuristic

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment