Skip to main content

uqa_sql/schema/production/
canonical.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Canonical row boundaries admit lookup ordering and physical-slot remapping before publishing their immutable layout.
8
9use super::{
10    copy,
11    lease::{boxed_text, SchemaMemory},
12    optional_type, parts,
13};
14use crate::{
15    schema::{ColumnIdentity, RowSchema, SchemaBuildMetadata, SchemaMap, SchemaSet, NULL_SLOT},
16    SQLError,
17};
18use uqa_core::memory::{Produced, ProductionControl, ProductionMap, ProductionVec};
19
20#[cfg(test)]
21mod tests;
22
23impl RowSchema {
24    pub fn canonical_projection_with_control(
25        &self,
26        control: &ProductionControl<'_>,
27    ) -> Result<(Self, Produced<Vec<usize>>), SQLError> {
28        self.project_canonical_with_control(false, control)
29    }
30
31    /// Establish a new relation's attribute order independently of its input's physical slots. Every visible attribute gets its own position, including repeated inputs and NULL slots; hidden executor attributes retain their selected values.
32    pub fn canonical_relation_projection_with_control(
33        &self,
34        control: &ProductionControl<'_>,
35    ) -> Result<(Self, Produced<Vec<usize>>), SQLError> {
36        self.project_canonical_with_control(true, control)
37    }
38
39    fn project_canonical_with_control(
40        &self,
41        distinct_columns: bool,
42        control: &ProductionControl<'_>,
43    ) -> Result<(Self, Produced<Vec<usize>>), SQLError> {
44        control.check()?;
45        let mut source_slots = ProductionVec::new(*control);
46        let mut positions = ProductionMap::new(*control);
47        let mut slots = ProductionVec::new(*control);
48        for slot in &self.index.slots {
49            let position = if distinct_columns {
50                let position = source_slots.len();
51                source_slots.push_copy(*slot)?;
52                if *slot != NULL_SLOT && positions.get(slot).is_none() {
53                    positions.insert_copy(*slot, position)?;
54                }
55                position
56            } else {
57                remap(*slot, &mut source_slots, &mut positions)?
58            };
59            slots.push_copy(position)?;
60        }
61        let mut source_aliases = ProductionVec::new(*control);
62        for (identity, slot) in &self.index.aliases {
63            source_aliases.push_copy((identity, *slot))?;
64        }
65        source_aliases
66            .as_mut_slice()
67            .sort_unstable_by_key(|(identity, _)| *identity);
68        let aliases = SchemaMap::from_produced(
69            source_aliases.iter().map(|(identity, slot)| {
70                Ok((
71                    identity.clone_with_control(control)?,
72                    inline(remap(*slot, &mut source_slots, &mut positions)?, control)?,
73                ))
74            }),
75            control,
76        )?;
77        let mut source_internal = ProductionVec::new(*control);
78        for (column, slot) in &self.index.executor_attributes {
79            source_internal.push_copy((*column, *slot))?;
80        }
81        source_internal
82            .as_mut_slice()
83            .sort_unstable_by_key(|(column, _)| *column);
84        let internal = SchemaMap::from_produced(
85            source_internal.iter().map(|(column, slot)| {
86                Ok((
87                    inline(*column, control)?,
88                    inline(remap(*slot, &mut source_slots, &mut positions)?, control)?,
89                ))
90            }),
91            control,
92        )?;
93        let metadata = self.canonical_metadata(aliases, internal, &source_slots, control)?;
94        let mut columns = ProductionVec::new(*control);
95        let mut identities = ProductionVec::new(*control);
96        let mut types = ProductionVec::new(*control);
97        for name in self.columns() {
98            columns.push_produced(control.copy_text(name)?)?;
99        }
100        for identity in self.identities() {
101            identities.push_produced(identity.clone_with_control(control)?)?;
102        }
103        for ty in self.column_types() {
104            types.push_produced(optional_type(ty.as_ref(), control)?)?;
105        }
106        let output = parts::produce(
107            columns.finish()?,
108            identities.finish()?,
109            types.finish()?,
110            slots.finish()?,
111            source_slots.len(),
112            metadata,
113            control,
114        )?;
115        Ok((output, source_slots.finish()?))
116    }
117    fn canonical_metadata(
118        &self,
119        aliases: SchemaMap<ColumnIdentity, usize>,
120        internal: SchemaMap<crate::ast::InternalColumnRef, usize>,
121        source_slots: &[usize],
122        control: &ProductionControl<'_>,
123    ) -> Result<SchemaBuildMetadata, SQLError> {
124        let cold = &self.index.cold;
125        let scores = copy::score_sources(self, control)?;
126        let (score_sources, memory) = scores.into_parts();
127        Ok(SchemaBuildMetadata {
128            collations: cold.collations.copy_with_control(control)?,
129            record_fields: SchemaMap::from_produced(
130                source_slots
131                    .iter()
132                    .enumerate()
133                    .filter_map(|(position, slot)| {
134                        cold.record_fields.get(slot).map(|fields| {
135                            Ok((inline(position, control)?, inline(fields.clone(), control)?))
136                        })
137                    }),
138                control,
139            )?,
140            aliases,
141            internal,
142            alias_types: identity_types(&cold.aliases, control)?,
143            internal_types: SchemaMap::from_produced(
144                cold.executor_attribute_types.iter().map(|(column, ty)| {
145                    Ok((
146                        inline(*column, control)?,
147                        optional_type(ty.as_ref(), control)?,
148                    ))
149                }),
150                control,
151            )?,
152            score_sources,
153            wildcard_hidden: SchemaSet::from_produced(
154                cold.wildcard_hidden
155                    .iter()
156                    .map(|position| inline(*position, control)),
157                control,
158            )?,
159            binding_only: identity_types(&cold.binding_only, control)?,
160            row_types: cold.row_types.clone(),
161            row_presence: cold.row_presence.clone(),
162            open_qualifiers: SchemaSet::from_produced(
163                cold.open_qualifiers.iter().map(|name| {
164                    let (name, memory) = match name {
165                        Some(name) => {
166                            let (name, memory) = boxed_text(name, control)?.into_parts();
167                            (Some(name), memory)
168                        }
169                        None => (None, control.empty_reservation()),
170                    };
171                    Ok(control.finish(name, memory)?)
172                }),
173                control,
174            )?,
175            memory: SchemaMemory::new(memory),
176            ..SchemaBuildMetadata::empty_with_control(control)
177        })
178    }
179}
180
181fn remap(
182    slot: usize,
183    sources: &mut ProductionVec<'_, usize>,
184    positions: &mut ProductionMap<'_, usize, usize>,
185) -> Result<usize, SQLError> {
186    if slot == NULL_SLOT {
187        return Ok(NULL_SLOT);
188    }
189    if let Some(position) = positions.get(&slot) {
190        return Ok(*position);
191    }
192    let position = sources.len();
193    sources.push_copy(slot)?;
194    positions.insert_copy(slot, position)?;
195    Ok(position)
196}
197
198fn inline<T>(value: T, control: &ProductionControl<'_>) -> Result<Produced<T>, SQLError> {
199    Ok(control.finish(value, control.empty_reservation())?)
200}
201
202fn identity_types(
203    input: &SchemaMap<ColumnIdentity, Option<crate::ColumnType>>,
204    control: &ProductionControl<'_>,
205) -> Result<SchemaMap<ColumnIdentity, Option<crate::ColumnType>>, SQLError> {
206    SchemaMap::from_produced(
207        input.iter().map(|(identity, ty)| {
208            Ok((
209                identity.clone_with_control(control)?,
210                optional_type(ty.as_ref(), control)?,
211            ))
212        }),
213        control,
214    )
215}