SQL models, written in Python.
Write warehouse models as Python functions, reuse components, and compile the whole graph into plain SQL.
pip install "git+https://github.com/YuriyTrofymenko/selectjoin.git"MIT licensed. Installs from GitHub until the PyPI release.
from selectjoin import model, select, source
@model(grain="order_id")
def build():
orders = source("orders")
return (
select(
orders.order_id,
(orders.amount - orders.discount).as_("net_amount"),
)
.from_(orders)
.where(orders.status == "completed")
)SELECT
"orders"."order_id",
"orders"."amount" - "orders"."discount" AS "net_amount"
FROM "orders"
WHERE
"orders"."status" = 'completed'SQL is where CSS was before preprocessors.
CSS moved to variables, mixins, and components, and stayed the output. Warehouse SQL is still typed by hand, with the same logic copied from file to file. 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 generating SQL changes.
- 01
Consistent SQL
Every query is generated: the same quoting, aliases, and structure in every model.
- 02
Errors before the warehouse
A misspelled column fails an offline check, with the file, the line, and the fix.
- 03
Breaking changes listed
A diff lists every removed column and changed type, on each model downstream.
- 04
Column lineage
Column lineage traces a value through every model, back to the raw table.
- 05
Smaller reviews
A reviewer reads a short Python change and the SQL it produced.
- 06
Rules written once
A check for every model in a layer is one loop.
- 07
Agents reuse your code
Coding agents import your components and check their own work.
- 08
Conventions built in
Layers, name prefixes, and scaffolding put a new model in the right place.
- 09
One place for scripts
Audits, reports, and custom exports live in scripts/ and run with one command.
What you write, and what it writes.
Pick any part to see it.
A project is a folder with this file. Everything in it is checked together, offline.
dialect = "duckdb"
sources = "sources"
models = "models"A source is a raw table and its column types. Models read it by name with source().
@source
def build():
raw = table("raw.orders", schema=ORDER_SCHEMA)
return select(raw.order_id, raw.status).from_(raw)A model is one query in one file: a Python function that returns a select. The folder it sits in is its layer: staging, intermediate, or marts.
sourcestagingintermediatemartsthe same colours as the model graph below
@model(grain="order_id")
def build():
return clean_orders(source("orders"))A component is a plain Python function that returns part of a query, imported wherever it is needed.
def normalize_status(status):
return status.trim().lower()A script is your own code that works with the whole project: data checks, an audit, a report, an export.
# selectjoin run summary --limit 5
def run(project, limit: int = 20):
for model in project.models()[:limit]:
print(model.name, model.grain)Optional. Point at a dbt project and its models become sources you can reference.
[packages.analytics]
type = "dbt"
manifest = "../analytics/target/manifest.json"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 "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";Five common problems.
Pick one to see the code.
The same cleaning logic in ten models
Write it once as a Python function and import it. Presets name each data change.
# 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 and generate a check 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 with main before merging. Removed columns, changed types, and changed grains are listed for each model affected.
Late data and incremental loads
Declare the merge key and a date window. SelectJoin generates the MERGE, or a full rebuild on request.
@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.
$ 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" } ]
See all of it on a real project.
Agents work from your components.
- ConsistentAn agent imports your components instead of writing the logic again.
- Self-checkingOne command validates the project offline and answers in JSON: a pass, or the file and a fix.
- Reports what it changedA diff lists every column removed and every type 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 }
A real project and the SQL it compiles to.
The layered example from the package: 11 sources and models, from raw tables to a customer revenue mart.
The explorer, live: each model's Python beside its SQL.
Open the explorer →Four steps to compiled SQL.
- 01
Install
A Python package with a command-line tool.
$ pip install "git+https://github.com/YuriyTrofymenko/selectjoin.git" - 02
Create a project
One source and one staging model.
$ selectjoin init my_projectCreated project: my_project
- 03
Add a model
Scaffolded in the right layer.
$ 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 offline, then read the SQL.
$ selectjoin checkOK: 3 sources/models validated (duckdb).$ selectjoin compile mart_order_totals
What you see in your terminal
Free to use. A star is all it asks.
Open source, no donations. If it saves you time, star it on GitHub.