Skip to main content

uqa_sql/plan/
source_metadata.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Declared metadata of SQL-invisible VALUES inputs, including empty carriers.
8
9use super::SourcePlan;
10use crate::{RowSchema, SQLError};
11
12#[cfg(test)]
13mod tests;
14
15impl SourcePlan {
16    /// Explicit LATERAL permission retained by a range item independently of its parent join.
17    pub fn is_explicitly_lateral(&self) -> bool {
18        matches!(
19            self,
20            Self::Values { lateral: true, .. } | Self::Subquery { lateral: true, .. }
21        )
22    }
23
24    /// Recover an internal VALUES schema from its declarations without sampling a row or exposing SQL-visible attributes.
25    pub fn internal_values_schema(&self) -> Result<Option<RowSchema>, SQLError> {
26        self.internal_values_schema_with_inference(None)
27    }
28
29    /// Fill undeclared captured attributes from their caller scope, retaining explicit declarations and collations unchanged.
30    pub fn internal_values_schema_with_inference(
31        &self,
32        inferred: Option<&RowSchema>,
33    ) -> Result<Option<RowSchema>, SQLError> {
34        self.internal_values_schema_with_control(
35            inferred,
36            &uqa_core::memory::ProductionControl::uncontrolled(),
37        )
38    }
39
40    pub fn internal_values_schema_with_control(
41        &self,
42        inferred: Option<&RowSchema>,
43        control: &uqa_core::memory::ProductionControl<'_>,
44    ) -> Result<Option<RowSchema>, SQLError> {
45        control.check()?;
46        let Self::Values {
47            internal_relation: Some(relation),
48            internal_column_types: types,
49            internal_column_collations: collations,
50            ..
51        } = self
52        else {
53            return Ok(None);
54        };
55        if !collations.is_empty() && collations.len() != types.len() {
56            return Err(SQLError::Internal(
57                "internal VALUES collation width does not match its declared attributes".into(),
58            ));
59        }
60        let metadata = types.iter().enumerate().map(|(position, declared)| {
61            let ty = declared
62                .as_ref()
63                .or_else(|| inferred.and_then(|schema| schema.column_type(position)));
64            let collation = collations.get(position).copied().flatten().or_else(|| {
65                declared
66                    .is_none()
67                    .then(|| inferred.and_then(|schema| schema.column_collation(position)))
68                    .flatten()
69            });
70            (ty, collation)
71        });
72        RowSchema::with_internal_relation_metadata_with_control(*relation, metadata, control)
73            .map(Some)
74    }
75}