Skip to main content

uqa_sql/plan/mutable/
windows.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Canonical window refresh follows the existing query-local traversal while every replacement retains its constructor owner.
8
9use super::{
10    CommandQuerySlot, MutableCommandPlan, MutableExecutablePlan, MutableQueryPlan,
11    MutableSourcePlan, OwnedScalarExpr, QueryChildSlot, QueryScalarSlot, SourceChildSlot,
12    SourceScalarSlot,
13};
14use crate::{
15    plan::{CommandPlan, RelationalPlan, SourcePlan},
16    SQLError, ScalarExpr, ScalarWindowSpec,
17};
18use uqa_core::memory::ProductionControl;
19
20mod roots;
21
22impl MutableExecutablePlan {
23    pub fn normalize_window_definitions(
24        self,
25        control: &ProductionControl<'_>,
26    ) -> Result<Self, SQLError> {
27        Ok(match self {
28            Self::Query(query) => Self::Query(query.normalize_window_definitions(control)?),
29            Self::Command(command) => Self::Command(command.normalize_window_definitions(control)?),
30        })
31    }
32}
33impl MutableQueryPlan {
34    pub fn normalize_window_definitions(
35        mut self,
36        control: &ProductionControl<'_>,
37    ) -> Result<Self, SQLError> {
38        self.assert_owner(control);
39        control.check()?;
40        for index in 0..self.ctes.len() {
41            self = self.map_cte(index, control, |plan| {
42                plan.normalize_window_definitions(control)
43            })?;
44        }
45        let subqueries = match &self.root {
46            RelationalPlan::QueryBlock(block) => block.subqueries.len(),
47            RelationalPlan::SetOp { subqueries, .. }
48            | RelationalPlan::Values { subqueries, .. } => subqueries.len(),
49        };
50        match &self.root {
51            RelationalPlan::QueryBlock(_) => {
52                self = self.map_source(control, |source| normalize_source(source, control))?;
53            }
54            RelationalPlan::SetOp { .. } => {
55                self = self.map_query_child(QueryChildSlot::Left, control, |query| {
56                    query.normalize_window_definitions(control)
57                })?;
58                self = self.map_query_child(QueryChildSlot::Right, control, |query| {
59                    query.normalize_window_definitions(control)
60                })?;
61            }
62            RelationalPlan::Values { .. } => {}
63        }
64        for index in 0..subqueries {
65            self = self.map_query_child(QueryChildSlot::Subquery(index), control, |query| {
66                query.normalize_window_definitions(control)
67            })?;
68        }
69        if let RelationalPlan::QueryBlock(block) = &self.root {
70            let resolved =
71                crate::plan::windows::resolved_window_definitions_with_control(block, control)?;
72            self = roots::normalize(self, &resolved, control)?;
73        }
74        self.prune_subqueries(control)
75    }
76}
77impl MutableCommandPlan {
78    pub fn normalize_window_definitions(
79        mut self,
80        control: &ProductionControl<'_>,
81    ) -> Result<Self, SQLError> {
82        self.assert_owner(control);
83        control.check()?;
84        for index in 0..self.ctes().len() {
85            self = self.map_cte(index, control, |plan| {
86                plan.normalize_window_definitions(control)
87            })?;
88        }
89        self = self.map_source(control, |source| normalize_source(source, control))?;
90        let subqueries = match &*self {
91            CommandPlan::Insert(plan) => {
92                let count = plan.subqueries.len();
93                if plan.source.is_some() {
94                    self =
95                        self.map_query_child(CommandQuerySlot::InsertSource, control, |query| {
96                            query.normalize_window_definitions(control)
97                        })?;
98                }
99                count
100            }
101            CommandPlan::Update(plan) => plan.subqueries.len(),
102            CommandPlan::Delete(plan) => plan.subqueries.len(),
103            CommandPlan::Merge(plan) => plan.subqueries.len(),
104            _ => 0,
105        };
106        for index in 0..subqueries {
107            self = self.map_query_child(CommandQuerySlot::Subquery(index), control, |query| {
108                query.normalize_window_definitions(control)
109            })?;
110        }
111        match &*self {
112            CommandPlan::CreateView { .. }
113            | CommandPlan::CreateMaterializedView { .. }
114            | CommandPlan::CreateTableAs { .. }
115            | CommandPlan::DeclareCursor { .. } => {
116                self.map_query_body(control, |query| query.normalize_window_definitions(control))
117            }
118            CommandPlan::Explain { .. } | CommandPlan::Prepare { .. } => {
119                self.map_executable_body(control, |body| body.normalize_window_definitions(control))
120            }
121            CommandPlan::Execute { params, .. } | CommandPlan::Call { args: params, .. } => {
122                let count = params.len();
123                for parameter in 0..count {
124                    let (call, queries) = match &*self {
125                        CommandPlan::Call { args, .. } => (true, args[parameter].subqueries.len()),
126                        CommandPlan::Execute { params, .. } => {
127                            (false, params[parameter].subqueries.len())
128                        }
129                        _ => unreachable!(),
130                    };
131                    for query in 0..queries {
132                        let slot = if call {
133                            CommandQuerySlot::CallArgumentSubquery {
134                                argument: parameter,
135                                query,
136                            }
137                        } else {
138                            CommandQuerySlot::ExecuteParameterSubquery { parameter, query }
139                        };
140                        self = self.map_query_child(slot, control, |query| {
141                            query.normalize_window_definitions(control)
142                        })?;
143                    }
144                }
145                Ok(self)
146            }
147            _ => Ok(self),
148        }
149    }
150}
151fn normalize_source(
152    mut source: MutableSourcePlan,
153    control: &ProductionControl<'_>,
154) -> Result<MutableSourcePlan, SQLError> {
155    control.check()?;
156    match &*source {
157        SourcePlan::Subquery { .. } => {
158            source.map_query(control, |query| query.normalize_window_definitions(control))
159        }
160        SourcePlan::Join { .. } => {
161            source = source.map_child(SourceChildSlot::Left, control, |source| {
162                normalize_source(source, control)
163            })?;
164            source.map_child(SourceChildSlot::Right, control, |source| {
165                normalize_source(source, control)
166            })
167        }
168        _ => Ok(source),
169    }
170}
171fn scalar(
172    mut expression: OwnedScalarExpr,
173    resolved: &[ScalarWindowSpec],
174    control: &ProductionControl<'_>,
175) -> Result<OwnedScalarExpr, SQLError> {
176    control.check()?;
177    if let ScalarExpr::WindowCall { spec, .. } = &*expression {
178        if let Some(slot) = spec.definition {
179            let canonical = resolved.get(slot).ok_or_else(|| {
180                super::super::windows::invalid("a call refers to a missing window definition")
181            })?;
182            expression = expression.replace_window_spec(canonical, control)?;
183        }
184    }
185    if let ScalarExpr::WindowCall { args, filter, .. } = &*expression {
186        let arguments = args.len();
187        let filter = filter.is_some();
188        let children = expression.child_count();
189        for index in 0..arguments {
190            expression =
191                expression.map_child(index, control, |child| scalar(child, resolved, control))?;
192        }
193        if filter {
194            expression = expression.map_child(children - 1, control, |child| {
195                scalar(child, resolved, control)
196            })?;
197        }
198        for index in arguments..children - usize::from(filter) {
199            expression =
200                expression.map_child(index, control, |child| scalar(child, resolved, control))?;
201        }
202        Ok(expression)
203    } else {
204        expression.map_children(control, |_, child| scalar(child, resolved, control))
205    }
206}