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