Skip to main content
Macros are Python functions that generate SQL during compilation. They provide reusable, parameterized SQL without introducing a separate template language.

Create a macro

Put project-wide macros in Python files under the top-level macros/ directory:
Every public function defined by a macro file becomes callable from SQL:

Call a macro from SQL

Use @macro_name(...) in a model query:
During compilation, SQLBuild replaces the call with the function’s returned SQL:
A macro used directly in SQL must return a string.

Arguments

Macro calls accept Python literal values:
  • Strings: "value" or 'value'
  • Numbers: 42, 3.14, -1
  • Booleans: True, False
  • Lists: [1, 2, 3]
  • Dictionaries: {"key": "value"}
  • None
  • The result of another macro call
Positional and keyword arguments are supported:
Use quoted strings when passing SQL expressions such as column names. The macro decides how to place that text into its returned SQL.

Keep implementation details private

Only public functions owned by the file are exported as macros. Prefix helpers, constants, classes, and type aliases with _:
Here, SQL may call @completed_orders(). _status_filter and _DEFAULT_STATUS remain ordinary Python implementation details. Imported functions are not re-exported as new macros from the importing file.

Use macros in tests

Tests are SQL, so they can use macros as reusable fixture generators:

Use macros in hooks

Macros work inside inline and named SQL hooks:
See SQL Hooks for hook lifecycle and context syntax.

Where macros work

Macros are supported in:
  • Model query SQL
  • Inline and named SQL hooks
  • Unit tests and scenarios
  • Standalone audit SQL
  • SQL functions and supported inline source expressions
Macros are not accepted in ordinary MODEL() configuration fields. SQL hook entries are the exception because their contents are SQL.

Next steps

Composition and Context

Compose macros through Python imports and use adapter or target context.

Declarations and Scopes

Limit a macro to one folder, or to that folder and its child folders.