Skip to main content

Write a pipeline

Build derived tables from tables you already have in Bauplan, with SQL and Python models in a project. Use this page when the project exists and you want to add models to it; to create one, see how to set up a project. The concepts behind this page are in semantic layer and pipelines and expectations.

If your logic starts in a notebook, see the from-notebooks-to-prod example, which runs notebook functions as models.

Run everything on a branch whose name starts with your username; see how to name branches.

Write a model

A model can be SQL or Python.

If the model is SQL

Create a .sql file containing a query. The file name is the model name, and comment headers set its options. Every SQL model declares an output schema, defined as a class in a top-level Python file of the project. Replace the table and columns with your own:

# schemas.py
import bauplan

class CleanOrders(bauplan.TableSchema):
"""Valid orders."""

order_id: bauplan.Int64
customer_id: bauplan.Int64
amount: bauplan.Float64
order_date: bauplan.Date32
-- clean_orders.sql
-- bauplan: materialization_strategy = NONE
-- bauplan: output_schema = CleanOrders
SELECT
order_id,
customer_id,
CAST(amount AS DOUBLE) AS amount,
CAST(created_at AS DATE) AS order_date
FROM raw.orders
WHERE amount > 0

SQL models run on DataFusion and follow the DataFusion SQL dialect. The NONE materialization strategy computes the output and passes it to the models that read it, without writing to object storage; see pick a strategy for each model. To use run parameters such as $start_date in the query, see how to use them in filters and as arguments.

In the query, select only the columns and rows the model needs; see how to speed up reads.

Read only catalog tables in a SQL model. A SQL model's query can join tables, use subqueries and use CTEs across tables that already exist on the branch, but it can't read the output of another model in the same run. If a step needs another model's output, write that step as a Python model that reads the other model with bauplan.Model("<model name>").

SQL files in subfolders are sent only if the project file includes them explicitly; see how to organize SQL files. SQL can also run in ad hoc queries outside any pipeline; see how to query tables.

If the model is Python

A Python model is a function with an output schema, two decorators, typed inputs and a body that returns an Arrow table.

Define the output schema

Define the columns the model returns as a schema class:

# models.py
from typing import Annotated

import bauplan
import pyarrow as pa

class CustomerRevenue(bauplan.TableSchema):
"""Revenue per customer and day."""

customer_id: bauplan.Int64
order_date: bauplan.Date32
revenue: bauplan.Float64
orders: bauplan.Int64

Add the decorators

@bauplan.model(
name="analytics.customer_revenue",
materialization_strategy="REPLACE",
partitioned_by=["day(order_date)"],
)
@bauplan.python("3.13", pip={"polars": "1.40.0"})

@bauplan.model sets the table the model writes and how it's written; see pick a strategy for each model.

If the model writes a large table, set partitioned_by. Every write reconciles the table's partitioning with the one the model declares. How to choose the partition column is in choose the partition column, and the header a SQL model uses in set partitioned_by on the model. To reprocess a window of a partitioned table without rewriting the rest, use OVERWRITE_PARTITIONS and filter on declared partition columns only; see overwrite a window of partitions, and stage the new files and overwrite the window in the API ingestion guide for an example.

In @bauplan.python, declare the Python version and every package the function imports, with an exact version. Bauplan builds a separate environment for each model. Models in one pipeline can use different Python and package versions; see execution model.

Declare the inputs and the output

def customer_revenue(
# A model of the project, or a table in the catalog
orders: Annotated[pa.Table, bauplan.Model("clean_orders")],
) -> Annotated[pa.Table, CustomerRevenue]:
"""Aggregate valid orders per customer and day."""

bauplan.Model("<name>") works for both kinds of input. If a model in the project is called <name>, Bauplan runs it first and passes its output to this model. Otherwise, it reads the table called <name> from the branch. The return annotation names the output schema.

Declare what each input reads from a table that already exists on the branch. A projection schema selects columns and checks their types; a filter selects rows. Both are pushed down to the table scan, so the model loads less data. For example, this model reads two columns and only the large orders:

class OrderColumns(bauplan.TableSchema):
"""Columns of raw.orders used by this model."""

