Skip to main content

uqa_sql/semantics/view_rewrite/
production.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Automatic view layers retain independently movable columns and scalar-query ownership.
8
9use super::{
10    context::{stored_view_schema_with_control, ViewRewriteContext},
11    ColumnRestriction, ComputePlan, NotUpdatableReason, RelationalPlan, SQLError, ScalarExpr,
12    SourcePlan, StoredViewKind, ViewCheckOption,
13};
14use crate::{
15    catalog::view::ViewRewriteDefinitionRef,
16    plan::{OwnedScalarExpr, ScalarQueryArena},
17    RowSchema,
18};
19use uqa_core::memory::{Produced, ProductionControl, ProductionMap, ProductionVec};
20
21mod columns;
22mod frozen;
23
24pub struct OwnedViewColumn {
25    pub name: Produced<String>,
26    pub collation_oid: Option<u32>,
27    pub expression: OwnedScalarExpr,
28    pub writable_source_column: Option<Produced<String>>,
29}
30
31pub struct OwnedAutomaticViewLayer {
32    pub canonical_name: Produced<String>,
33    pub source_name: Produced<String>,
34    pub source_qualifier: Produced<String>,
35    pub source_column_map: Produced<Vec<(String, String)>>,
36    pub source_include_descendants: bool,
37    pub source_schema: RowSchema,
38    pub columns: Produced<Vec<OwnedViewColumn>>,
39    pub predicate: Option<OwnedScalarExpr>,
40    pub subqueries: ScalarQueryArena,
41    pub check_option: ViewCheckOption,
42}
43
44impl OwnedAutomaticViewLayer {
45    pub fn physical_source_column<'a>(&'a self, column: &'a str) -> &'a str {
46        self.source_column_map
47            .binary_search_by(|(name, _)| name.as_str().cmp(column))
48            .map_or(column, |index| self.source_column_map[index].1.as_str())
49    }
50    pub fn column_restriction(&self, column: &OwnedViewColumn) -> ColumnRestriction {
51        let name = match &*column.expression {
52            ScalarExpr::Column(name) => Some(name),
53            ScalarExpr::QualifiedColumn { qualifier, column }
54                if super::source_qualifier_matches(
55                    qualifier,
56                    &self.source_qualifier,
57                    &self.source_name,
58                ) =>
59            {
60                Some(column)
61            }
62            _ => None,
63        };
64        if name.is_some_and(|name| {
65            crate::schema::columns::POSTGRES_SYSTEM_COLUMNS.contains(&name.as_str())
66        }) {
67            ColumnRestriction::SystemColumn
68        } else {
69            ColumnRestriction::Computed
70        }
71    }
72}
73
74/// Shape analysis preserves the first rejection reason without constructing a layer for rejected views.
75#[expect(
76    clippy::large_enum_variant,
77    reason = "the independently admitted layer moves without a temporary root allocation"
78)]
79pub enum OwnedViewQueryShape {
80    Updatable(OwnedAutomaticViewLayer),
81    NotUpdatable(NotUpdatableReason),
82}
83
84pub fn automatic_view_layer_owned(
85    services: ViewRewriteContext<'_>,
86    name: &str,
87    control: &ProductionControl<'_>,
88) -> Result<Option<OwnedAutomaticViewLayer>, SQLError> {
89    Ok(match view_query_shape_owned(services, name, control)? {
90        Some(OwnedViewQueryShape::Updatable(layer)) => Some(layer),
91        Some(OwnedViewQueryShape::NotUpdatable(_)) | None => None,
92    })
93}
94
95pub fn view_query_shape_owned(
96    services: ViewRewriteContext<'_>,
97    name: &str,
98    control: &ProductionControl<'_>,
99) -> Result<Option<OwnedViewQueryShape>, SQLError> {
100    let Some(canonical) = services
101        .catalog
102        .try_resolve_view_name_with_control(name, control)?
103    else {
104        return Ok(None);
105    };
106    let mut result = None;
107    services
108        .catalog
109        .with_view_definition_with_control(&canonical, control, &mut |definition| {
110            let definition = definition.ok_or_else(|| SQLError::UnknownTable(name.into()))?;
111            if definition.kind == StoredViewKind::View {
112                result = Some(shape_from_definition(
113                    services, &canonical, definition, control,
114                )?);
115            }
116            Ok(())
117        })?;
118    Ok(result)
119}
120
121fn restriction(
122    services: ViewRewriteContext<'_>,
123    query: &crate::plan::QueryPlan,
124    control: &ProductionControl<'_>,
125) -> Result<Option<NotUpdatableReason>, SQLError> {
126    control.check()?;
127    let block = match &query.root {
128        RelationalPlan::QueryBlock(block) => block,
129        RelationalPlan::SetOp { .. } => return Ok(Some(NotUpdatableReason::SetOperation)),
130        RelationalPlan::Values { .. } => return Ok(Some(NotUpdatableReason::NotSingleRelation)),
131    };
132    Ok(if block.distinct || !block.distinct_on.is_empty() {
133        Some(NotUpdatableReason::Distinct)
134    } else if !block.group_by.is_empty() || !block.grouping_sets.is_empty() || block.group_distinct
135    {
136        Some(NotUpdatableReason::GroupBy)
137    } else if block.having.is_some() {
138        Some(NotUpdatableReason::Having)
139    } else if !query.ctes.is_empty() {
140        Some(NotUpdatableReason::With)
141    } else if block.limit.is_some() || block.offset.is_some() || block.with_ties {
142        Some(NotUpdatableReason::LimitOffset)
143    } else if matches!(block.compute, ComputePlan::Aggregate)
144        || (matches!(block.compute, ComputePlan::Window)
145            && crate::semantics::aggregates::has_aggregate_with_control(
146                services.routines,
147                &block.projections,
148                control,
149            )?)
150    {
151        Some(NotUpdatableReason::Aggregate)
152    } else if matches!(block.compute, ComputePlan::Window) {
153        Some(NotUpdatableReason::Window)
154    } else {
155        None
156    })
157}
158
159pub(super) fn shape_from_definition(
160    services: ViewRewriteContext<'_>,
161    canonical: &str,
162    definition: ViewRewriteDefinitionRef<'_>,
163    control: &ProductionControl<'_>,
164) -> Result<OwnedViewQueryShape, SQLError> {
165    if let Some(reason) = restriction(services, definition.query, control)? {
166        return Ok(OwnedViewQueryShape::NotUpdatable(reason));
167    }
168    let RelationalPlan::QueryBlock(block) = &definition.query.root else {
169        unreachable!("non-query blocks have a structural restriction");
170    };
171    let scope = services.catalog.binding_scope_with_control(control)?;
172    let source_schema = match block.from.as_ref() {
173        Some(source) => crate::binding::analyze_source_plan_schema_with_control(
174            services.routines,
175            source,
176            &[],
177            scope.context_with_control(control)?,
178            None,
179            control,
180        )?,
181        None => RowSchema::new_with_control(
182            control.finish(Vec::new(), control.empty_reservation())?,
183            control,
184        )?,
185    };
186    let resolver = crate::binding::scoped_types::BindingTypeResolver {
187        routines: services.routines,
188        scope: &scope,
189    };
190    for projection in &block.projections {
191        if crate::semantics::sets::validation::expression_may_return_set_with_control(
192            services.routines,
193            &resolver,
194            &projection.expr,
195            &source_schema,
196            &[],
197            control,
198        )? {
199            return Ok(OwnedViewQueryShape::NotUpdatable(
200                NotUpdatableReason::SetReturning,
201            ));
202        }
203    }
204    let Some(SourcePlan::Table {
205        name: source_name,
206        qualifier,
207        alias,
208        column_aliases,
209        include_descendants,
210        ..
211    }) = block.from.as_ref()
212    else {
213        return Ok(OwnedViewQueryShape::NotUpdatable(
214            NotUpdatableReason::NotSingleRelation,
215        ));
216    };
217    if services
218        .catalog
219        .target_view_kind_with_control(source_name, control)?
220        == Some(StoredViewKind::Materialized)
221    {
222        return Ok(OwnedViewQueryShape::NotUpdatable(
223            NotUpdatableReason::NotSingleRelation,
224        ));
225    }
226    let source_qualifier = alias.as_deref().unwrap_or(qualifier);
227    let source_columns = super::relation_columns_with_control(services, source_name, control)?;
228    let mut selected = ProductionMap::new(*control);
229    for (position, column) in source_columns.iter().enumerate() {
230        selected.insert_copy(
231            column_aliases.get(position).unwrap_or(column).as_str(),
232            column.as_str(),
233        )?;
234    }
235    let source_map = retain_column_mapping(&selected, control)?;
236    let output = stored_view_schema_with_control(services, definition, control)?;
237    let columns = columns::produce(
238        block,
239        source_name,
240        source_qualifier,
241        &source_columns,
242        column_aliases,
243        &selected,
244        &output,
245        canonical,
246        control,
247    )?;
248    Ok(OwnedViewQueryShape::Updatable(OwnedAutomaticViewLayer {
249        canonical_name: control.copy_text(canonical)?,
250        source_name: control.copy_text(source_name)?,
251        source_qualifier: control.copy_text(source_qualifier)?,
252        source_column_map: source_map,
253        source_include_descendants: *include_descendants,
254        source_schema,
255        columns,
256        predicate: block
257            .r#where
258            .as_ref()
259            .map(|expression| expression.copy_for_rewrite(control))
260            .transpose()?,
261        subqueries: ScalarQueryArena::copy_from(&block.subqueries, control)?,
262        check_option: ViewCheckOption::from_options(definition.options),
263    }))
264}
265
266fn retain_column_mapping(
267    selected: &ProductionMap<'_, &str, &str>,
268    control: &ProductionControl<'_>,
269) -> Result<Produced<Vec<(String, String)>>, SQLError> {
270    let mut source_map = ProductionVec::new(*control);
271    for (visible, physical) in selected {
272        let visible = control.copy_text(visible)?;
273        let physical = control.copy_text(physical)?;
274        let (visible, left) = visible.into_parts();
275        let (physical, right) = physical.into_parts();
276        source_map
277            .push_produced(control.finish((visible, physical), control.combine(left, right))?)?;
278    }
279    Ok(source_map.finish()?)
280}
281
282#[cfg(test)]
283mod tests;