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