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<PresenceBindings>>);
14
15#[derive(Debug, Default, Clone, PartialEq, Eq)]
16struct PresenceBindings {
17    bindings: SchemaMap<Box<str>, InternalColumnRef>,
18    _memory: super::production::lease::SchemaMemory,
19}
20
21impl std::ops::Deref for PresenceBindings {
22    type Target = SchemaMap<Box<str>, InternalColumnRef>;
23    fn deref(&self) -> &Self::Target {
24        &self.bindings
25    }
26}
27
28impl std::ops::DerefMut for PresenceBindings {
29    fn deref_mut(&mut self) -> &mut Self::Target {
30        &mut self.bindings
31    }
32}
33
34mod production;
35
36impl RelationPresence {
37    fn insert(&mut self, qualifier: &str, marker: InternalColumnRef) {
38        let bindings = self
39            .0
40            .get_or_insert_with(|| Arc::new(PresenceBindings::default()));
41        Arc::make_mut(bindings).insert(qualifier.into(), marker);
42    }
43
44    pub(super) fn retaining(&self, keep: impl Fn(InternalColumnRef) -> bool) -> Self {
45        let Some(bindings) = &self.0 else {
46            return Self::default();
47        };
48        if bindings.values().all(|marker| keep(*marker)) {
49            return self.clone();
50        }
51        let retained: SchemaMap<_, _> = bindings
52            .iter()
53            .filter(|(_, marker)| keep(**marker))
54            .map(|(qualifier, marker)| (qualifier.clone(), *marker))
55            .collect();
56        Self((!retained.is_empty()).then(|| {
57            Arc::new(PresenceBindings {
58                bindings: retained,
59                ..PresenceBindings::default()
60            })
61        }))
62    }
63
64    pub(super) fn joined(left: &RowSchema, right: &RowSchema) -> Self {
65        let mut result = Self::default();
66        for (source, other) in [(left, right), (right, left)] {
67            for (qualifier, marker) in source.whole_row_presences() {
68                if !other.has_qualifier(qualifier) {
69                    result.insert(qualifier, marker);
70                }
71            }
72        }
73        result
74    }
75
76    pub(super) fn with_outer(input: &RowSchema, outer: &RowSchema) -> Self {
77        let mut result = input.index.cold.row_presence.clone();
78        for (qualifier, marker) in outer.whole_row_presences() {
79            if !input.has_qualifier(qualifier) {
80                result.insert(qualifier, marker);
81            }
82        }
83        result
84    }
85}
86
87impl RowSchema {
88    pub(super) fn relayout_presence_slot(
89        &self,
90        target: &Self,
91        column: InternalColumnRef,
92    ) -> Option<usize> {
93        target
94            .whole_row_presences()
95            .find_map(|(qualifier, marker)| {
96                (marker == column)
97                    .then(|| self.whole_row_presence(qualifier))
98                    .flatten()
99                    .and_then(|marker| self.internal_slot(marker))
100            })
101    }
102
103    /// The Boolean executor attribute which distinguishes an existing relation row from its NULL extension. An unmarked relation is always present in this scope.
104    pub fn whole_row_presence(&self, qualifier: &str) -> Option<InternalColumnRef> {
105        self.index
106            .cold
107            .row_presence
108            .0
109            .as_ref()?
110            .get(qualifier)
111            .copied()
112    }
113
114    /// Presence bindings share the ordinary internal-attribute layout and have no SQL column names.
115    pub fn whole_row_presences(&self) -> impl Iterator<Item = (&str, InternalColumnRef)> {
116        self.index.cold.row_presence.0.iter().flat_map(|bindings| {
117            bindings
118                .iter()
119                .map(|(qualifier, marker)| (qualifier.as_ref(), *marker))
120        })
121    }
122
123    /// 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.
124    pub fn with_nullable_relations(&self, marker: InternalColumnRef) -> Option<Self> {
125        self.with_nullable_relations_with_control(
126            marker,
127            &uqa_core::memory::ProductionControl::uncontrolled(),
128        )
129        .expect("ordinary nullable relation layout")
130    }
131
132    /// Restore validated presence bindings after a physical layout is decoded. The marker must be a real Boolean internal attribute; duplicate namespaces are malformed input.
133    pub fn with_whole_row_presences(
134        mut self,
135        bindings: impl IntoIterator<Item = (String, InternalColumnRef)>,
136    ) -> SchemaLayoutResult<Self> {
137        let mut presence = RelationPresence::default();
138        for (qualifier, marker) in bindings {
139            if self.internal_slot(marker).is_none()
140                || self.internal_type(marker) != Some(&ColumnType::Boolean)
141            {
142                return Err(SchemaLayoutError(
143                    "whole-row presence requires a Boolean internal attribute".into(),
144                ));
145            }
146            if presence
147                .0
148                .as_ref()
149                .is_some_and(|bindings| bindings.contains_key(qualifier.as_str()))
150            {
151                return Err(SchemaLayoutError(format!(
152                    "duplicate whole-row presence qualifier `{qualifier}`"
153                )));
154            }
155            presence.insert(&qualifier, marker);
156        }
157        Arc::make_mut(&mut self.index).cold.row_presence = presence;
158        Ok(self)
159    }
160}
161
162#[cfg(test)]
163mod tests;