Skip to main content

uqa_sql/semantics/
membership.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Membership operands shared by access selection, cardinality and key reads.
8
9use crate::{ast::FunctionDispatch, ScalarExpr};
10use uqa_core::Value;
11
12/// An equality set or its SQL three-valued negation. The operands still require the consumer's ordinary safety and constant checks.
13pub struct MembershipOperands<'a> {
14    pub value: &'a ScalarExpr,
15    pub items: MembershipItems<'a>,
16    pub negated: bool,
17}
18
19/// Analyzed expressions or the borrowed resident values left after constant array folding.
20#[derive(Clone, Copy)]
21pub enum MembershipItems<'a> {
22    Expressions(&'a [ScalarExpr]),
23    Constants(&'a [Value]),
24}
25
26pub enum MembershipItem<'a> {
27    Expression(&'a ScalarExpr),
28    Constant(&'a Value),
29}
30
31impl<'a> MembershipItems<'a> {
32    #[must_use]
33    pub fn len(self) -> usize {
34        match self {
35            Self::Expressions(items) => items.len(),
36            Self::Constants(items) => items.len(),
37        }
38    }
39
40    #[must_use]
41    pub fn is_empty(self) -> bool {
42        self.len() == 0
43    }
44
45    pub fn iter(self) -> impl Iterator<Item = MembershipItem<'a>> {
46        let (expressions, constants): (&[ScalarExpr], &[Value]) = match self {
47            Self::Expressions(items) => (items, &[]),
48            Self::Constants(items) => (&[], items),
49        };
50        expressions
51            .iter()
52            .map(MembershipItem::Expression)
53            .chain(constants.iter().map(MembershipItem::Constant))
54    }
55}
56
57/// Borrow an IN list or its analyzed scalar-array comparison without dropping conversions. Empty ALL arrays stay scalar because they also accept a NULL left operand.
58#[must_use]
59pub fn membership_operands(expression: &ScalarExpr) -> Option<MembershipOperands<'_>> {
60    match expression {
61        ScalarExpr::InList {
62            expr,
63            list,
64            negated,
65        } => Some(MembershipOperands {
66            value: expr,
67            items: MembershipItems::Expressions(list),
68            negated: *negated,
69        }),
70        ScalarExpr::Func {
71            binding: Some(binding),
72            args,
73            ..
74        } => {
75            let [value, array, ScalarExpr::Literal(Value::Str(operator))] = args.as_slice() else {
76                return None;
77            };
78            let items = match array {
79                ScalarExpr::Array(items) => MembershipItems::Expressions(items),
80                ScalarExpr::Literal(Value::Array(array))
81                | ScalarExpr::TypedLiteral {
82                    value: Value::Array(array),
83                    ..
84                } if array.dimensions().len() <= 1 => MembershipItems::Constants(array.elements()),
85                ScalarExpr::RetainedLiteral(literal) => {
86                    let Some(Value::Array(array)) = literal.value.resident_value() else {
87                        return None;
88                    };
89                    if array.dimensions().len() > 1 {
90                        return None;
91                    }
92                    MembershipItems::Constants(array.elements())
93                }
94                _ => return None,
95            };
96            let negated = match (binding.dispatch, operator.as_str()) {
97                (Some(FunctionDispatch::AnyOperator), "=") => false,
98                (Some(FunctionDispatch::AllOperator), "<>") if !items.is_empty() => true,
99                _ => return None,
100            };
101            Some(MembershipOperands {
102                value,
103                items,
104                negated,
105            })
106        }
107        _ => None,
108    }
109}
110
111#[cfg(test)]
112mod tests;
113
114/// Query-local columns participate in IN-list partitioning and window placement; an enclosing query's columns do not. A declared schema without physical scopes treats every column as local.
115pub(crate) fn references_current_row(
116    expression: &ScalarExpr,
117    schema: Option<&crate::RowSchema>,
118) -> bool {
119    let mut found = false;
120    expression.visit(&mut |node| {
121        found |= match node {
122            ScalarExpr::Column(column) => {
123                schema.is_none_or(|schema| schema.resolves_local_column(None, column))
124            }
125            ScalarExpr::QualifiedColumn { qualifier, column } => {
126                schema.is_none_or(|schema| schema.resolves_local_column(Some(qualifier), column))
127            }
128            ScalarExpr::Position(position) => schema.is_none_or(|schema| {
129                schema
130                    .slot(*position)
131                    .is_some_and(|slot| schema.slot_is_local(slot))
132            }),
133            ScalarExpr::InternalColumn(column) => schema.is_none_or(|schema| {
134                schema
135                    .internal_slot(*column)
136                    .is_some_and(|slot| schema.slot_is_local(slot))
137            }),
138            ScalarExpr::QualifiedStar(qualifier) => schema.is_none_or(|schema| {
139                schema
140                    .identities()
141                    .iter()
142                    .any(|identity| identity.qualifier() == Some(qualifier.as_str()))
143            }),
144            _ => false,
145        };
146    });
147    found
148}