Skip to main content

datafusion_expr/
physical_planning_context.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use std::fmt;
6use std::hash::{Hash, Hasher};
7use std::sync::{Arc, Mutex};
8
9use datafusion_common::{HashMap, Result, ScalarValue, TableReference, internal_err};
10
11/// Context used while converting a logical plan subtree into a physical plan.
12///
13/// Unlike [`ExecutionProps`](crate::execution_props::ExecutionProps), which
14/// applies to the overall planning and execution of a query, this context can
15/// differ between recursively planned subtrees. It currently carries:
16///
17/// * the state needed to create physical expressions for
18///   [`Expr::ScalarSubquery`] nodes that read from a shared
19///   [`ScalarSubqueryResults`] container, and
20/// * the qualifiers assigned to the [`Expr::LambdaVariable`]s that are in scope.
21///
22/// The physical planner builds this context from the set of uncorrelated scalar
23/// subqueries it has scheduled for a subtree. It is then passed explicitly
24/// through `create_physical_expr` so that function can find the slot index for
25/// each [`Subquery`]. While planning the body of a lambda,
26/// `create_physical_expr` extends the context with the lambda's parameters via
27/// [`Self::with_qualified_lambda_variables`].
28///
29/// An empty [`PhysicalPlanningContext`] (the [`Default`]) is what every
30/// non-physical-planner caller passes; if such a caller encounters a scalar
31/// subquery, `create_physical_expr` returns a `not_impl_err`.
32///
33/// [`Expr::ScalarSubquery`]: crate::Expr::ScalarSubquery
34/// [`Expr::LambdaVariable`]: crate::Expr::LambdaVariable
35/// [`Subquery`]: crate::logical_plan::Subquery
36#[derive(Clone, Debug, Default)]
37pub struct PhysicalPlanningContext {
38    /// Behind an `Arc` because the context is cloned for each lambda body that
39    /// is planned, and the indexes are the same for the whole subtree.
40    indexes: Arc<HashMap<crate::logical_plan::Subquery, SubqueryIndex>>,
41    results: ScalarSubqueryResults,
42    /// Maps each lambda variable name in scope to the qualifier generated for
43    /// its lambda during physical planning.
44    lambda_variable_qualifier: HashMap<String, TableReference>,
45}
46
47impl PhysicalPlanningContext {
48    /// Create a [`PhysicalPlanningContext`] from an index map and a shared
49    /// results container. The index map must use the same indices as slots in
50    /// `results`.
51    pub fn new(
52        indexes: HashMap<crate::logical_plan::Subquery, SubqueryIndex>,
53        results: ScalarSubqueryResults,
54    ) -> Self {
55        Self {
56            indexes: Arc::new(indexes),
57            results,
58            lambda_variable_qualifier: HashMap::new(),
59        }
60    }
61
62    /// Returns the slot index assigned to `subquery`, if any.
63    pub fn index_of(
64        &self,
65        subquery: &crate::logical_plan::Subquery,
66    ) -> Option<SubqueryIndex> {
67        self.indexes.get(subquery).copied()
68    }
69
70    /// Returns the shared results container.
71    pub fn results(&self) -> &ScalarSubqueryResults {
72        &self.results
73    }
74
75    /// Adds a mapping for each variable to the given qualifier. Existing
76    /// variables with conflicting names are shadowed.
77    pub fn with_qualified_lambda_variables(
78        mut self,
79        qualifier: &TableReference,
80        variables: &[String],
81    ) -> Self {
82        for var in variables {
83            self.lambda_variable_qualifier
84                .entry_ref(var)
85                .insert(qualifier.clone());
86        }
87
88        self
89    }
90
91    /// Returns the qualifier of the lambda variable `name`, if it is in scope.
92    pub fn lambda_variable_qualifier(&self, name: &str) -> Option<&TableReference> {
93        self.lambda_variable_qualifier.get(name)
94    }
95}
96
97/// Index of a scalar subquery within a [`ScalarSubqueryResults`] container.
98#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
99pub struct SubqueryIndex(usize);
100
101impl SubqueryIndex {
102    /// Creates a new subquery index.
103    pub const fn new(index: usize) -> Self {
104        Self(index)
105    }
106
107    /// Returns the underlying slot index.
108    pub const fn as_usize(self) -> usize {
109        self.0
110    }
111}
112
113/// Shared results container for uncorrelated scalar subqueries.
114///
115/// Each entry corresponds to one scalar subquery, identified by its index.
116/// Each slot is populated at execution time by `ScalarSubqueryExec`, read by
117/// `ScalarSubqueryExpr` instances that share this container, and cleared when
118/// the plan is reset for re-execution.
119#[derive(Clone, Default)]
120pub struct ScalarSubqueryResults {
121    slots: Arc<Vec<Mutex<Option<ScalarValue>>>>,
122}
123
124impl ScalarSubqueryResults {
125    /// Creates a new shared results container with `n` empty slots.
126    pub fn new(n: usize) -> Self {
127        Self {
128            slots: Arc::new((0..n).map(|_| Mutex::new(None)).collect()),
129        }
130    }
131
132    /// Returns the scalar value stored at `index`, if it has been populated.
133    pub fn get(&self, index: SubqueryIndex) -> Option<ScalarValue> {
134        let slot = self.slots.get(index.as_usize())?;
135        slot.lock().unwrap().clone()
136    }
137
138    /// Stores `value` in the slot at `index`.
139    pub fn set(&self, index: SubqueryIndex, value: ScalarValue) -> Result<()> {
140        let Some(slot) = self.slots.get(index.as_usize()) else {
141            return internal_err!(
142                "ScalarSubqueryResults: result index {} is out of bounds",
143                index.as_usize()
144            );
145        };
146
147        let mut slot = slot.lock().unwrap();
148        if slot.is_some() {
149            return internal_err!(
150                "ScalarSubqueryResults: result for index {} was already populated",
151                index.as_usize()
152            );
153        }
154        *slot = Some(value);
155
156        Ok(())
157    }
158
159    /// Clears all populated results so the container can be reused.
160    pub fn clear(&self) {
161        for slot in self.slots.iter() {
162            *slot.lock().unwrap() = None;
163        }
164    }
165
166    /// Returns true if `this` and `other` point to the same shared container.
167    pub fn ptr_eq(this: &Self, other: &Self) -> bool {
168        Arc::ptr_eq(&this.slots, &other.slots)
169    }
170}
171
172impl fmt::Debug for ScalarSubqueryResults {
173    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174        f.debug_list()
175            .entries(self.slots.iter().map(|slot| slot.lock().unwrap().clone()))
176            .finish()
177    }
178}
179
180impl PartialEq for ScalarSubqueryResults {
181    fn eq(&self, other: &Self) -> bool {
182        Self::ptr_eq(self, other)
183    }
184}
185
186impl Eq for ScalarSubqueryResults {}
187
188impl Hash for ScalarSubqueryResults {
189    fn hash<H: Hasher>(&self, state: &mut H) {
190        Arc::as_ptr(&self.slots).hash(state);
191    }
192}
193
194#[cfg(test)]
195mod tests {
196    use super::*;
197
198    #[test]
199    fn scalar_subquery_results_set_and_get() -> Result<()> {
200        let results = ScalarSubqueryResults::new(1);
201        assert_eq!(results.get(SubqueryIndex::new(0)), None);
202
203        results.set(SubqueryIndex::new(0), ScalarValue::Int32(Some(42)))?;
204        assert_eq!(
205            results.get(SubqueryIndex::new(0)),
206            Some(ScalarValue::Int32(Some(42)))
207        );
208        assert!(
209            results
210                .set(SubqueryIndex::new(0), ScalarValue::Int32(Some(7)))
211                .is_err()
212        );
213
214        Ok(())
215    }
216
217    #[test]
218    fn lambda_variables_shadow_outer_scope() {
219        let outer = TableReference::bare("lambda_1");
220        let inner = TableReference::bare("lambda_2");
221
222        let ctx = PhysicalPlanningContext::default()
223            .with_qualified_lambda_variables(&outer, &["x".to_string(), "y".to_string()])
224            .with_qualified_lambda_variables(&inner, &["y".to_string()]);
225
226        assert_eq!(ctx.lambda_variable_qualifier("x"), Some(&outer));
227        assert_eq!(ctx.lambda_variable_qualifier("y"), Some(&inner));
228        assert_eq!(ctx.lambda_variable_qualifier("z"), None);
229    }
230
231    #[test]
232    fn scalar_subquery_results_clear() -> Result<()> {
233        let results = ScalarSubqueryResults::new(1);
234        results.set(SubqueryIndex::new(0), ScalarValue::Int32(Some(42)))?;
235
236        results.clear();
237
238        assert_eq!(results.get(SubqueryIndex::new(0)), None);
239        results.set(SubqueryIndex::new(0), ScalarValue::Int32(Some(7)))?;
240        assert_eq!(
241            results.get(SubqueryIndex::new(0)),
242            Some(ScalarValue::Int32(Some(7)))
243        );
244
245        Ok(())
246    }
247}