Programmatic, injection-safe builder for DataFusion SQL.
Actively maintained. Last release 6 weeks ago. A safe choice.
pip install datafusion-query-builderdatafusion-query-builder
A programmatic, injection-safe builder for DataFusion SQL — a typed Rust core with a pyo3-exposed Python API. It replaces hand-rolled f-string / template-literal SQL with a typed, composable surface, while still emitting SQL text (so the SQL stays visible in logs/traces, greppable, and cache-keyable).
Values are escaped by construction, so untrusted input (column values, user filters) is safe to
embed. Strings, arrays, and numbers are quoted/encoded for you; an explicit raw(...) escape hatch
is the only unescaped path.
Install
pip install datafusion-query-builder
Prebuilt abi3 wheels are published for CPython 3.9+ on macOS (Apple Silicon + Intel) and Linux
(x86_64 + aarch64).
Quick start (Python)
from datafusion_query_builder import col, lit, param, raw, when, and_, table
from datafusion_query_builder import functions as f
q = (
table("records")
.filter((col("kind") == "span") & col("deployment_environment").is_in(["prod", "staging"]))
.select(
f.coalesce(col("service_name"), "(unknown)").alias("service"),
f.approx_distinct(col("trace_id")).alias("request_count"),
f.approx_percentile_cont(col("duration"), 0.95).alias("p95"),
)
.group_by(col("service_name"))
.order_by(col("request_count").desc())
.limit(200)
)
print(q.to_sql())
Bare Python scalars auto-promote to literals (so col("x") == "prod" works), and string/array
literals are escaped — values are injection-safe by construction. Reach for raw(...) (a SQL
fragment), f.call("name", ...) (any function), or param("name") (a ${name} placeholder) when
you step outside the v1 grammar.
A raw(...) fragment must be one complete SQL expression. The builder parses it on its own, drops
any comments, and adds brackets where its top-level operator binds looser than the surrounding
one, as it does for native expressions. Pass a user-written predicate as raw(predicate), not
raw(f"({predicate})"). Text wrapping breaks on a trailing -- comment, and a predicate such as
1=1) OR (1=1 can close the bracket.
The JSONB key-exists operators are first-class: col("attributes").has_key("gen_ai.input.messages")
renders attributes ? 'gen_ai.input.messages' — a cheap presence check that never extracts the
value (contrast raw("attributes ->> 'k'").is_not_null(), which reads the whole value out just to
test it). and render / .