order_id: bauplan.Int64
amount: bauplan.Float64

@bauplan.model()
@bauplan.python("3.13")
def large_orders(
orders: Annotated[
pa.Table,
bauplan.Model("raw.orders", projection_schema=OrderColumns, filter="amount > 1000"),
],
) -> Annotated[pa.Table, OrderColumns]:
return orders

Filter only tables that already exist on the branch. The planner rejects a filter on the output of another model in the same pipeline. Filter inside the function instead. For example, if clean_orders is a model in the same project, this input is rejected:

bauplan.Model("clean_orders", filter="order_date <= '2026-09-30'")

How to write filters the scan can use is in how to speed up reads.

Write the function body

import polars as pl

return (
pl.DataFrame(orders)
.group_by("customer_id", "order_date")
.agg(pl.col("amount").sum().alias("revenue"), pl.len().cast(pl.Int64).alias("orders"))
.to_arrow()
)

Import the packages inside the function body. Each model runs in its own container with only the packages declared in the decorator. An import at the top of the file fails.

Return a PyArrow table, converting from Polars or pandas first. Cast types that Iceberg can't store, such as the unsigned integers some libraries return for counts, like pl.len() above, or the output doesn't match its schema.

Run SQL inside the model

To run a query in the middle of a Python model's logic, use an embedded engine such as DuckDB, declared as a dependency. This is also how to write a step in SQL when it reads another model's output:

class CustomerOrders(bauplan.TableSchema):
"""Order count per customer."""

customer_id: bauplan.Int64
orders: bauplan.Int64

@bauplan.model()
@bauplan.python("3.13", pip={"duckdb": "2.0.0"})
def customer_orders(
orders: Annotated[pa.Table, bauplan.Model("clean_orders")],
) -> Annotated[pa.Table, CustomerOrders]:
"""Count the orders of each customer."""
import duckdb

# DuckDB reads the Arrow table through the name of its variable
return duckdb.sql(
"SELECT customer_id, COUNT(*) AS orders FROM orders GROUP BY customer_id"
).to_arrow_table()

Either way, the output is an Arrow table. The models that read it don't need to know which language produced it.

Document the schemas

The docstring of each schema and the doc of each field become the documentation of the table; see schemas. Write them for the person or agent who reads the table later. The steps below document the two schemas of one model.

Document the input schema

  • In a schema's docstring, say whether it's a projection schema or an output schema, and which models use it.
  • In a column's doc, say what to expect from its values, such as a range, a filter already applied or a number that stands for a category, and whether the column is used in a join or an aggregation.
class SelectedInputColumns(bauplan.TableSchema):
"""
Projection schema applied to `input_table` containing three columns.

+ ----------- + SelectedInputColumns + -------- +
| input_table | ----------------------> | my_model |
+ ----------- + (projection) + -------- +
"""

col_1: Annotated[bauplan.String, bauplan.TableField(
doc='aggregation key in `my_model`'
)]

Document the output schema and its lineage

Set lineage on an output field that comes from an input field, as col_1 does here. Its doc follows the same advice as the input schema's.

class CountByColOne(bauplan.TableSchema):
"""
Output schema for `my_model` containing two columns.
Row counts grouped by `col_1`.
"""

col_1: Annotated[bauplan.String, bauplan.TableField(
doc='aggregation column for `my_model`',
lineage=SelectedInputColumns["col_1"],
)]
count: Annotated[bauplan.Int64, bauplan.TableField(
doc='row count for each unique value in `col_1`'
)]

Iterate on the pipeline

While developing, run without writing anything and print the first rows of each model. --preview also takes tail, and -p <project_dir> points at a project in another directory:

bauplan run --dry-run --preview head

A dry run plans and executes every model and expectation but materializes nothing. You can run it as often as you like on any branch. print output from Python models streams back to your terminal. When the output looks right, run for real on your branch and inspect the resulting table:

bauplan run
bauplan table get <namespace>.<table>

bauplan table get shows the columns, their types and nullability, and the documentation written from your schemas. To publish the table, merge the branch; see the orchestrator integrations for running pipelines on a schedule.