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    /// Recover an internal VALUES schema from its declarations without sampling a row or exposing SQL-visible attributes.
17    pub fn internal_values_schema(&self) -> Result<Option<RowSchema>, SQLError> {
18        self.internal_values_schema_with_inference(None)
19    }
20
21    /// Fill undeclared captured attributes from their caller scope, retaining explicit declarations and collations unchanged.
22    pub fn internal_values_schema_with_inference(
23        &self,
24        inferred: Option<&RowSchema>,
25    ) -> Result<Option<RowSchema>, SQLError> {
26        let Self::Values {
27            internal_relation: Some(relation),
28            internal_column_types: types,
29            internal_column_collations: collations,
30            ..
31        } = self
32        else {
33            return Ok(None);
34        };
35        if !collations.is_empty() && collations.len() != types.len() {
36            return Err(SQLError::Internal(
37                "internal VALUES collation width does not match its declared attributes".into(),
38            ));
39        }
40        let metadata = types
41            .iter()
42            .enumerate()
43            .map(|(position, declared)| {
44                let inferred_type = inferred
45                    .and_then(|schema| schema.column_types().get(position))
46                    .cloned()
47                    .flatten();
48                let ty = declared.clone().or(inferred_type);
49                let collation = collations.get(position).copied().flatten().or_else(|| {
50                    declared
51                        .is_none()
52                        .then(|| inferred.and_then(|schema| schema.column_collation(position)))
53                        .flatten()
54                });
55                (ty, collation)
56            })
57            .collect::<Vec<_>>();
58        for (ty, oid) in &metadata {
59            if oid.is_some_and(|oid| oid != 0)
60                && !ty
61                    .as_ref()
62                    .is_some_and(crate::schema::composites::type_is_collatable)
63            {
64                return Err(SQLError::Internal(
65                    "internal VALUES collation requires a collatable attribute type".into(),
66                ));
67            }
68        }
69        Ok(Some(RowSchema::with_internal_relation_metadata(
70            *relation, metadata,
71        )))
72    }
73}