Skip to main content

uqa_sql/schema/
mod.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! SQL column identities, declared types, and logical slot layouts.
8
9use crate::ast::{ColumnType, InternalColumnRef};
10use std::collections::{HashMap, HashSet};
11
12/// Lookup maps keyed by column names and identities. Name binding constructs and probes these maps for every column of every bound schema, so they hash with `ahash` instead of the standard library's `SipHash` default.
13pub(crate) use lookup_map::SchemaMap;
14pub(crate) use lookup_set::SchemaSet;
15use std::sync::Arc;
16
17mod collations;
18mod identity_lookup;
19mod input_slots;
20mod lateral;
21mod lookup_map;
22mod lookup_set;
23mod name_binding;
24mod open_columns;
25mod outer_scope;
26mod production;
27mod record_fields;
28mod relation_presence;
29mod relation_types;
30mod result_columns;
31mod schema_composition;
32mod schema_construction;
33mod schema_layout;
34mod schema_projection;
35mod schema_remap;
36pub use collations::CollationBinding;
37use collations::Collations;
38pub use input_slots::InputSlots;
39pub use record_fields::RecordFields;
40pub(crate) use record_fields::{RecordDescriptor, RecordFieldMetadata, RecordMetadata};
41
42const NULL_SLOT: usize = usize::MAX;
43
44/// Invalid schema layout supplied by a planner or a persisted row layout.
45#[derive(Debug, thiserror::Error)]
46#[error("{0}")]
47pub struct SchemaLayoutError(pub String);
48
49type SchemaLayoutResult<T> = Result<T, SchemaLayoutError>;
50
51/// Structured SQL column identity. A qualifier is metadata, never a prefix encoded into the column name, so quoted names containing `.` remain intact.
52#[derive(
53    Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
54)]
55pub struct ColumnIdentity {
56    qualifier: Option<Box<str>>,
57    column: Box<str>,
58}
59
60/// One score-bearing relation carried through the executor under an opaque internal attribute. The optional qualifier is SQL namespace metadata; the score value itself is never addressed by a magic SQL column name.
61#[derive(Debug, Clone, PartialEq, Eq)]
62struct ScoreSource {
63    qualifier: Option<Box<str>>,
64    column: InternalColumnRef,
65}
66
67impl ColumnIdentity {
68    #[must_use]
69    pub fn unqualified(column: impl Into<String>) -> Self {
70        Self {
71            qualifier: None,
72            column: Box::<str>::from(column.into()),
73        }
74    }
75
76    #[must_use]
77    pub fn qualified(qualifier: impl Into<String>, column: impl Into<String>) -> Self {
78        Self {
79            qualifier: Some(Box::<str>::from(qualifier.into())),
80            column: Box::<str>::from(column.into()),
81        }
82    }
83
84    #[must_use]
85    pub fn qualifier(&self) -> Option<&str> {
86        self.qualifier.as_deref()
87    }
88
89    #[must_use]
90    pub fn column(&self) -> &str {
91        &self.column
92    }
93}
94
95#[derive(Debug, Clone, PartialEq, Eq)]
96struct SchemaIndex {
97    /// Public/materialized output labels in logical order.
98    columns: Box<[String]>,
99    /// SQL lookup identities aligned with `columns`.
100    identities: Box<[ColumnIdentity]>,
101    /// Logical column position -> flattened physical value position.
102    slots: Box<[usize]>,
103    physical_width: usize,
104    /// Structural lookup by physical/public label. SQL name binding uses `unqualified` or `qualified`, never this map.
105    exact: SchemaMap<Box<str>, usize>,
106    unqualified: SchemaMap<Box<str>, usize>,
107    qualified: SchemaMap<ColumnIdentity, usize>,
108    /// Additional lookup identities that point directly at an existing physical slot without becoming output columns. Correlated table aliases use this to expose `(alias, column)` without duplicating the value.
109    aliases: SchemaMap<ColumnIdentity, usize>,
110    /// Executor-only relation/attribute identities mapped directly to physical
111    /// slots. These never participate in SQL name lookup or wildcard output.
112    executor_attributes: SchemaMap<InternalColumnRef, usize>,
113    /// Visible unqualified names with more than one logical owner.
114    ambiguous_unqualified: SchemaSet<Box<str>>,
115    /// Visible qualified identities with more than one logical owner.
116    ambiguous_qualified: SchemaSet<ColumnIdentity>,
117    /// Static type metadata stays behind a cold pointer so declared SQL identities do not enlarge or displace the cache-hot row lookup fields above.
118    cold: Box<SchemaColdMetadata>,
119    _memory: production::lease::SchemaMemory,
120}
121
122#[derive(Debug, Clone, PartialEq, Eq)]
123struct SchemaColdMetadata {
124    collations: Collations,
125    row_types: relation_types::RelationRowTypes,
126    row_presence: relation_presence::RelationPresence,
127    record_fields: SchemaMap<usize, RecordMetadata>,
128    /// `None` is an as-yet unresolved type, not a runtime NULL value.
129    columns: Box<[Option<ColumnType>]>,
130    aliases: SchemaMap<ColumnIdentity, Option<ColumnType>>,
131    executor_attribute_types: SchemaMap<InternalColumnRef, Option<ColumnType>>,
132    score_sources: Vec<ScoreSource>,
133    /// Logical attributes omitted from unqualified and qualified wildcard
134    /// expansion. Explicit references and projections remain ordinary SQL
135    /// columns; only the source-owned metadata positions are hidden.
136    wildcard_hidden: SchemaSet<usize>,
137    /// Static name-binding identities with no runtime slot. Unlike aliases,
138    /// these are never part of qualified wildcard expansion or spill layout.
139    binding_only: SchemaMap<ColumnIdentity, Option<ColumnType>>,
140    /// Names supplied only when a document or native-function source opens.
141    open_qualifiers: SchemaSet<Option<Box<str>>>,
142    identity_layout: bool,
143    /// The physical width of the schema's own columns when [`RowSchema::with_outer_schema`] overlaid an enclosing query's columns after them; `None` when every column is the schema's own.
144    local_width: Option<usize>,
145    lateral_restrictions: Option<Arc<lateral::LateralRestrictions>>,
146}
147
148#[derive(Default)]
149struct SchemaBuildMetadata {
150    collations: Collations,
151    row_types: relation_types::RelationRowTypes,
152    row_presence: relation_presence::RelationPresence,
153    record_fields: SchemaMap<usize, RecordMetadata>,
154    aliases: SchemaMap<ColumnIdentity, usize>,
155    alias_types: SchemaMap<ColumnIdentity, Option<ColumnType>>,
156    internal: SchemaMap<InternalColumnRef, usize>,
157    internal_types: SchemaMap<InternalColumnRef, Option<ColumnType>>,
158    score_sources: Vec<ScoreSource>,
159    wildcard_hidden: SchemaSet<usize>,
160    binding_only: SchemaMap<ColumnIdentity, Option<ColumnType>>,
161    open_qualifiers: SchemaSet<Option<Box<str>>>,
162    exact_unqualified_precedence: bool,
163    extra_ambiguous_unqualified: SchemaSet<Box<str>>,
164    extra_ambiguous_qualified: SchemaSet<ColumnIdentity>,
165    local_width: Option<usize>,
166    lateral_restrictions: Option<Arc<lateral::LateralRestrictions>>,
167    memory: production::lease::SchemaMemory,
168}
169
170pub struct PhysicalLayout {
171    pub columns: Vec<String>,
172    pub identities: Vec<ColumnIdentity>,
173    pub types: Vec<Option<ColumnType>>,
174    pub slots: Vec<Option<usize>>,
175    pub physical_width: usize,
176    pub aliases: Vec<(ColumnIdentity, Option<usize>, Option<ColumnType>)>,
177    pub internal: Vec<(InternalColumnRef, Option<usize>, Option<ColumnType>)>,
178    pub score_sources: Vec<(Option<String>, InternalColumnRef)>,
179    pub wildcard_hidden: HashSet<usize>,
180}
181
182/// Immutable column layout shared by an operator and all of its batches.
183///
184/// `columns` are the logical output labels. `slots` may point into a wider
185/// composite physical row after a projection/rename, allowing those operators
186/// to change row shape without moving any values.
187#[derive(Debug, Clone, PartialEq, Eq)]
188pub struct RowSchema {
189    index: Arc<SchemaIndex>,
190}
191
192/// Physical source of one scalar-projection output. Direct input slots stay in the child row; only computed values extend its physical layout.
193#[derive(Debug, Clone, Copy, PartialEq, Eq)]
194pub enum ProjectedSlot {
195    Input(Option<usize>),
196    /// A SQL binding supplies its own collation even when another logical column shares this physical slot or the slot is NULL.
197    BoundInput {
198        physical: Option<usize>,
199        collation: Option<u32>,
200    },
201    Computed {
202        position: usize,
203        collation: Option<u32>,
204    },
205}
206
207impl RowSchema {
208    /// Logical-to-physical slots; usize::MAX denotes a NULL slot.
209    #[doc(hidden)]
210    pub fn layout_slots(&self) -> &[usize] {
211        &self.index.slots
212    }
213
214    /// Whether `other` is a clone of this schema, sharing the index that defines its names and layout.
215    #[must_use]
216    pub fn shares_index(&self, other: &Self) -> bool {
217        Arc::ptr_eq(&self.index, &other.index)
218    }
219
220    #[doc(hidden)]
221    pub fn is_identity_layout(&self) -> bool {
222        self.index.cold.identity_layout
223    }
224}
225
226pub mod join_output;
227
228mod declarations;
229pub mod expressions;
230pub use declarations::{SchemaBindingContext, SchemaExpressionCatalog};
231pub mod generated;
232pub mod indexes;
233
234pub mod columns;
235pub mod composites;
236pub mod constraints;
237pub mod defaults;
238pub mod domains;
239
240pub mod dependencies;
241
242pub mod check_inheritance;
243
244pub mod table_creation;
245
246pub mod inheritance;
247
248pub mod foreign_keys;
249
250pub mod referenced_partitions;
251
252pub mod sequences;
253
254pub mod constraint_metadata;
255
256pub mod keys;
257
258pub mod constraint_changes;
259
260pub mod constraint_views;
261
262pub mod table_alteration;
263
264pub mod removal;
265
266pub mod namespaces;
267pub mod relation_alteration;
268pub mod view_creation;
269
270pub mod truncate;
271
272pub mod type_objects;
273
274pub mod foreign_servers;
275pub mod foreign_tables;
276pub mod foreign_wrappers;
277
278pub mod retention;
279
280mod type_lookup;
281pub use type_lookup::{ColumnTypeSchema, ScalarTypeSchema};
282
283impl uqa_core::memory::ObserveAllocations for ColumnIdentity {
284    fn observe_allocations<'a>(
285        &'a self,
286        observer: &mut uqa_core::memory::AllocationObserver<'a, '_>,
287    ) -> Result<(), uqa_core::ValueRetentionError> {
288        let Self { qualifier, column } = self;
289        observer.child(qualifier)?;
290        observer.child(column)?;
291        Ok(())
292    }
293}