To answer the "kwargs" part of your question (but for a different example), I'll modify an answer that I posted to a related question on args and kwargs in Jinja
The kwargs
object will be a dictionary so if you want to use it you can iterate over it by accessing the items()
method, like you can in Python. I have this in a generic import
macro to streamline the top-level "import" CTEs:
{% macro import() %}
{%- for key, value in kwargs.items() %}
{{ key }} AS (
SELECT *
FROM {{ value }}
){%- if not loop.last -%},{%- endif -%}
{% endfor %}
{% endmacro %}
This can be used in the following way:
WITH
{{ import(
payments=source("stripe", "payments"),
customers=ref("stg_jaffle_shop__customers"),
orders=ref("fct_orders"),
bad_cte="jaffle_shop.pasties"
) }}
SELECT ...
This will compile into something like the following (depends on the model configs):
WITH
payments AS (
SELECT *
FROM stripe.payments
),
customers AS (
SELECT *
FROM jaffle_shop.customers
),
orders AS (
SELECT *
FROM jaffle_shop.orders
),
bad_cte AS (
SELECT *
FROM jaffle_shop.pasties
)
SELECT ...
Note that the bad_cte
argument is there to prove that this macro can take literal references in addition to source and model references, but that's generally a bad idea since a literal reference won't show up in dynamic content like the lineage diagram
Additionally, the advantage of setting up the imports is that it can be augmented to do things like use the INFORMATION_SCHEMA
(or equivalent) to expand the *
so that compiled scripts list all of their columns, which is useful for debugging and column lineage