Skip to main content

lower_within

Function lower_within 

Source
fn lower_within(
    ts_type: DataType,
    bound: ExprImpl,
) -> Result<(ExprImpl, ExprImpl)>
Expand description

Lower a WITHIN bound into the two expressions the executor consumes: the span predicate over a synthetic [last_order_key, first_order_key] row, and the per-row deadline over a synthetic [first_order_key] row.

Extracted so their relationship is testable. The executor treats the deadline as interchangeable with the right-hand side of the span predicate — it is what lets a hot-path span check reuse the deadline already cached per row instead of evaluating an expression — and that interchangeability holds only because BOTH are built here from one first + bound, and because the check below forces that sum to keep the order key’s type. The within_predicate_right_hand_side_is_the_deadline test pins the first property; the within_bound_that_promotes_the_order_key_type_is_rejected test pins the second.

Lowering the predicate as (last - first) <= bound looks equivalent and is not, for calendar-varying intervals: timestamp subtraction yields a months-free interval compared under 30-day normalization, while first + INTERVAL '1 month' is calendar addition. For starts in short months the deadline would then close BEFORE the span window, prematurely finalizing and evicting live partials.

The sum can still leave the order key’s range at runtime (a smallint key at 32766 with WITHIN 2::smallint). That is not a bind-time concern: every representable order key lies inside such a span, so the executor reads an out-of-range sum as a window that never closes (Deadline::Never in the stream crate) rather than as a NULL that the span check would reject.