Macros
SQL macro reference
Literal positions, relation slot reads and mappings, call checks and result types for SQL macros.
The rules behind SQL macros: which positions need a literal, how relation slots are read and mapped, what is checked at each call, and the result type of each form.
Positions that need a literal
Section titled “Positions that need a literal”SQL needs a literal in some positions. A parameter without CONST there fails with P023 when the
macro is checked:
error[P023]: places is used where a literal is required; declare it places INT CONST| Position | Adapters |
|---|---|
LIMIT, OFFSET, TOP and FETCH FIRST counts |
all |
INTERVAL and EXTRACT units |
all |
PIVOT ... IN (...) values |
all |
DATE_TRUNC unit (the first argument, or the last on BigQuery) |
all |
ROUND precision |
DuckDB and MotherDuck (for DECIMAL values), Databricks |
The positions every adapter shares are checked for every macro file. DATE_TRUNC and ROUND are
checked for the project’s adapter at each call.
Reading slots
Section titled “Reading slots”The examples use the weekly_rates macro from
Relation slots.
alias.@weekly.order_countreads the slot from a table alias or CTE, such assin that macro. For a group, the prefix applies to every column:s.@weekly.keysbecomess.product_id, s.region.- A plain read of a group,
@weekly.keys, always stands as the bare column names,product_id, region. So later CTEs, such asrated, read the group from whatever relation they select from, without an alias. A bare name that two joined relations share fails as hand-written SQL does, withB003; read it asalias.@weekly.keysthere. - A plain read of a single-column slot always reads through the passed relation, mapped or not:
@weekly.refund_countbecomesweekly.refund_count, orweekly.refunds_nwithweekly.refund_count := refunds_n. So the same body expands the same way for every mapping. - Every read inside
USING (...)stands unqualified, asUSINGneeds, includingUSING (@weekly.week)for a column the type does not declare. - In a column-list macro,
o.@weekly.keysoutputs the group’s columns under their own names. - Rules judge a read as you wrote it.
SQLCLEAN028, which rejects a query mixing qualified and unqualified columns, judges a query the macro writes whole, such as a CTE of a CTE-list macro, once, in the macro file. There every plain read counts as unqualified and everyalias.@weekly...read as qualified. A step written only in plain reads, such asSELECT @weekly.keys, @weekly.refund_count AS refunds FROM @weekly, passes; to qualify, read every slot through an alias. - Where a call’s output joins the caller’s query, as with expression and column-list macros, the
query is judged at the call. A read through the relation the call passes, such as
o.created_atin theaudit_columnsexample in SQL macros, fits either style; any other column counts as the macro writes it, so a barestatusbeside a hand-qualifiedo.order_idfails.
A plain group read inside a subquery, such as EXISTS (SELECT @weekly.keys FROM refunds AS r ...),
could bind its bare columns to the subquery’s relations instead of the one the slot reads. The
call fails with P017 when a relation of an enclosing subquery, other than the relation passed
for the slot, has one of the group’s columns, or when its columns are not known. LATERAL
subqueries in FROM or JOIN are checked the same way:
error[P017]: slot weekly.keys column product_id would bind to refunds in this subquery; write alias.@weekly.keysRead the group through its alias there. A group read in a CTE, or in a derived table in FROM,
reads that query’s own relations and is not checked.
alias.@weekly.name naming no slot, or alias.@weekly naming none at all, fails with P022.
@weekly.name without an alias may still read a column the type does not declare, through the
passed relation, as before.
Mapping slots at the call
Section titled “Mapping slots at the call”A call maps slots with relation.slot := ..., next to its other named arguments:
WITH weekly AS (SELECT * FROM __ref("weekly_orders")),@sql.weekly_rates(weekly, weekly.keys := (product_id), weekly.order_count := orders_placed, __cte := by_product)@sql.weekly_rates(weekly, weekly.keys := (product_id, region), weekly.order_count := orders_placed, __cte := by_product_region)final AS (SELECT * FROM by_product_region)SELECT * FROM finalThe first call compiles to the same SQL as a macro written for product_id, the second groups by
product and region. The left of := is always a parameter path, and the right side is column
names of the passed relation:
- A single-column slot takes one column name. An unmapped single-column slot reads the column of
its own name, so
refund_countabove readsrefund_count. - A group takes a parenthesised list of column names, such as
(product_id, region), and every call must map it. - A slot reads a column as it is: compute an expression in the relation you pass.
- A macro that passes its own relation on maps the inner slots to its slot names, as in
@sql.weekly_rates(weekly := @src, weekly.keys := (dims), weekly.order_count := placed), or to columns of its relation. Each inner slot keeps its kind: a group mapped to columns is still read bare, or after its alias, and mapping a group to a single-column slot of the outer relation, or the reverse, fails withP017.
Rules for groups
Section titled “Rules for groups”- A group is pasted verbatim, comma-separated. It takes no per-item expression, indexing, counting or renaming, and groups are never combined.
- A group stands only as a whole item of a select list,
PARTITION BY,GROUP BY,ORDER BY(withoutASC,DESCorNULLS) orUSING (...). Anywhere else fails withP015at the macro file. - Grouped columns keep their real names in the output.
- A group is never empty:
weekly.keys := ()fails. - A relation may have several groups, such as
keys COLUMNS, carried COLUMNS. Groups of one relation may not share a column, and a column that fills a single-column slot, mapped or by its own name, may not also be in a group.
Slot errors
Section titled “Slot errors”Slot errors fail with P017 and name the slot and the caller’s relation:
error[P017]: slot weekly.order_count needs a BIGINT column; weekly has no column orders_total- Every mapped and grouped column must exist in the passed relation, and a single-column slot needs
a compatible type:
slot weekly.order_count needs a BIGINT column; weekly.region is VARCHAR, orslot weekly.keys groups column channel; weekly has no column channel. Like other argument checks, these run when the relation is a CTE or table alias; the model’s own column checks still run on the expanded SQL. - Overlapping groups, or a grouped column that also fills a single-column slot, fail at the call.
- A grouped column named like a column the macro defines, or like a bare column such as
s.weekor a column read through the relation such as@weekly.regionbeside the group in the same select list, fails withP018, naming both:column refunds of slot weekly.keys clashes with column refunds that macro weekly_rates() defines. - A mapped single-column slot read in a select list needs an
ASin the macro, so output names don’t depend on the caller’s mapping. Groups are exempt, because they keep their real names, and so is an unmapped slot, which keeps its own name. So are reads inIN,EXISTSand scalar subqueries, whose column names never reach the macro’s output. ALATERALsubquery inFROMorJOINis checked like a derived table, because its columns reach the output, as throughl.*.
Checks on every call
Section titled “Checks on every call”Each macro is checked on its own when the project compiles, and each call is checked against the caller’s column types, inferred like the rest of the model:
- a
RELATIONargument must have every declared column, each of a compatible type, and every column its slots are mapped to; - a typed argument must have a compatible type, so
@sql.cents_to_dollars(o.status)with aVARCHARstatus fails.
These fail with P017, naming the argument, the expected type or column and what the caller has:
error[P017]: argument src of macro clean_orders() needs column is_deleted BOOLEAN; orders_raw has no column is_deleted --> models/marts/orders_clean.sql:2:1 parameter declared here: --> macros/sql/clean_orders.sql:3:14 = help: pass a relation with these columns: order_id BIGINT, updated_at TIMESTAMP, is_deleted BOOLEANAn argument whose type the compiler cannot infer passes. So do calls inside a subquery or in a
query part with UNION, INTERSECT or EXCEPT, arguments built from __ref(), macro calls or
parameters of a calling macro, and calls in models with runtime placeholders; the model’s own
column checks still run on the expanded SQL. All other errors also point at the call and at the
macro file.
Result types
Section titled “Result types”An expression macro call is typed wherever it stands, from its expanded SQL, as if the SQL were
written there. returns declares the type for when that SQL’s type is unknown:
MACRO (description "Status bar", arguments (value VARCHAR), returns VARCHAR);
bar(LENGTH(@value), 0, 10)- The declared type applies only where the expanded SQL’s type is unknown, including a list
literal such as
[], whose type analysis doesn’t infer. A known type stands, even a close one such asVARCHAR(100)forreturns VARCHAR(5), and contract checks report a mismatch withK002. - The type flows on as an inferred type would: through CTEs,
SELECT *, subqueries, joins and each branch of a set operation, through operators and functions around the call, to contract checks (K002,K003),SQBRCONTRACT105and models that read the column. returnsis used only for analysis. It doesn’t appear in the generated SQL, so on its own it doesn’t change the column’s physical type. A body of'ACTIVE'still createsVARCHAR(6)on Snowflake. ForSQBRCONTRACT105, a select-list item that is one call needs noCASTat the call only when the macro body’s outermost expression is aCAST(... AS type)or...::typeto the column’s contract type, compared as the dialect does, such asCAST(LEFT(@value, 3) AS VARCHAR)for aVARCHARcolumn. Otherwise the rule asks for a cast in the macro or at the call, whether the macro declares a fixedreturnsorreturns TYPE OF. A call inside a larger expression always needs an outer cast.- Without
returns, the call is typed by inference alone. When an output is one call whose type is unknown,K003andSQBRCONTRACT105suggest declaringreturnson the macro. returns TYPE OF <argument>declares the type of that argument at each call, under the same rule:arguments (value ANY NUMERIC, places INT CONST DEFAULT 2), returns TYPE OF value. If the argument’s own type is unknown, so is the call’s. The argument must be a scalar argument of the macro (P015).- A fixed
returnsis checked against the body at the macro file. The body is typed from the declared argument types; a known type of another family, such asUPPER(@value)withreturns BIGINT, fails withP024. A body whose type cannot be inferred, for example because it readsANYarguments, is a list literal, or calls a function whose type is unknown or only guessed, trustsreturns. returnsand every argument type must be a type the adapter’s SQL dialect accepts, including a decimal precision and scale it can hold, such as at mostDECIMAL(38, s)on DuckDB (P015).- A call where only a keyword can stand, such as the date part of
EXTRACT, is typed by inference alone. - A call inside a Python macro argument, as in
@py.bracket(@sql.status_bar(o.status)), is typed by inference alone. returnsnever changes the compiled SQL.
A * REPLACE item takes its source column’s type rather than the call’s.