Skip to content

Components and presets

Components are plain Python functions in components/ that return expressions or queries. They need no registration.

components/staging.py
def clean_status(orders):
return (
orders.trim_spaces("status")
.lowercase_text("status")
.replace_empty_strings_with_null("status")
.named("normalized_status")
)
models/staging/stg_orders.py
from selectjoin import model, source
from components.staging import clean_status
@model(grain="order_id")
def build():
return clean_status(source("orders")).keep_first_row_per_key(
by="order_id", order_by=["updated_at DESC"]
)
  • from components... import ... resolves inside the current project at any folder depth. Relative imports also work.
  • Each project’s components are isolated from other projects and reload on every project load.
  • Components can take parameters, use loops and conditions, and call each other. Use them directly or with query.apply(component, **parameters).
  • Don’t import model files — reference models by name with ref().

Presets transform the previous result in call order. Each name describes exactly one effect, so reviewers can see every data change. They are available as methods on source(), ref(), and table() references, or as functions in selectjoin.presets.

from selectjoin import relation
orders = relation("raw.orders", schema={
"order_id": "BIGINT", "status": "VARCHAR", "amount": "DECIMAL(18, 2)",
"updated_at": "TIMESTAMP",
})
cleaned = (
orders.trim_spaces("status")
.lowercase_text("status")
.replace_empty_strings_with_null("status")
.replace_nulls({"status": "unknown", "amount": 0})
.keep_first_row_per_key(by="order_id", order_by=["updated_at DESC", "amount DESC"])
)
print(cleaned.sql(dialect="postgres"))

relation() declares an input for scripts; it never reads data. See the preset reference for exact semantics.

.named("stage_name") keeps a meaningful intermediate result as a readable CTE in the compiled SQL. Collisions in a compiled graph get deterministic suffixes.

metrics = orders.select(
status=lambda row: row.c.status.trim_spaces().lowercase_text().replace_nulls("unknown"),
amount_per_unit=lambda row: row.c.amount.safe_divide(2),
)

safe_divide casts the numerator to floating point and returns NULL for a zero or NULL denominator.

selectjoin.components.latest_per_key(query, by=[...], order_by=[...]) keeps the latest row per key from a projected query or named CTE. Ordering is required — choose tie breakers that make the winner deterministic.