Macros are reusable Jinja templates that can be called from your SQL models. They help you DRY (Don’t Repeat Yourself) your SQL code by encapsulating common patterns, calculations, or logic into reusable snippets. If you are new to Jinja, the following are some resources to get started:Documentation Index
Fetch the complete documentation index at: https://docs.pysquirrels.com/llms.txt
Use this file to discover all available pages before exploring further.
File structure
Macros are stored in themacros/ directory at the root of your Squirrels project:
Macros are loaded recursively from the
macros/ directory and its subdirectories. All macros from all files are available globally across your SQL models.Supported file extensions
Squirrels loads macro files with any of the following extensions:.sql.j2.jinja.jinja2
macros/ directory (and subdirectories) are automatically loaded when the project initializes.
Creating macros
Macros use Jinja’s{% macro %} syntax. Here’s the basic structure:
macros/my_macros.sql
Basic example
Here’s a simple macro that generates filter conditions:macros/filters.sql
Using macros in models
Macros can be used in any SQL model (builds, dbviews, or federates) by calling them with{{ macro_name(args) }}:
models/federates/fed_my_model.sql
Using the indent filter
When embedding multi-line macro output, use the indent filter to maintain proper SQL formatting:
indent specifies the number of spaces to add to each line after the first.
Built-in Jinja filters
Squirrels provides several useful Jinja filters for use in macros and models:Wraps a value in quotes. Accepts optional parameters
q (quote character, default: ') and attribute (attribute name if variable is an object, default: None).Joins a list of values with a delimiter. Accepts optional parameters
d (delimiter, default: ,) and attribute (attribute name if items are objects, default: None).Quotes each value in a list and joins them with a delimiter. Accepts optional parameters
q (quote character, default: '), d (delimiter, default: ,), and attribute (attribute name if items are objects, default: None).Macros from packages
If you use Squirrels packages (defined insquirrels.yml), macros from those packages are also available. Package macros are loaded from their respective macros/ directories before your project’s macros.
squirrels.yml
sqrl_packages/shared_analytics/macros/ will be available in your models.
When package macros and project macros have the same name, the project macro takes precedence since project macros are loaded last.
Related pages
- Build models - Static models that use macros
- Dbview models - Dynamic SQL models that use macros
- Federate models - Dynamic models that use macros