Skip to main content

uqa_sql/schema/production/
projection.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Physical projection layouts admit only their surviving columns and preserve independent hidden metadata.
8
9use super::{copy, lease::SchemaMemory, optional_type, parts};
10use crate::{
11    ast::InternalColumnRef,
12    production::Buffer,
13    schema::{
14        ColumnIdentity, ColumnType, ProjectedSlot, RowSchema, SchemaBuildMetadata, SchemaMap,
15        SchemaSet, NULL_SLOT,
16    },
17    SQLError,
18};
19use uqa_core::memory::{Produced, ProductionControl, ProductionVec};
20
21struct Column<'a> {
22    name: &'a str,
23    ty: Option<&'a ColumnType>,
24    identity: Option<&'a ColumnIdentity>,
25    source: ProjectedSlot,
26    replaced: bool,
27}
28
29impl RowSchema {
30    /// Build a physical output from borrowed selected fields. Replacement releases no unrelated metadata and copies no discarded column payload.
31    pub fn project_with_sources_with_control<'a>(
32        input: &'a Self,
33        projected: impl IntoIterator<Item = (&'a str, Option<&'a ColumnType>, ProjectedSlot)>,
34        projected_internal: &[(InternalColumnRef, Option<&ColumnType>, ProjectedSlot)],
35        computed_count: usize,
36        pass_through: bool,
37        control: &ProductionControl<'_>,
38    ) -> Result<Self, SQLError> {
39        control.check()?;
40        let mut columns = Buffer::new(control);
41        if pass_through {
42            for (position, name) in input.columns().iter().enumerate() {
43                columns.push(
44                    Column {
45                        name,
46                        ty: input.column_type(position),
47                        identity: input.identity(position),
48                        source: ProjectedSlot::Input(input.physical_slot(position)),
49                        replaced: false,
50                    },
51                    control,
52                )?;
53            }
54        }
55        let mut collations = input.index.cold.collations.copy_with_control(control)?;
56        for (column, ty, source) in projected_internal {
57            collations.internal_with_control(
58                *column,
59                source_collation(input, *source),
60                *ty,
61                control,
62            )?;
63        }
64        if !pass_through {
65            collations.clear_columns();
66        }
67        for (name, ty, source) in projected {
68            control.check()?;
69            let position = if pass_through {
70                columns.iter().position(|column| column.name == name)
71            } else {
72                None
73            };
74            let column = Column {
75                name,
76                ty,
77                identity: None,
78                source,
79                replaced: true,
80            };
81            let position = if let Some(position) = position {
82                columns[position] = column;
83                position
84            } else {
85                let position = columns.len();
86                columns.push(column, control)?;
87                position
88            };
89            collations.column_with_control(
90                position,
91                source_collation(input, source),
92                ty,
93                control,
94            )?;
95        }
96        let mut names = ProductionVec::new(*control);
97        let mut identities = ProductionVec::new(*control);
98        let mut types = ProductionVec::new(*control);
99        let mut slots = ProductionVec::new(*control);
100        for column in columns.iter() {
101            names.push_produced(control.copy_text(column.name)?)?;
102            identities.push_produced(match column.identity {
103                Some(identity) => identity.clone_with_control(control)?,
104                None => ColumnIdentity::from_parts_with_control(None, column.name, control)?,
105            })?;
106            types.push_produced(optional_type(column.ty, control)?)?;
107            slots.push_copy(resolve_slot(input, column.source))?;
108        }
109        let metadata = projection_metadata(
110            input,
111            projected_internal,
112            collations,
113            pass_through,
114            &columns,
115            control,
116        )?;
117        parts::produce(
118            names.finish()?,
119            identities.finish()?,
120            types.finish()?,
121            slots.finish()?,
122            input.physical_width() + computed_count,
123            metadata,
124            control,
125        )
126    }
127}
128
129fn projection_metadata(
130    input: &RowSchema,
131    projected_internal: &[(InternalColumnRef, Option<&ColumnType>, ProjectedSlot)],
132    collations: crate::schema::Collations,
133    pass_through: bool,
134    columns: &[Column<'_>],
135    control: &ProductionControl<'_>,
136) -> Result<SchemaBuildMetadata, SQLError> {
137    let (scores, score_memory) = copy::score_sources(input, control)?.into_parts();
138    let cold = &input.index.cold;
139    let inherited = if pass_through {
140        inherited_metadata(input, columns, control)?
141    } else {
142        SchemaBuildMetadata::empty_with_control(control)
143    };
144    Ok(SchemaBuildMetadata {
145        collations,
146        record_fields: SchemaMap::from_produced(
147            cold.record_fields.iter().map(|(slot, record)| {
148                Ok((inline(*slot, control)?, inline(record.clone(), control)?))
149            }),
150            control,
151        )?,
152        internal: SchemaMap::from_produced(
153            input
154                .index
155                .executor_attributes
156                .iter()
157                .map(|(column, slot)| Ok((inline(*column, control)?, inline(*slot, control)?)))
158                .chain(projected_internal.iter().map(|(column, _, source)| {
159                    Ok((
160                        inline(*column, control)?,
161                        inline(resolve_slot(input, *source), control)?,
162                    ))
163                })),
164            control,
165        )?,
166        internal_types: SchemaMap::from_produced(
167            cold.executor_attribute_types
168                .iter()
169                .map(|(column, ty)| {
170                    Ok((
171                        inline(*column, control)?,
172                        optional_type(ty.as_ref(), control)?,
173                    ))
174                })
175                .chain(projected_internal.iter().map(|(column, ty, _)| {
176                    Ok((inline(*column, control)?, optional_type(*ty, control)?))
177                })),
178            control,
179        )?,
180        score_sources: scores,
181        memory: SchemaMemory::new(score_memory),
182        ..inherited
183    })
184}
185
186fn inherited_metadata(
187    input: &RowSchema,
188    columns: &[Column<'_>],
189    control: &ProductionControl<'_>,
190) -> Result<SchemaBuildMetadata, SQLError> {
191    let cold = &input.index.cold;
192    Ok(SchemaBuildMetadata {
193        aliases: SchemaMap::from_produced(
194            input.index.aliases.iter().map(|(identity, slot)| {
195                Ok((
196                    identity.clone_with_control(control)?,
197                    inline(*slot, control)?,
198                ))
199            }),
200            control,
201        )?,
202        alias_types: identity_types(
203            cold.aliases
204                .iter()
205                .map(|(identity, ty)| (identity, ty.as_ref())),
206            control,
207        )?,
208        binding_only: identity_types(
209            cold.binding_only
210                .iter()
211                .map(|(identity, ty)| (identity, ty.as_ref())),
212            control,
213        )?,
214        wildcard_hidden: SchemaSet::from_produced(
215            cold.wildcard_hidden
216                .iter()
217                .filter(|position| !columns[**position].replaced)
218                .map(|position| inline(*position, control)),
219            control,
220        )?,
221        open_qualifiers: SchemaSet::from_produced(
222            cold.open_qualifiers.iter().map(|name| {
223                let (name, memory) = match name.as_deref() {
224                    Some(name) => {
225                        let (name, memory) = super::lease::boxed_text(name, control)?.into_parts();
226                        (Some(name), memory)
227                    }
228                    None => (None, control.empty_reservation()),
229                };
230                Ok(control.finish(name, memory)?)
231            }),
232            control,
233        )?,
234        row_types: cold.row_types.clone(),
235        row_presence: cold.row_presence.clone(),
236        ..SchemaBuildMetadata::empty_with_control(control)
237    })
238}
239
240fn resolve_slot(input: &RowSchema, source: ProjectedSlot) -> usize {
241    match source {
242        ProjectedSlot::Input(slot) | ProjectedSlot::BoundInput { physical: slot, .. } => {
243            slot.unwrap_or(NULL_SLOT)
244        }
245        ProjectedSlot::Computed { position, .. } => input.physical_width() + position,
246    }
247}
248
249fn source_collation(input: &RowSchema, source: ProjectedSlot) -> Option<u32> {
250    match source {
251        ProjectedSlot::Input(Some(slot)) => input.inherited_physical_collation(slot),
252        ProjectedSlot::BoundInput { collation, .. } | ProjectedSlot::Computed { collation, .. } => {
253            collation
254        }
255        ProjectedSlot::Input(None) => None,
256    }
257}
258
259fn inline<T>(value: T, control: &ProductionControl<'_>) -> Result<Produced<T>, SQLError> {
260    Ok(control.finish(value, control.empty_reservation())?)
261}
262
263fn identity_types<'a>(
264    entries: impl IntoIterator<Item = (&'a ColumnIdentity, Option<&'a ColumnType>)>,
265    control: &ProductionControl<'_>,
266) -> Result<SchemaMap<ColumnIdentity, Option<ColumnType>>, SQLError> {
267    SchemaMap::from_produced(
268        entries.into_iter().map(|(identity, ty)| {
269            Ok((
270                identity.clone_with_control(control)?,
271                optional_type(ty, control)?,
272            ))
273        }),
274        control,
275    )
276}
277
278#[cfg(test)]
279mod tests;