Skip to main content

uqa_sql/plan/mutable/
slots.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Typed scalar locations share the query constructor's field ownership.
8
9use super::{memory::RewriteMemory, QueryPlan, RelationalPlan, ScalarExpr};
10
11/// A scalar root in one query's own expression namespace. Nested sources and query children retain separate owners.
12#[derive(Clone, Copy, Debug)]
13pub enum QueryScalarSlot {
14    Projection(usize),
15    Where,
16    GroupBy(usize),
17    GroupingSet { set: usize, expression: usize },
18    Having,
19    OrderBy(usize),
20    Limit,
21    Offset,
22    DistinctOn(usize),
23    WindowPartition { window: usize, expression: usize },
24    WindowOrder { window: usize, expression: usize },
25    WindowFrameStart(usize),
26    WindowFrameEnd(usize),
27    Value { row: usize, column: usize },
28}
29
30impl QueryScalarSlot {
31    pub(super) fn expression_mut(self, query: &mut QueryPlan) -> Option<&mut ScalarExpr> {
32        match &mut query.root {
33            RelationalPlan::QueryBlock(block) => match self {
34                Self::Projection(index) => Some(&mut block.projections[index].expr),
35                Self::Where => block.r#where.as_mut(),
36                Self::GroupBy(index) => Some(&mut block.group_by[index]),
37                Self::GroupingSet { set, expression } => {
38                    Some(&mut block.grouping_sets[set][expression])
39                }
40                Self::Having => block.having.as_mut(),
41                Self::OrderBy(index) => Some(&mut block.order_by[index].expr),
42                Self::Limit => block.limit.as_mut(),
43                Self::Offset => block.offset.as_mut(),
44                Self::DistinctOn(index) => Some(&mut block.distinct_on[index]),
45                Self::WindowPartition { window, expression } => {
46                    Some(&mut block.windows[window].spec.partition_by[expression])
47                }
48                Self::WindowOrder { window, expression } => {
49                    Some(&mut block.windows[window].spec.order_by[expression].expr)
50                }
51                Self::WindowFrameStart(window) | Self::WindowFrameEnd(window) => {
52                    let frame = block.windows[window].spec.frame.as_mut()?;
53                    match if matches!(self, Self::WindowFrameStart(_)) {
54                        &mut frame.start
55                    } else {
56                        &mut frame.end
57                    } {
58                        crate::ScalarFrameBound::Preceding(expression)
59                        | crate::ScalarFrameBound::Following(expression) => Some(expression),
60                        _ => None,
61                    }
62                }
63                Self::Value { .. } => panic!("VALUES scalar belongs to a VALUES root"),
64            },
65            RelationalPlan::Values { rows, .. } => match self {
66                Self::Value { row, column } => Some(&mut rows[row][column]),
67                _ => panic!("query-block scalar belongs to a query block"),
68            },
69            RelationalPlan::SetOp {
70                order_by,
71                limit,
72                offset,
73                ..
74            } => match self {
75                Self::OrderBy(index) => Some(&mut order_by[index].expr),
76                Self::Limit => limit.as_deref_mut(),
77                Self::Offset => offset.as_deref_mut(),
78                _ => panic!("set-operation scalar belongs to its ordering or slice"),
79            },
80        }
81    }
82
83    pub(super) fn memory_mut(
84        self,
85        memory: &mut RewriteMemory,
86    ) -> &mut Option<crate::plan::scalar::ScalarMemory> {
87        let root = memory.field_mut("root").as_mut().expect("query root");
88        let has_block = match root {
89            RewriteMemory::Fields { fields, .. } => {
90                fields.iter().any(|field| field.name == "block")
91            }
92            RewriteMemory::Scalar(_) | RewriteMemory::Scalars { .. } => {
93                unreachable!("query root owner")
94            }
95        };
96        let root = if has_block {
97            root.field_mut("block").as_mut().expect("query block")
98        } else {
99            root
100        };
101        match self {
102            Self::Projection(index) => item(root, "projections", index).scalar_mut(),
103            Self::Where => field(root, "where").scalar_mut(),
104            Self::GroupBy(index) => item(root, "group_by", index).scalar_mut(),
105            Self::GroupingSet { set, expression } => {
106                item(root, "grouping_sets", set).scalar_item_mut(expression)
107            }
108            Self::Having => field(root, "having").scalar_mut(),
109            Self::OrderBy(index) => item(root, "order_by", index).scalar_mut(),
110            Self::Limit => field(root, "limit").scalar_mut(),
111            Self::Offset => field(root, "offset").scalar_mut(),
112            Self::DistinctOn(index) => item(root, "distinct_on", index).scalar_mut(),
113            Self::WindowPartition { window, expression } => item(
114                field(item(root, "windows", window), "spec"),
115                "partition_by",
116                expression,
117            )
118            .scalar_mut(),
119            Self::WindowOrder { window, expression } => item(
120                field(item(root, "windows", window), "spec"),
121                "order_by",
122                expression,
123            )
124            .scalar_mut(),
125            Self::WindowFrameStart(window) | Self::WindowFrameEnd(window) => field(
126                field(field(item(root, "windows", window), "spec"), "frame"),
127                if matches!(self, Self::WindowFrameStart(_)) {
128                    "start"
129                } else {
130                    "end"
131                },
132            )
133            .scalar_mut(),
134            Self::Value { row, column } => item(root, "rows", row).scalar_item_mut(column),
135        }
136    }
137}
138
139fn field<'a>(memory: &'a mut RewriteMemory, name: &str) -> &'a mut RewriteMemory {
140    memory.field_mut(name).as_mut().expect("copied query field")
141}
142
143fn item<'a>(memory: &'a mut RewriteMemory, name: &str, index: usize) -> &'a mut RewriteMemory {
144    field(memory, name)
145        .item_mut(index)
146        .as_mut()
147        .expect("copied query item")
148}