Skip to main content

uqa_execution/scalar/
state.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Function state belongs to immutable expressions prepared for one execution.
8
9use std::sync::OnceLock;
10
11use crate::RowSchema;
12
13use uqa_core::{memory::Produced, Value};
14use uqa_sql::{
15    ast::{BinaryOp, FunctionBinding, FunctionDispatch},
16    expr::enums::EnumComparisonState,
17    ScalarExpr,
18};
19
20#[cfg(test)]
21thread_local! {
22    static COMPARISON_LOOKUPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
23    pub(super) static CAST_TYPE_RESOLUTIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
24    pub(super) static COLUMN_NAME_LOOKUPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
25}
26
27/// The first conversion of a cast whose operand is a literal.
28#[derive(Debug)]
29pub(crate) enum ConstantCast {
30    /// An immutable conversion, which every later evaluation copies.
31    Retained(Value),
32    /// The conversion reads a catalog descriptor, a session setting or a type outside the builtin scalars, so every evaluation converts again.
33    PerEvaluation,
34}
35
36/// Catalog-free source inference is retained for the same immutable execution schema. Explicit builtin conversions can also retain their descriptor; other casts resolve their source and target names against the invoking catalog on every evaluation.
37#[derive(Debug)]
38pub(crate) enum RowCast {
39    Resolved {
40        conversion: uqa_sql::expr::ResolvedCast,
41        source: Produced<String>,
42        schema: Option<RowSchema>,
43    },
44    Source {
45        source: Option<Produced<String>>,
46        schema: Option<RowSchema>,
47    },
48}
49
50/// A fixed numeric overload tied to the immutable schema that selected it.
51#[derive(Debug)]
52pub(crate) enum NumericCall {
53    Resolved {
54        operation: uqa_sql::expr::ResolvedNumericOperator,
55        schema: Option<RowSchema>,
56    },
57    PerEvaluation,
58}
59
60/// The context schema the resolution of a column reference depended on.
61#[derive(Debug)]
62pub(crate) enum ContextSchema {
63    /// A qualified reference never consults the context schema.
64    Unused,
65    /// The context carried no schema.
66    Absent,
67    /// The context carried this schema, which decided between a column and a whole-row reference.
68    Shared(RowSchema),
69}
70
71/// The key a column reference reads once the schema of its rows is known.
72#[derive(Debug)]
73pub(crate) struct ColumnSlot {
74    pub(crate) context_schema: ContextSchema,
75    /// The schema the rows resolved the reference through. Retaining it keeps the index alive, so a later schema can never reuse its address.
76    pub(crate) row_schema: RowSchema,
77    /// The space of `key`: rows of the same schema read through a lookup of another space resolve the name again.
78    pub(crate) key_space: uqa_sql::expr::RowKeySpace,
79    /// The row lookup's key for the reference, or `None` for a name the rows do not carry.
80    pub(crate) key: Option<usize>,
81}
82
83/// Read-only lookup into the function state owned by a prepared expression set.
84/// The state has one fixed-size entry per logical ordering comparison, numeric operator, literal/row cast or column reference, never per input row.
85#[derive(Debug, Default)]
86pub struct FunctionCallStates {
87    enums: Vec<((usize, u8), EnumComparisonState)>,
88    constant_casts: Vec<(usize, OnceLock<ConstantCast>)>,
89    columns: Vec<(usize, OnceLock<ColumnSlot>)>,
90    row_casts: Vec<(usize, OnceLock<RowCast>)>,
91    numeric_operators: Vec<(usize, OnceLock<NumericCall>)>,
92}
93
94impl FunctionCallStates {
95    fn register(&mut self, expression: &ScalarExpr) {
96        let first_row_cast = self.row_casts.len();
97        let first_numeric = self.numeric_operators.len();
98        let mut parameter_dependent = false;
99        expression.visit(&mut |expression| match expression {
100            ScalarExpr::Func { name, binding, args, .. } => {
101                self.add(args.as_ptr() as usize, function_slots(name, binding.as_ref(), args));
102                if binding.as_ref().is_some_and(|binding| binding.builtin
103                    && matches!(binding.dispatch, Some(FunctionDispatch::NumericOperator(operator)) if args.len() == operator.arity())) {
104                    self.numeric_operators.push((args.as_ptr() as usize, OnceLock::new()));
105                }
106            }
107            ScalarExpr::Binary {
108                op: BinaryOp::Less | BinaryOp::LessEqual | BinaryOp::Greater | BinaryOp::GreaterEqual,
109                lhs, ..
110            } => self.add(std::ptr::from_ref(lhs.as_ref()) as usize, 1),
111            ScalarExpr::Between { low, high, .. } => {
112                self.add(std::ptr::from_ref(low.as_ref()) as usize, 1);
113                self.add(std::ptr::from_ref(high.as_ref()) as usize, 1);
114            }
115            ScalarExpr::Cast { expr, .. }
116                if matches!(expr.as_ref(), ScalarExpr::Literal(_) | ScalarExpr::TypedLiteral { .. }) =>
117            {
118                self.constant_casts
119                    .push((std::ptr::from_ref(expr.as_ref()) as usize, OnceLock::new()));
120            }
121            ScalarExpr::Cast { expr, .. } => {
122                self.row_casts.push((std::ptr::from_ref(expr.as_ref()) as usize, OnceLock::new()));
123            }
124            ScalarExpr::Param(_) => parameter_dependent = true,
125            ScalarExpr::Column(_) | ScalarExpr::QualifiedColumn { .. } => {
126                self.columns
127                    .push((std::ptr::from_ref(expression) as usize, OnceLock::new()));
128            }
129            _ => {},
130        });
131        // One traversal per root avoids rescanning every nested cast's subtree. Parameter-dependent roots keep live inference without disabling independent roots.
132        if parameter_dependent {
133            self.row_casts.truncate(first_row_cast);
134            self.numeric_operators.truncate(first_numeric);
135        }
136    }
137
138    fn is_empty(&self) -> bool {
139        self.enums.is_empty()
140            && self.constant_casts.is_empty()
141            && self.columns.is_empty()
142            && self.row_casts.is_empty()
143            && self.numeric_operators.is_empty()
144    }
145
146    /// The retained key of the column reference `expression`.
147    pub(crate) fn column_slot(&self, expression: &ScalarExpr) -> Option<&OnceLock<ColumnSlot>> {
148        let address = std::ptr::from_ref(expression) as usize;
149        self.columns
150            .binary_search_by_key(&address, |(key, _)| *key)
151            .ok()
152            .map(|index| &self.columns[index].1)
153    }
154
155    /// The retained first conversion of the cast whose literal operand is `operand`.
156    pub(crate) fn constant_cast(&self, operand: &ScalarExpr) -> Option<&OnceLock<ConstantCast>> {
157        let address = std::ptr::from_ref(operand) as usize;
158        self.constant_casts
159            .binary_search_by_key(&address, |(key, _)| *key)
160            .ok()
161            .map(|index| &self.constant_casts[index].1)
162    }
163
164    pub(crate) fn row_cast(&self, operand: &ScalarExpr) -> Option<&OnceLock<RowCast>> {
165        let address = std::ptr::from_ref(operand) as usize;
166        self.row_casts
167            .binary_search_by_key(&address, |(key, _)| *key)
168            .ok()
169            .map(|index| &self.row_casts[index].1)
170    }
171
172    pub(crate) fn numeric_operator(
173        &self,
174        arguments: &[ScalarExpr],
175    ) -> Option<&OnceLock<NumericCall>> {
176        let address = arguments.as_ptr() as usize;
177        self.numeric_operators
178            .binary_search_by_key(&address, |(key, _)| *key)
179            .ok()
180            .map(|index| &self.numeric_operators[index].1)
181    }
182
183    fn add(&mut self, address: usize, slots: u8) {
184        for slot in 0..slots {
185            self.enums
186                .push(((address, slot), EnumComparisonState::default()));
187        }
188    }
189
190    pub(crate) fn enum_comparisons(
191        &self,
192        arguments: &[ScalarExpr],
193    ) -> [Option<&EnumComparisonState>; 4] {
194        let address = arguments.as_ptr() as usize;
195        let Ok(first) = self
196            .enums
197            .binary_search_by_key(&(address, 0), |(key, _)| *key)
198        else {
199            return [None; 4];
200        };
201        std::array::from_fn(|slot| {
202            self.enums
203                .get(first + slot)
204                .filter(|(key, _)| *key == (address, slot as u8))
205                .map(|(_, state)| state)
206        })
207    }
208
209    pub(crate) fn enum_binary_comparison(&self, left: &ScalarExpr) -> Option<&EnumComparisonState> {
210        #[cfg(test)]
211        COMPARISON_LOOKUPS.with(|count| count.set(count.get() + 1));
212        self.enums
213            .binary_search_by_key(&(std::ptr::from_ref(left) as usize, 0), |(key, _)| *key)
214            .ok()
215            .map(|index| &self.enums[index].1)
216    }
217}
218
219fn function_slots(name: &str, binding: Option<&FunctionBinding>, args: &[ScalarExpr]) -> u8 {
220    if binding.is_some_and(|binding| !binding.builtin) {
221        return 0;
222    }
223    match binding.and_then(|binding| binding.dispatch) {
224        Some(FunctionDispatch::Enum { operation, .. }) => {
225            u8::from(args.len() == 2 && operation.uses_comparison_state())
226        }
227        Some(FunctionDispatch::AnyOperator | FunctionDispatch::AllOperator) => u8::from(
228            args.len() == 3
229                && matches!(args.last(),
230                Some(ScalarExpr::Literal(uqa_core::Value::Str(op)))
231                    if matches!(op.as_str(), "<" | "<=" | ">" | ">=")),
232        ),
233        Some(FunctionDispatch::BetweenSymmetric) if args.len() == 3 => 4,
234        None => u8::from(
235            args.len() >= 2
236                && (name.eq_ignore_ascii_case("greatest") || name.eq_ignore_ascii_case("least")),
237        ),
238        _ => 0,
239    }
240}
241
242type VisitRoots<T> = fn(&T, &mut dyn FnMut(&ScalarExpr));
243
244/// Retains both the immutable source and its call state. Argument vectors and
245/// comparison operands are heap allocations, so their identity survives moves. They cannot
246/// be changed or freed while the state is usable; addresses are only lookup keys
247/// and are never dereferenced. Cloning prepares independent, initially empty state.
248pub(crate) struct PreparedExpressions<T> {
249    expressions: T,
250    calls: Option<Box<PreparedCallStates<T>>>,
251}
252
253struct PreparedCallStates<T> {
254    calls: FunctionCallStates,
255    visit_roots: VisitRoots<T>,
256}
257
258static EMPTY_CALL_STATES: FunctionCallStates = FunctionCallStates {
259    enums: Vec::new(),
260    constant_casts: Vec::new(),
261    columns: Vec::new(),
262    row_casts: Vec::new(),
263    numeric_operators: Vec::new(),
264};
265
266impl<T> PreparedExpressions<T> {
267    pub(crate) fn new(expressions: T, visit_roots: VisitRoots<T>) -> Self {
268        let mut calls = FunctionCallStates::default();
269        visit_roots(&expressions, &mut |expression| calls.register(expression));
270        calls.enums.sort_unstable_by_key(|(address, _)| *address);
271        calls.enums.dedup_by_key(|(address, _)| *address);
272        calls
273            .constant_casts
274            .sort_unstable_by_key(|(address, _)| *address);
275        calls.constant_casts.dedup_by_key(|(address, _)| *address);
276        calls.columns.sort_unstable_by_key(|(address, _)| *address);
277        calls.columns.dedup_by_key(|(address, _)| *address);
278        calls
279            .row_casts
280            .sort_unstable_by_key(|(address, _)| *address);
281        calls.row_casts.dedup_by_key(|(address, _)| *address);
282        calls
283            .numeric_operators
284            .sort_unstable_by_key(|(address, _)| *address);
285        calls
286            .numeric_operators
287            .dedup_by_key(|(address, _)| *address);
288        Self {
289            expressions,
290            calls: (!calls.is_empty()).then(|| Box::new(PreparedCallStates { calls, visit_roots })),
291        }
292    }
293
294    pub(crate) fn calls(&self) -> &FunctionCallStates {
295        self.calls
296            .as_ref()
297            .map_or(&EMPTY_CALL_STATES, |calls| &calls.calls)
298    }
299}
300
301impl PreparedExpressions<ScalarExpr> {
302    pub(crate) fn scalar(expression: ScalarExpr) -> Self {
303        Self::new(expression, |expression, visit| visit(expression))
304    }
305}
306
307impl PreparedExpressions<Vec<ScalarExpr>> {
308    pub(crate) fn scalars(expressions: Vec<ScalarExpr>) -> Self {
309        Self::new(expressions, |expressions, visit| {
310            expressions.iter().for_each(visit);
311        })
312    }
313}
314
315impl PreparedExpressions<Vec<crate::SortKey>> {
316    pub(crate) fn sort_keys(keys: Vec<crate::SortKey>) -> Self {
317        Self::new(keys, |keys, visit| {
318            for key in keys {
319                visit(&key.expr);
320            }
321        })
322    }
323}
324
325impl<T> std::ops::Deref for PreparedExpressions<T> {
326    type Target = T;
327
328    fn deref(&self) -> &T {
329        &self.expressions
330    }
331}
332
333impl<T: Clone> Clone for PreparedExpressions<T> {
334    fn clone(&self) -> Self {
335        match self.calls.as_ref() {
336            Some(calls) => Self::new(self.expressions.clone(), calls.visit_roots),
337            None => Self {
338                expressions: self.expressions.clone(),
339                calls: None,
340            },
341        }
342    }
343}
344
345#[cfg(test)]
346mod tests;