Skip to main content

uqa_sql/schema/
relation_presence.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Whole-row NULL identity is independent of the values of its fields.
8
9use super::{Arc, ColumnType, RowSchema, SchemaLayoutError, SchemaLayoutResult, SchemaMap};
10use crate::ast::InternalColumnRef;
11
12#[derive(Debug, Default, Clone, PartialEq, Eq)]
13pub(super) struct RelationPresence(Option<Arc<SchemaMap<Box<str>, InternalColumnRef>>>);
14
15impl RelationPresence {
16    fn insert(&mut self, qualifier: &str, marker: InternalColumnRef) {
17        let bindings = self.0.get_or_insert_with(|| Arc::new(SchemaMap::default()));
18        Arc::make_mut(bindings).insert(qualifier.into(), marker);
19    }
20
21    pub(super) fn retaining(&self, keep: impl Fn(InternalColumnRef) -> bool) -> Self {
22        let Some(bindings) = &self.0 else {
23            return Self::default();
24        };
25        if bindings.values().all(|marker| keep(*marker)) {
26            return self.clone();
27        }
28        let retained: SchemaMap<_, _> = bindings
29            .iter()
30            .filter(|(_, marker)| keep(**marker))
31            .map(|(qualifier, marker)| (qualifier.clone(), *marker))
32            .collect();
33        Self((!retained.is_empty()).then(|| Arc::new(retained)))
34    }
35
36    pub(super) fn joined(left: &RowSchema, right: &RowSchema) -> Self {
37        let mut result = Self::default();
38        for (source, other) in [(left, right), (right, left)] {
39            for (qualifier, marker) in source.whole_row_presences() {
40                if !other.has_qualifier(qualifier) {
41                    result.insert(qualifier, marker);
42                }
43            }
44        }
45        result
46    }
47
48    pub(super) fn with_outer(input: &RowSchema, outer: &RowSchema) -> Self {
49        let mut result = input.index.cold.row_presence.clone();
50        for (qualifier, marker) in outer.whole_row_presences() {
51            if !input.has_qualifier(qualifier) {
52                result.insert(qualifier, marker);
53            }
54        }
55        result
56    }
57}
58
59impl RowSchema {
60    pub(super) fn relayout_presence_slot(
61        &self,
62        target: &Self,
63        column: InternalColumnRef,
64    ) -> Option<usize> {
65        target
66            .whole_row_presences()
67            .find_map(|(qualifier, marker)| {
68                (marker == column)
69                    .then(|| self.whole_row_presence(qualifier))
70                    .flatten()
71                    .and_then(|marker| self.internal_slot(marker))
72            })
73    }
74
75    /// The Boolean executor attribute which distinguishes an existing relation row from its NULL extension. An unmarked relation is always present in this scope.
76    pub fn whole_row_presence(&self, qualifier: &str) -> Option<InternalColumnRef> {
77        self.index
78            .cold
79            .row_presence
80            .0
81            .as_ref()?
82            .get(qualifier)
83            .copied()
84    }
85
86    /// Presence bindings share the ordinary internal-attribute layout and have no SQL column names.
87    pub fn whole_row_presences(&self) -> impl Iterator<Item = (&str, InternalColumnRef)> {
88        self.index.cold.row_presence.0.iter().flat_map(|bindings| {
89            bindings
90                .iter()
91                .map(|(qualifier, marker)| (qualifier.as_ref(), *marker))
92        })
93    }
94
95    /// Add one physical marker for the input's still-unmarked relation scopes. Existing inner-join NULL identities keep their original markers. The caller appends TRUE to produced rows; ordinary outer-join NULL extension clears the marker along with the fields.
96    pub fn with_nullable_relations(&self, marker: InternalColumnRef) -> Option<Self> {
97        let mut qualifiers = self
98            .relation_qualifiers()
99            .filter(|qualifier| self.whole_row_presence(qualifier).is_none())
100            .peekable();
101        qualifiers.peek()?;
102        let mut result = Self::append_internal_typed(self, &[(marker, Some(ColumnType::Boolean))]);
103        let presence = &mut Arc::make_mut(&mut result.index).cold.row_presence;
104        for qualifier in qualifiers {
105            presence.insert(qualifier, marker);
106        }
107        Some(result)
108    }
109
110    /// Restore validated presence bindings after a physical layout is decoded. The marker must be a real Boolean internal attribute; duplicate namespaces are malformed input.
111    pub fn with_whole_row_presences(
112        mut self,
113        bindings: impl IntoIterator<Item = (String, InternalColumnRef)>,
114    ) -> SchemaLayoutResult<Self> {
115        let mut presence = RelationPresence::default();
116        for (qualifier, marker) in bindings {
117            if self.internal_slot(marker).is_none()
118                || self.internal_type(marker) != Some(&ColumnType::Boolean)
119            {
120                return Err(SchemaLayoutError(
121                    "whole-row presence requires a Boolean internal attribute".into(),
122                ));
123            }
124            if presence
125                .0
126                .as_ref()
127                .is_some_and(|bindings| bindings.contains_key(qualifier.as_str()))
128            {
129                return Err(SchemaLayoutError(format!(
130                    "duplicate whole-row presence qualifier `{qualifier}`"
131                )));
132            }
133            presence.insert(&qualifier, marker);
134        }
135        Arc::make_mut(&mut self.index).cold.row_presence = presence;
136        Ok(self)
137    }
138}
139
140#[cfg(test)]
141mod tests;