Skip to main content

uqa_sql/plan/
windows.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Canonical window clauses own analyzed inputs; expanded call specifications are derived copies.
8
9use super::{
10    CommandPlan, CtePlan, CtePlanBody, QueryBlockPlan, QueryPlan, RelationalPlan, SourcePlan,
11    UnifiedPlan,
12};
13use crate::{SQLError, ScalarExpr, ScalarWindowSpec};
14mod production;
15pub use production::resolved_window_definitions_with_control;
16
17/// Resolve the canonical own clauses without evaluating any expression.
18pub fn resolved_window_definitions(
19    block: &QueryBlockPlan,
20) -> Result<Vec<ScalarWindowSpec>, SQLError> {
21    resolved_window_definitions_with_control(
22        block,
23        &uqa_core::memory::ProductionControl::uncontrolled(),
24    )?
25    .into_uncontrolled()
26    .map_err(|_| unreachable!("ordinary canonical window owner"))
27}
28
29impl UnifiedPlan {
30    /// Refresh execution copies after input constants or stored identities change. Call only after identity-based input replacement has completed.
31    pub fn normalize_window_definitions(&mut self) -> Result<(), SQLError> {
32        match self {
33            Self::Query(query) => query.normalize_window_definitions(),
34            Self::Command(command) => normalize_command(command),
35        }
36    }
37}
38
39impl QueryPlan {
40    /// Keep each call's execution specification equal to its canonical query-local definition.
41    pub fn normalize_window_definitions(&mut self) -> Result<(), SQLError> {
42        normalize_ctes(&mut self.ctes)?;
43        let result = match &mut self.root {
44            RelationalPlan::QueryBlock(block) => {
45                if let Some(source) = &mut block.from {
46                    normalize_source(source)?;
47                }
48                for query in &mut block.subqueries {
49                    query.normalize_window_definitions()?;
50                }
51                let resolved = resolved_window_definitions(block)?;
52                let mut result = Ok(());
53                let mut update = |node: &mut ScalarExpr| {
54                    if result.is_ok() {
55                        if let ScalarExpr::WindowCall { spec, .. } = node {
56                            if let Some(slot) = spec.definition {
57                                match resolved.get(slot) {
58                                    Some(canonical) => spec.clone_from(canonical),
59                                    None => {
60                                        result = Err(invalid(
61                                            "a call refers to a missing window definition",
62                                        ));
63                                    }
64                                }
65                            }
66                        }
67                    }
68                };
69                visit_local_roots_mut(block, &mut |expression| expression.visit_mut(&mut update));
70                result
71            }
72            RelationalPlan::SetOp {
73                left,
74                right,
75                subqueries,
76                ..
77            } => {
78                left.normalize_window_definitions()?;
79                right.normalize_window_definitions()?;
80                for query in subqueries {
81                    query.normalize_window_definitions()?;
82                }
83                Ok(())
84            }
85            RelationalPlan::Values { subqueries, .. } => {
86                for query in subqueries {
87                    query.normalize_window_definitions()?;
88                }
89                Ok(())
90            }
91        };
92        result?;
93        super::subqueries::prune_query(self);
94        Ok(())
95    }
96}
97
98fn normalize_command(command: &mut CommandPlan) -> Result<(), SQLError> {
99    if let Some(ctes) = command.ctes_mut() {
100        normalize_ctes(ctes)?;
101    }
102    if let Some(source) = command.source_input_mut() {
103        normalize_source(source)?;
104    }
105    for query in command.query_inputs_mut() {
106        query.normalize_window_definitions()?;
107    }
108    match command {
109        CommandPlan::CreateView { query, .. }
110        | CommandPlan::CreateMaterializedView { query, .. }
111        | CommandPlan::CreateTableAs { query, .. }
112        | CommandPlan::DeclareCursor { query, .. } => query.normalize_window_definitions(),
113        CommandPlan::Explain { body, .. } | CommandPlan::Prepare { body, .. } => {
114            body.normalize_window_definitions()
115        }
116        CommandPlan::Execute { params, .. } | CommandPlan::Call { args: params, .. } => {
117            for expression in params {
118                for query in &mut expression.subqueries {
119                    query.normalize_window_definitions()?;
120                }
121            }
122            Ok(())
123        }
124        _ => Ok(()),
125    }
126}
127
128fn normalize_ctes(ctes: &mut [CtePlan]) -> Result<(), SQLError> {
129    for cte in ctes {
130        match &mut cte.body {
131            CtePlanBody::Query(query) => query.normalize_window_definitions()?,
132            CtePlanBody::Command(command) => normalize_command(command)?,
133        }
134    }
135    Ok(())
136}
137
138fn normalize_source(source: &mut SourcePlan) -> Result<(), SQLError> {
139    match source {
140        SourcePlan::Subquery { body, .. } => body.normalize_window_definitions(),
141        SourcePlan::Join { left, right, .. } => {
142            normalize_source(left)?;
143            normalize_source(right)
144        }
145        _ => Ok(()),
146    }
147}
148
149fn visit_local_roots_mut(block: &mut QueryBlockPlan, visit: &mut dyn FnMut(&mut ScalarExpr)) {
150    if let Some(source) = &mut block.from {
151        visit_source_roots_mut(source, visit);
152    }
153    for expression in block
154        .projections
155        .iter_mut()
156        .map(|projection| &mut projection.expr)
157        .chain(block.r#where.iter_mut())
158        .chain(block.group_by.iter_mut())
159        .chain(block.grouping_sets.iter_mut().flatten())
160        .chain(block.having.iter_mut())
161        .chain(block.order_by.iter_mut().map(|order| &mut order.expr))
162        .chain(block.limit.iter_mut())
163        .chain(block.offset.iter_mut())
164        .chain(block.distinct_on.iter_mut())
165    {
166        visit(expression);
167    }
168}
169
170fn visit_source_roots_mut(source: &mut SourcePlan, visit: &mut dyn FnMut(&mut ScalarExpr)) {
171    match source {
172        crate::plan::SourcePlan::RetainedRows(_) => {}
173        SourcePlan::Table { .. } | SourcePlan::Subquery { .. } => {}
174        SourcePlan::Join {
175            left, right, on, ..
176        } => {
177            visit_source_roots_mut(left, visit);
178            visit_source_roots_mut(right, visit);
179            if let Some(on) = on {
180                visit(on);
181            }
182        }
183        SourcePlan::Values { rows, .. } => {
184            for expression in rows.iter_mut().flatten() {
185                visit(expression);
186            }
187        }
188        SourcePlan::Function { args, .. } => {
189            for expression in args {
190                visit(expression);
191            }
192        }
193        SourcePlan::FunctionGroup { functions, .. } => {
194            for expression in functions.iter_mut().flat_map(|function| &mut function.args) {
195                visit(expression);
196            }
197        }
198    }
199}
200
201pub(in crate::plan) fn invalid(message: &str) -> SQLError {
202    SQLError::Internal(format!("invalid stored window definitions: {message}"))
203}
204
205#[cfg(test)]
206mod tests;