Defining macros
Create Python files undermacros/ in your project. Every public function in a macro file becomes a callable macro:
Using macros in models
Call macros in model SQL using the@macro_name(args) syntax:
@cents_to_dollars('SUM(p.amount_cents)') expands to ROUND(CAST(SUM(p.amount_cents) AS DOUBLE) / 100, 2).
Using macros in tests
Because unit tests are written in SQL, they support macro calls. This is useful for reusable mock data generators:Using macros in hooks
Macros are expanded insidesql(...) hook entries in pre_hooks and post_hooks:
@@CTX: context variables, @@name project variables, and @@ENV:NAME environment variables directly without needing a macro wrapper.
For hooks that need more than string interpolation, use python(...) hooks instead. See Hooks for the full Python hook API.
Macro context
When a macro function accepts actx parameter as its first argument, SQLBuild passes a MacroContext object with adapter and target information:
| Field | Description |
|---|---|
adapter_name | The active adapter (e.g. duckdb, snowflake) |
sql_analysis_enabled | Whether SQL analysis is enabled |
target_name | The active target name, if any |
vars | Effective project variables as a dict (merged from project config, target, local config, and CLI --vars) |
Macro arguments
Macro arguments use Python literal syntax. Supported types:- Strings:
'value'or"value" - Numbers:
42,3.14,-1 - Booleans:
True,False - Lists:
[1, 2, 3] - Dicts:
{'key': 'value'} - None:
None - Nested macro calls:
@other_macro('arg')
Nested macro calls in arguments
Macros can be passed as arguments to other macros. The inner macro evaluates first and its result becomes an argument to the outer macro:Composing macros
Macro output cannot contain macro calls. Expansion is single-pass: if a macro returns SQL containing@another_macro(), SQLBuild raises an error. If you need composition, compose in Python:
Where macros are allowed
- Model query SQL - the SELECT statement after the MODEL() header
- Hook strings -
sql(...)entries inpre_hooksandpost_hooksin MODEL() config - Test SQL - unit test CTE bodies
- Audit SQL - singular audit queries
@macro(), SQLBuild raises a compile error.
Discovery rules
- SQLBuild discovers all
.pyfiles undermacros/recursively - Every public function (not starting with
_) becomes a macro - Macro names must be unique across all macro files - duplicates raise a compile error
- Macros are loaded once at compile time, not per-model

