SQL models, written in Python.
Hand-written SQL does not scale. Write warehouse models as Python functions, reuse components, and compile the whole graph into clean, reviewable SQL.
pip install "git+https://github.com/YuriyTrofymenko/selectjoin.git"Open source, MIT licensed. Installs from source while the PyPI release is prepared.
from selectjoin import model, select, source
@model(grain="order_id")
def build():
orders = source("orders")
return (
select(
orders.order_id,
orders.customer_id,
(orders.amount - orders.discount).as_("net_amount"),
)
.from_(orders)
.where(orders.status == "completed")
)WITH "orders" AS (
SELECT "order_id", "customer_id", "status", "amount", "discount"
FROM raw.orders
)
SELECT
"orders"."order_id",
"orders"."customer_id",
"orders"."amount" - "orders"."discount" AS "net_amount"
FROM "orders"
WHERE "orders"."status" = 'completed';- Python
- DuckDB
- PostgreSQL
- dbt
- Looker
- Airflow
- Metabase soon
SQL is where CSS was before preprocessors.
Hand-written CSS stopped scaling years ago. The web moved to variables, mixins, and components, and kept CSS as the output. Warehouse SQL is still typed by hand: the same logic copied from file to file, a little different each time. SelectJoin makes SQL the output too.
By hand One rule, typed three times
SELECT order_id, NULLIF(LOWER(TRIM(status)), '') AS statusFROM raw.orders
SELECT refund_id, NULLIF(LOWER(TRIM(status)), '') AS statusFROM raw.refunds
SELECT return_id, LOWER(status) AS statusFROM raw.returns
With SelectJoin Written once, imported three times
def clean_status(rows): return ( rows.trim_spaces("status") .lowercase_text("status") .replace_empty_strings_with_null("status") )
clean_status( source("orders"))
clean_status( source("refunds"))
clean_status( source("returns"))
What you ship is still plain, readable SQL. You just stop typing it.
Five problems every SQL codebase has.
Pick one to see how SelectJoin handles it.
The same cleaning logic in ten models
Write it once as a Python function and import it. Presets name every data change, so a reviewer sees exactly what happens to each column.
# 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 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"]
)One rule for every table in a layer
A policy is a loop. Select models by layer or metadata and generate a check, or a whole model, for each one.
from datetime import timedelta
from selectjoin import freshness
def build(project):
for model in project.models(layer="staging"):
yield freshness(model, column="updated_at", max_age=timedelta(hours=24))A change that breaks something downstream
Compare the project with main before you merge. Every removed column, changed type, and changed grain is listed, on each model it reaches.
Late data and incremental loads
Declare the merge key and a date window with overlap. SelectJoin generates the MERGE, or a full rebuild when you ask for one.
@model(
grain=("event_id", "occurred_at"),
relation="analytics.events",
materialization=Incremental(
strategy="merge",
key=("event_id", "occurred_at"),
partition_by="occurred_at",
window="daily",
),
)
def build(run: Context):
events = source("events")
batch = select(events.event_id, events.occurred_at, events.amount).from_(events)
if run.is_incremental:
batch = batch.where(run.window("daily").predicate(events.occurred_at))
...Where does this number come from?
Column lineage follows a value through every model back to the raw table, in the terminal or in the local explorer.
$ selectjoin lineage mart_customer_revenue --column net_revenue # excerpt of the JSON output "column_edges": [ { "from_model": "int_orders_customers", "from_column": "net_amount", "to_model": "int_order_customer_features", "to_column": "net_amount" }, { "from_model": "int_order_customer_features", "from_column": "net_amount", "to_model": "mart_customer_revenue", "to_column": "net_revenue" } ]
Built for the agents that write your SQL.
Ask an agent for SQL and it writes it from scratch, a little differently each time. In a SelectJoin project it builds from the same components your team uses, checks its own work, and tells you what it changed.
- ConsistentIt imports your components instead of writing the logic again, so the tenth model cleans a column exactly like the first.
- Self-checkingOne command validates the whole project offline and answers in JSON: a pass, or the file and a suggested fix.
- Honest about impactBefore anything merges, it can list every column it removed and every type it changed.
$ selectjoin check --json { "ok": false, "error": { "message": "… Unknown column: statuss Did you mean 'status'?", "file": "models/marts/mart_completed_orders.py", "line": 13, "suggestion": "status" } } # the agent applies the suggestion, then checks again $ selectjoin check --json { "ok": true, "dialect": "duckdb", "units": 2, "checks": 0 }
Browse a real project. Read every line it compiles to.
The layered example that ships with the package: 11 sources and models, from raw tables to a customer revenue mart. Open any node to see its Python next to its SQL.
The explorer itself, shown live: each model's Python beside the SQL it compiles to.
Open the explorer →Python in. The files your stack already reads, out.
SelectJoin checks your project offline, then writes it in the form each tool expects. Pick an output to see the same model in that form.
sources/tables and column types models/queries, one per file components/shared Python functions checks.pydata quality rules dbt manifestoptional: build on dbt modelsSELECT
"int_order_customer_features"."customer_id",
"int_order_customer_features"."customer_name",
COUNT(*) AS "order_count",
SUM("int_order_customer_features"."net_amount") AS "net_revenue",
SUM("int_order_customer_features"."loyalty_adjusted_amount") AS "loyalty_adjusted_revenue"
FROM "int_order_customer_features"
WHERE
"int_order_customer_features"."is_completed"
GROUP BY
"int_order_customer_features"."customer_id",
"int_order_customer_features"."customer_name";{{ config(materialized='view') }}
SELECT
"int_order_customer_features"."customer_id",
"int_order_customer_features"."customer_name",
COUNT(*) AS "order_count",
SUM("int_order_customer_features"."net_amount") AS "net_revenue",
SUM("int_order_customer_features"."loyalty_adjusted_amount") AS "loyalty_adjusted_revenue"
FROM {{ ref('int_order_customer_features') }} AS "int_order_customer_features"
WHERE
"int_order_customer_features"."is_completed"
GROUP BY
"int_order_customer_features"."customer_id",
"int_order_customer_features"."customer_name"view: mart_customer_revenue {
sql_table_name: analytics.mart_customer_revenue ;;
dimension: customer_id {
primary_key: yes
type: number
sql: ${TABLE}.customer_id ;;
}
dimension: net_revenue {
type: number
sql: ${TABLE}.net_revenue ;;
description: "Revenue after order discounts."
}
measure: count {
type: count
}
}-- Generated by SelectJoin from models/marts/mart_customer_revenue.py.
CREATE OR REPLACE VIEW analytics.mart_customer_revenue AS
SELECT
"int_order_customer_features"."customer_id",
"int_order_customer_features"."customer_name",
COUNT(*) AS "order_count",
SUM("int_order_customer_features"."net_amount") AS "net_revenue",
SUM("int_order_customer_features"."loyalty_adjusted_amount") AS "loyalty_adjusted_revenue"
FROM analytics.int_order_customer_features AS "int_order_customer_features"
WHERE
"int_order_customer_features"."is_completed"
GROUP BY
"int_order_customer_features"."customer_id",
"int_order_customer_features"."customer_name";How SelectJoin works →Project structure →Choose where to start →Metabase is planned.
From nothing to compiled SQL in four steps.
- 01
Install
A Python package with a command-line tool.
$ pip install "git+https://github.com/YuriyTrofymenko/selectjoin.git" - 02
Create a project
A folder with one source and one staging model, ready to compile.
$ selectjoin init my_projectCreated project: my_project
- 03
Add a model
Scaffolded in the right layer, ready to edit.
$ selectjoin new order_totals --layer marts --from stg_orders --grain order_idCreated mart_order_totals: models/marts/mart_order_totals.py
- 04
Check and compile
Validate everything offline, then read the SQL.
$ selectjoin checkOK: 3 sources/models validated (duckdb).$ selectjoin compile mart_order_totals
What you see in your terminal
Built by developers. Funded by its users.
If SelectJoin saves you time, sponsoring keeps the Python package free, fast, and focused on the people who write the models.