-
Notifications
You must be signed in to change notification settings - Fork 323
Description
π Feature Request: Conditional Query Builder Helpers for Optional Filters and Joins
Problem
Building dynamic queries with optional filters, joins, and conditions currently requires repeated if checks scattered throughout the codebase.
This pattern leads to:
- Cluttered, repetitive query-building logic
- Reduced readability and maintainability for complex analytics queries
- Higher risk of wiring incorrect conditions when flags are false
- Widespread edits whenever new optional parameters are introduced
In analytical dashboards and reporting systems, these optional filters are standard practice, and the current approach makes such use cases cumbersome and error-prone.
Proposed Solution
Introduce conditional builder helpers that allow attaching query segments only when a condition evaluates to True, while leaving the original chain untouched otherwise.
Example API
query = (
Query.from_(sales)
.select(sales.id, sales.amount)
.when(include_customer, lambda q: q.join(customers).on(sales.cust_id == customers.id))
.when(apply_date_filter, lambda q: q.where(sales.date >= start_date))
)If include_customer or apply_date_filter are False, the corresponding segments are ignored, and the query structure remains identical to the unmodified chain.
Key Requirements
- Provide one or more idiomatic helpers such as:
.when(condition, fn).when_join(condition, fn).when_filter(condition, fn)
- Guarantee that when a condition evaluates to
False, the query chain remains structurally identical (no side effects or partial joins). - Maintain full compatibility with existing chaining methods.
- Ensure deterministic SQL generation, even when multiple conditions interact.
- Tests must confirm:
- Structural integrity of the unmodified query
- Correct inclusion/exclusion of optional segments
- No interference with aliases, subqueries, or aggregates
Example Usage
Without helper (current):
q = Query.from_(sales).select(sales.id)
if include_customer:
q = q.join(customers).on(sales.cust_id == customers.id)
if apply_date_filter:
q = q.where(sales.date >= start_date)With helper (proposed):
q = (
Query.from_(sales)
.select(sales.id)
.when(include_customer, lambda q: q.join(customers).on(sales.cust_id == customers.id))
.when(apply_date_filter, lambda q: q.where(sales.date >= start_date))
)Benefits
β
Simplifies query-building logic
β
Reduces repetitive conditionals
β
Keeps code readable, modular, and maintainable
β
Minimizes risk of incorrect query assembly
β
Improves testability and reduces surface area for future edits
Summary
Adding a .when()-style conditional helper would make the query builder more expressive, safe, and composable for real-world reporting scenarios.
It enables dynamic, conditional SQL generation without boilerplate, perfectly fitting the fluent chaining style developers already use.