Skip to main content

uqa_sql/plan/scalar/owned/
windows.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Window specification replacement preserves argument/filter owners and retires only the superseded specification allocations.
8
9use super::{OwnedScalarExpr, Result, ScalarExpr, ScalarMemory};
10use crate::{
11    plan::scalar::resources::{Control, Lowering},
12    ScalarFrameBound, ScalarOrder, ScalarWindowFrame, ScalarWindowSpec,
13};
14use uqa_core::memory::{BudgetedVec, Produced, ProductionControl};
15
16pub(in crate::plan) struct OwnedWindowSpec {
17    value: ScalarWindowSpec,
18    memory: Option<ScalarMemory>,
19}
20impl OwnedWindowSpec {
21    pub(in crate::plan) fn copy_parts(
22        definition: Option<usize>,
23        partition: &[ScalarExpr],
24        order: &[ScalarOrder],
25        frame: Option<&ScalarWindowFrame>,
26        control: &ProductionControl<'_>,
27    ) -> Result<Self> {
28        control.check()?;
29        let mut lowering = Lowering {
30            control: control.budget().map(|_| Control::from_production(*control)),
31            owned_children: control.budget().map(BudgetedVec::new),
32        };
33        let value = ScalarWindowSpec {
34            definition,
35            partition_by: lowering.map(partition.iter(), |lowering, expression| {
36                OwnedScalarExpr::attach_child(lowering, expression.copy_for_rewrite(control)?)
37            })?,
38            order_by: lowering.map(order.iter(), |lowering, order| {
39                Ok(ScalarOrder {
40                    expr: OwnedScalarExpr::attach_child(
41                        lowering,
42                        order.expr.copy_for_rewrite(control)?,
43                    )?,
44                    descending: order.descending,
45                    nulls: order.nulls,
46                })
47            })?,
48            frame: frame
49                .map(|frame| {
50                    Ok::<_, crate::schema::retention::CatalogRetentionError>(ScalarWindowFrame {
51                        mode: frame.mode,
52                        start: bound(&mut lowering, &frame.start, control)?,
53                        end: bound(&mut lowering, &frame.end, control)?,
54                        between: frame.between,
55                        exclusion: frame.exclusion,
56                    })
57                })
58                .transpose()?,
59        };
60        let memory = lowering.control.map(|control| {
61            ScalarMemory::from_parts(
62                control.memory,
63                lowering.owned_children.expect("controlled window children"),
64            )
65        });
66        let output = Self { value, memory };
67        control.check()?;
68        Ok(output)
69    }
70    pub(in crate::plan) fn finish(
71        self,
72        control: &ProductionControl<'_>,
73    ) -> Result<Produced<ScalarWindowSpec>> {
74        Ok(control.finish(self.value, self.memory.map(ScalarMemory::into_reservation))?)
75    }
76}
77fn bound(
78    lowering: &mut Lowering<'_>,
79    value: &ScalarFrameBound,
80    control: &ProductionControl<'_>,
81) -> Result<ScalarFrameBound> {
82    Ok(match value {
83        ScalarFrameBound::UnboundedPreceding => ScalarFrameBound::UnboundedPreceding,
84        ScalarFrameBound::UnboundedFollowing => ScalarFrameBound::UnboundedFollowing,
85        ScalarFrameBound::CurrentRow => ScalarFrameBound::CurrentRow,
86        ScalarFrameBound::Preceding(expression) => {
87            ScalarFrameBound::Preceding(lowering.boxed(|lowering| {
88                OwnedScalarExpr::attach_child(lowering, expression.copy_for_rewrite(control)?)
89            })?)
90        }
91        ScalarFrameBound::Following(expression) => {
92            ScalarFrameBound::Following(lowering.boxed(|lowering| {
93                OwnedScalarExpr::attach_child(lowering, expression.copy_for_rewrite(control)?)
94            })?)
95        }
96    })
97}
98fn frame_children(spec: &ScalarWindowSpec) -> usize {
99    spec.frame
100        .iter()
101        .flat_map(|frame| [&frame.start, &frame.end])
102        .filter(|bound| {
103            matches!(
104                bound,
105                ScalarFrameBound::Preceding(_) | ScalarFrameBound::Following(_)
106            )
107        })
108        .count()
109}
110
111impl OwnedScalarExpr {
112    pub fn replace_window_spec(
113        mut self,
114        specification: &ScalarWindowSpec,
115        control: &ProductionControl<'_>,
116    ) -> Result<Self> {
117        self.assert_owner(control);
118        control.check()?;
119        let replacement = OwnedWindowSpec::copy_parts(
120            specification.definition,
121            &specification.partition_by,
122            &specification.order_by,
123            specification.frame.as_ref(),
124            control,
125        )?;
126        let ScalarExpr::WindowCall { args, spec, .. } = &self.expression else {
127            panic!("window specification replacement requires a window call")
128        };
129        let arguments = args.len();
130        let old_count = spec.partition_by.len() + spec.order_by.len() + frame_children(spec);
131        let old_bytes = spec.partition_by.capacity() * size_of::<ScalarExpr>()
132            + spec.order_by.capacity() * size_of::<ScalarOrder>()
133            + frame_children(spec) * size_of::<ScalarExpr>();
134        let new_count = replacement.value.partition_by.len()
135            + replacement.value.order_by.len()
136            + frame_children(&replacement.value);
137        if let Some(memory) = &mut self.memory {
138            memory.reserve_children(new_count.saturating_sub(old_count))?;
139        }
140        let ScalarExpr::WindowCall { spec, .. } = &mut self.expression else {
141            unreachable!()
142        };
143        let old = std::mem::replace(spec, replacement.value);
144        drop(old);
145        self.remove_child_owners(arguments..arguments + old_count);
146        if let Some(parent) = &mut self.memory {
147            drop(parent.direct.split(old_bytes));
148            let (direct, children) = replacement
149                .memory
150                .expect("controlled specification")
151                .into_parts();
152            let (children, children_memory) = children.into_parts();
153            for child in children {
154                parent
155                    .push_child(child)
156                    .expect("window child slots admitted before replacement");
157            }
158            drop(children_memory);
159            parent.children[arguments..].rotate_right(new_count);
160            parent.direct.absorb(direct);
161        }
162        control.check()?;
163        Ok(self)
164    }
165}