Skip to main content

uqa_sql/schema/
production.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Schema constructors own admitted names, type payloads, lookup indexes and layout buffers through the final shared row generation.
8
9use super::{ColumnIdentity, ColumnType, RowSchema, SchemaBuildMetadata};
10use crate::{ast::InternalRelationId, SQLError};
11use uqa_core::memory::{Produced, ProductionControl, ProductionVec};
12
13mod canonical;
14mod captured_aliases;
15mod captured_output;
16mod composition;
17pub(super) mod copy;
18mod identity_aliases;
19mod indexes;
20mod internal_aliases;
21mod internal_relations;
22pub(super) mod lease;
23mod parts;
24mod physical_attributes;
25mod projection;
26mod rebinding;
27pub(super) mod remapping;
28mod renaming;
29mod virtual_names;
30mod wildcards;
31
32impl SchemaBuildMetadata {
33    pub(in crate::schema) fn empty_with_control(control: &ProductionControl<'_>) -> Self {
34        Self {
35            memory: lease::SchemaMemory::new(control.empty_reservation()),
36            ..Self::default()
37        }
38    }
39}
40
41impl RowSchema {
42    /// Construct an empty immutable layout with its index and shared headers admitted before allocation.
43    pub fn empty_with_control(control: &ProductionControl<'_>) -> Result<Self, SQLError> {
44        Self::new_with_control(
45            control.finish(Vec::new(), control.empty_reservation())?,
46            control,
47        )
48    }
49
50    /// Consume already admitted column names and construct the immutable positional layout under the same allowance.
51    pub fn new_with_control(
52        columns: Produced<Vec<String>>,
53        control: &ProductionControl<'_>,
54    ) -> Result<Self, SQLError> {
55        control.check()?;
56        let mut identities = ProductionVec::new(*control);
57        let mut types = ProductionVec::new(*control);
58        let mut slots = ProductionVec::new(*control);
59        for (position, column) in columns.iter().enumerate() {
60            identities.push_produced(ColumnIdentity::from_parts_with_control(
61                None, column, control,
62            )?)?;
63            types.push_produced(control.finish(None, control.empty_reservation())?)?;
64            slots.push_copy(position)?;
65        }
66        let width = columns.len();
67        parts::produce(
68            columns,
69            identities.finish()?,
70            types.finish()?,
71            slots.finish()?,
72            width,
73            SchemaBuildMetadata::empty_with_control(control),
74            control,
75        )
76    }
77
78    /// Select borrowed declarations without constructing ordinary names, identities, types or collation maps first.
79    pub fn with_column_metadata_with_control<'a>(
80        qualifier: Option<&str>,
81        columns: impl IntoIterator<Item = (&'a str, Option<&'a ColumnType>, Option<u32>)>,
82        control: &ProductionControl<'_>,
83    ) -> Result<Self, SQLError> {
84        columns_with_control(
85            qualifier,
86            None,
87            columns
88                .into_iter()
89                .map(|(name, ty, oid)| (name, ty, oid, None)),
90            false,
91            control,
92        )
93    }
94
95    /// Publish complete typed output metadata once, before sharing the schema index. Record handles already own their immutable field/descriptor payloads.
96    pub(crate) fn with_output_metadata_with_control<'a>(
97        qualifier: Option<&str>,
98        columns: impl IntoIterator<
99            Item = (
100                &'a str,
101                Option<&'a ColumnType>,
102                Option<u32>,
103                Option<super::RecordMetadata>,
104            ),
105        >,
106        open: bool,
107        control: &ProductionControl<'_>,
108    ) -> Result<Self, SQLError> {
109        columns_with_control(qualifier, None, columns, open, control)
110    }
111
112    /// Produce the visible routine parameter namespace and its matching executor-only identities in one layout. Both refer to the same physical positions and retain the same selected types.
113    pub fn with_parameter_metadata_with_control<'a>(
114        qualifier: &str,
115        relation: InternalRelationId,
116        columns: impl IntoIterator<Item = (&'a str, Option<&'a ColumnType>)>,
117        control: &ProductionControl<'_>,
118    ) -> Result<Self, SQLError> {
119        columns_with_control(
120            Some(qualifier),
121            Some(relation),
122            columns.into_iter().map(|(name, ty)| (name, ty, None, None)),
123            false,
124            control,
125        )
126    }
127}
128
129fn columns_with_control<'a>(
130    qualifier: Option<&str>,
131    internal_relation: Option<InternalRelationId>,
132    columns: impl IntoIterator<
133        Item = (
134            &'a str,
135            Option<&'a ColumnType>,
136            Option<u32>,
137            Option<super::RecordMetadata>,
138        ),
139    >,
140    open: bool,
141    control: &ProductionControl<'_>,
142) -> Result<RowSchema, SQLError> {
143    control.check()?;
144    columns_with_metadata(
145        qualifier,
146        internal_relation,
147        columns,
148        open,
149        SchemaBuildMetadata::empty_with_control(control),
150        control,
151    )
152}
153
154fn columns_with_metadata<'a>(
155    qualifier: Option<&str>,
156    internal_relation: Option<InternalRelationId>,
157    columns: impl IntoIterator<
158        Item = (
159            &'a str,
160            Option<&'a ColumnType>,
161            Option<u32>,
162            Option<super::RecordMetadata>,
163        ),
164    >,
165    open: bool,
166    mut metadata: SchemaBuildMetadata,
167    control: &ProductionControl<'_>,
168) -> Result<RowSchema, SQLError> {
169    control.check()?;
170    let mut names = ProductionVec::new(*control);
171    let mut identities = ProductionVec::new(*control);
172    let mut types = ProductionVec::new(*control);
173    let mut slots = ProductionVec::new(*control);
174    let mut records = ProductionVec::new(*control);
175    for (name, ty, oid, record) in columns {
176        control.check()?;
177        assert!(
178            oid.is_none_or(|oid| oid == 0 || ty.is_some_and(super::composites::type_is_collatable)),
179            "collation requires a collatable column type"
180        );
181        let position = names.len();
182        names.push_produced(control.copy_text(name)?)?;
183        identities.push_produced(ColumnIdentity::from_parts_with_control(
184            qualifier, name, control,
185        )?)?;
186        types.push_produced(optional_type(ty, control)?)?;
187        slots.push_copy(position)?;
188        if let Some(record) = record {
189            records
190                .push_produced(control.finish((position, record), control.empty_reservation())?)?;
191        }
192        metadata
193            .collations
194            .column_with_control(position, oid, ty, control)?;
195    }
196    metadata.record_fields = super::SchemaMap::from_produced(
197        records.iter().map(|(position, record)| {
198            Ok((
199                control.finish(*position, control.empty_reservation())?,
200                control.finish(record.clone(), control.empty_reservation())?,
201            ))
202        }),
203        control,
204    )?;
205    drop(records);
206    if open {
207        metadata.open_qualifiers = super::SchemaSet::from_produced(
208            std::iter::once_with(|| {
209                let (qualifier, memory) = match qualifier {
210                    Some(name) => {
211                        let (name, memory) = lease::boxed_text(name, control)?.into_parts();
212                        (Some(name), memory)
213                    }
214                    None => (None, control.empty_reservation()),
215                };
216                Ok(control.finish(qualifier, memory)?)
217            }),
218            control,
219        )?;
220    }
221    let width = names.len();
222    if let Some(qualifier) = qualifier.filter(|_| width == 0) {
223        metadata.row_types =
224            super::relation_types::RelationRowTypes::anonymous_with_control(qualifier, control)?;
225    }
226    if let Some(relation) = internal_relation {
227        metadata.internal = super::SchemaMap::from_produced(
228            (0..width).map(|position| {
229                Ok((
230                    control.finish(relation.column(position), control.empty_reservation())?,
231                    control.finish(position, control.empty_reservation())?,
232                ))
233            }),
234            control,
235        )?;
236        metadata.internal_types = super::SchemaMap::from_produced(
237            types.iter().enumerate().map(|(position, ty)| {
238                Ok((
239                    control.finish(relation.column(position), control.empty_reservation())?,
240                    optional_type(ty.as_ref(), control)?,
241                ))
242            }),
243            control,
244        )?;
245    }
246    parts::produce(
247        names.finish()?,
248        identities.finish()?,
249        types.finish()?,
250        slots.finish()?,
251        width,
252        metadata,
253        control,
254    )
255}
256
257pub(super) fn optional_type(
258    ty: Option<&ColumnType>,
259    control: &ProductionControl<'_>,
260) -> Result<Produced<Option<ColumnType>>, SQLError> {
261    match ty {
262        Some(ty) => {
263            let (ty, memory) = ty.clone_with_control(control)?.into_parts();
264            Ok(control.finish(Some(ty), memory)?)
265        }
266        None => Ok(control.finish(None, control.empty_reservation())?),
267    }
268}
269
270#[cfg(test)]
271mod tests;