Skip to main content

datafusion_physical_expr/
scalar_subquery.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
5//! Physical expression for uncorrelated scalar subqueries.
6
7use std::fmt;
8use std::hash::Hash;
9use std::sync::Arc;
10
11use arrow::datatypes::{DataType, Field, FieldRef, Schema};
12use arrow::record_batch::RecordBatch;
13use datafusion_common::metadata::FieldMetadata;
14use datafusion_common::{Result, internal_datafusion_err};
15use datafusion_expr::physical_planning_context::{ScalarSubqueryResults, SubqueryIndex};
16use datafusion_expr_common::columnar_value::ColumnarValue;
17use datafusion_expr_common::sort_properties::{ExprProperties, SortProperties};
18use datafusion_physical_expr_common::physical_expr::PhysicalExpr;
19
20/// A physical expression whose value is provided by a scalar subquery.
21///
22/// Subquery execution is handled by `ScalarSubqueryExec`, which stores the
23/// result in a shared [`ScalarSubqueryResults`] container. This expression
24/// simply reads from that container at the appropriate index.
25#[derive(Debug)]
26pub struct ScalarSubqueryExpr {
27    /// Output field of the scalar subquery, including Arrow extension metadata.
28    field: FieldRef,
29    /// Index of this subquery in the shared results container.
30    index: SubqueryIndex,
31    /// Shared results container populated by `ScalarSubqueryExec`.
32    results: ScalarSubqueryResults,
33}
34
35impl ScalarSubqueryExpr {
36    pub fn new(
37        data_type: DataType,
38        nullable: bool,
39        index: SubqueryIndex,
40        results: ScalarSubqueryResults,
41    ) -> Self {
42        Self::new_with_metadata(data_type, nullable, None, index, results)
43    }
44
45    /// Create a scalar subquery expression, preserving optional field metadata
46    /// from the logical subquery output (for example Arrow extension type names).
47    pub fn new_with_metadata(
48        data_type: DataType,
49        nullable: bool,
50        metadata: Option<FieldMetadata>,
51        index: SubqueryIndex,
52        results: ScalarSubqueryResults,
53    ) -> Self {
54        let mut field = Field::new("scalar_subquery", data_type, nullable);
55        if let Some(metadata) = metadata {
56            field = metadata.add_to_field(field);
57        }
58        Self {
59            field: Arc::new(field),
60            index,
61            results,
62        }
63    }
64
65    pub fn results(&self) -> &ScalarSubqueryResults {
66        &self.results
67    }
68
69    #[deprecated(
70        since = "55.0.0",
71        note = "was only used for proto serialization, which no longer needs it; use `return_field` for type/nullability. It will be removed in 61.0.0 or 6 months after 55.0.0 is released, whichever is longer."
72    )]
73    pub fn data_type(&self) -> &DataType {
74        self.field.data_type()
75    }
76
77    #[deprecated(
78        since = "55.0.0",
79        note = "was only used for proto serialization, which no longer needs it; use `return_field` for type/nullability. It will be removed in 61.0.0 or 6 months after 55.0.0 is released, whichever is longer."
80    )]
81    pub fn nullable(&self) -> bool {
82        self.field.is_nullable()
83    }
84
85    /// Returns the index of this subquery in the shared results container.
86    pub fn index(&self) -> SubqueryIndex {
87        self.index
88    }
89}
90
91impl fmt::Display for ScalarSubqueryExpr {
92    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93        match self.results.get(self.index) {
94            Some(v) => write!(f, "scalar_subquery({v})"),
95            None => write!(f, "scalar_subquery(<pending>)"),
96        }
97    }
98}
99
100// Two ScalarSubqueryExprs are considered the "same" if they refer to the
101// same underlying shared results container and the same index within it.
102impl Hash for ScalarSubqueryExpr {
103    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
104        self.results.hash(state);
105        self.index.hash(state);
106    }
107}
108
109impl PartialEq for ScalarSubqueryExpr {
110    fn eq(&self, other: &Self) -> bool {
111        self.results == other.results && self.index == other.index
112    }
113}
114
115impl Eq for ScalarSubqueryExpr {}
116
117impl PhysicalExpr for ScalarSubqueryExpr {
118    fn return_field(&self, _input_schema: &Schema) -> Result<FieldRef> {
119        Ok(Arc::clone(&self.field))
120    }
121
122    fn evaluate(&self, _batch: &RecordBatch) -> Result<ColumnarValue> {
123        let value = self.results.get(self.index).ok_or_else(|| {
124            internal_datafusion_err!(
125                "ScalarSubqueryExpr evaluated before the subquery was executed"
126            )
127        })?;
128        Ok(ColumnarValue::Scalar(value))
129    }
130
131    fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
132        vec![]
133    }
134
135    fn with_new_children(
136        self: Arc<Self>,
137        _children: Vec<Arc<dyn PhysicalExpr>>,
138    ) -> Result<Arc<dyn PhysicalExpr>> {
139        Ok(self)
140    }
141
142    fn get_properties(&self, _children: &[ExprProperties]) -> Result<ExprProperties> {
143        Ok(ExprProperties::new_unknown().with_order(SortProperties::Singleton))
144    }
145
146    fn fmt_sql(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147        write!(f, "(scalar subquery)")
148    }
149
150    #[cfg(feature = "proto")]
151    fn try_to_proto(
152        &self,
153        _ctx: &datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx<'_>,
154    ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalExprNode>> {
155        use datafusion_common::utils::usize_to_wire;
156        use datafusion_proto_models::protobuf;
157
158        let Self {
159            field,
160            index,
161            results: _, // Runtime state, supplied by ScalarSubqueryExec on decode.
162        } = self;
163
164        Ok(Some(protobuf::PhysicalExprNode {
165            expr_id: None,
166            expr_type: Some(protobuf::physical_expr_node::ExprType::ScalarSubquery(
167                protobuf::PhysicalScalarSubqueryExprNode {
168                    data_type: Some(field.data_type().try_into()?),
169                    nullable: field.is_nullable(),
170                    index: usize_to_wire(
171                        index.as_usize(),
172                        "ScalarSubqueryExpr",
173                        "index",
174                    )?,
175                    metadata: field.metadata().into(),
176                },
177            )),
178        }))
179    }
180}
181
182#[cfg(feature = "proto")]
183impl ScalarSubqueryExpr {
184    /// Reconstruct a [`ScalarSubqueryExpr`] from its protobuf representation.
185    ///
186    /// Unlike other expressions, this takes a third argument: the shared
187    /// [`ScalarSubqueryResults`] container. That container is a runtime-only
188    /// `Arc` shared with the surrounding `ScalarSubqueryExec` and is not part of
189    /// the wire format, so it cannot be reconstructed here or carried on the
190    /// decode context (which lives in a crate that cannot depend on
191    /// `datafusion-expr`). The match arm in `from_proto.rs` fetches it from the
192    /// plan-level decode context and passes it in.
193    pub fn try_from_proto(
194        node: &datafusion_proto_models::protobuf::PhysicalExprNode,
195        _ctx: &datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx<'_>,
196        results: &ScalarSubqueryResults,
197    ) -> Result<Arc<dyn PhysicalExpr>> {
198        use datafusion_physical_expr_common::expect_expr_variant;
199        use datafusion_physical_expr_common::physical_expr::proto_decode::require_proto_field;
200        use datafusion_proto_models::protobuf;
201
202        let sq = expect_expr_variant!(
203            node,
204            protobuf::physical_expr_node::ExprType::ScalarSubquery,
205            "ScalarSubqueryExpr",
206        );
207        let protobuf::PhysicalScalarSubqueryExprNode {
208            data_type,
209            nullable,
210            index,
211            metadata,
212        } = sq;
213        let data_type =
214            require_proto_field(data_type.as_ref(), "ScalarSubqueryExpr", "data_type")?
215                .try_into()?;
216        let metadata = if metadata.is_empty() {
217            None
218        } else {
219            Some(FieldMetadata::from(metadata.clone()))
220        };
221        Ok(Arc::new(ScalarSubqueryExpr::new_with_metadata(
222            data_type,
223            *nullable,
224            metadata,
225            SubqueryIndex::new(*index as usize),
226            results.clone(),
227        )))
228    }
229}
230
231#[cfg(test)]
232mod tests {
233    use super::*;
234
235    use arrow::array::Int32Array;
236    use arrow::datatypes::Field;
237    use datafusion_common::ScalarValue;
238
239    fn make_results(values: Vec<Option<ScalarValue>>) -> ScalarSubqueryResults {
240        let results = ScalarSubqueryResults::new(values.len());
241        for (index, value) in values.into_iter().enumerate() {
242            if let Some(value) = value {
243                results.set(SubqueryIndex::new(index), value).unwrap();
244            }
245        }
246        results
247    }
248
249    #[test]
250    fn test_evaluate_with_value() -> Result<()> {
251        let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
252        let a = Int32Array::from(vec![1, 2, 3]);
253        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)])?;
254
255        let results = make_results(vec![Some(ScalarValue::Int32(Some(42)))]);
256        let expr = ScalarSubqueryExpr::new(
257            DataType::Int32,
258            false,
259            SubqueryIndex::new(0),
260            results,
261        );
262
263        let result = expr.evaluate(&batch)?;
264        match result {
265            ColumnarValue::Scalar(ScalarValue::Int32(Some(42))) => {}
266            other => panic!("Expected Scalar(Int32(42)), got {other:?}"),
267        }
268        Ok(())
269    }
270
271    #[test]
272    fn test_evaluate_before_populated() {
273        let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
274        let a = Int32Array::from(vec![1]);
275        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)]).unwrap();
276
277        let results = ScalarSubqueryResults::new(1);
278        let expr = ScalarSubqueryExpr::new(
279            DataType::Int32,
280            false,
281            SubqueryIndex::new(0),
282            results,
283        );
284
285        let result = expr.evaluate(&batch);
286        assert!(result.is_err());
287    }
288
289    #[test]
290    fn test_identity_equality() {
291        let results = make_results(vec![None, None]);
292
293        let e1a = ScalarSubqueryExpr::new(
294            DataType::Int32,
295            false,
296            SubqueryIndex::new(0),
297            results.clone(),
298        );
299        let e1b = ScalarSubqueryExpr::new(
300            DataType::Int32,
301            false,
302            SubqueryIndex::new(0),
303            results.clone(),
304        );
305        let e2 = ScalarSubqueryExpr::new(
306            DataType::Int32,
307            false,
308            SubqueryIndex::new(1),
309            results.clone(),
310        );
311
312        // Same container + same index → equal
313        assert_eq!(e1a, e1b);
314        // Same container, different index → not equal
315        assert_ne!(e1a, e2);
316
317        // Different container, same index → not equal
318        let other_results = make_results(vec![None]);
319        let e3 = ScalarSubqueryExpr::new(
320            DataType::Int32,
321            false,
322            SubqueryIndex::new(0),
323            other_results,
324        );
325        assert_ne!(e1a, e3);
326    }
327
328    #[test]
329    fn return_field_preserves_extension_metadata() -> Result<()> {
330        let metadata = FieldMetadata::from(std::collections::HashMap::from([(
331            "ARROW:extension:name".to_string(),
332            "example.extension".to_string(),
333        )]));
334        let expr = ScalarSubqueryExpr::new_with_metadata(
335            DataType::Utf8,
336            true,
337            Some(metadata),
338            SubqueryIndex::new(0),
339            ScalarSubqueryResults::new(1),
340        );
341
342        let field = expr.return_field(&Schema::empty())?;
343        assert_eq!(field.name(), "scalar_subquery");
344        assert_eq!(field.data_type(), &DataType::Utf8);
345        assert!(field.is_nullable());
346        assert_eq!(
347            field.metadata().get("ARROW:extension:name"),
348            Some(&"example.extension".to_string())
349        );
350        Ok(())
351    }
352}
353
354/// Tests for the `try_to_proto` / `try_from_proto` hooks.
355#[cfg(all(test, feature = "proto"))]
356mod proto_tests {
357    use super::*;
358    use crate::proto_test_util::{StubEncoder, UnreachableDecoder, column_node};
359    use datafusion_common::DataFusionError;
360    use datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx;
361    use datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx;
362    use datafusion_proto_models::protobuf::{
363        PhysicalExprNode, PhysicalScalarSubqueryExprNode, physical_expr_node,
364    };
365
366    /// Build a `ScalarSubquery` proto node directly, with control over each
367    /// field, so the decode error paths can be exercised independently.
368    fn proto_scalar_subquery_node(
369        data_type: Option<datafusion_proto_models::datafusion_common::ArrowType>,
370        nullable: bool,
371        index: u32,
372    ) -> PhysicalExprNode {
373        PhysicalExprNode {
374            expr_id: None,
375            expr_type: Some(physical_expr_node::ExprType::ScalarSubquery(
376                PhysicalScalarSubqueryExprNode {
377                    data_type,
378                    nullable,
379                    index,
380                    metadata: Default::default(),
381                },
382            )),
383        }
384    }
385
386    #[test]
387    fn round_trips_through_proto() {
388        // A three-slot results container so index 2 is meaningful.
389        let results = ScalarSubqueryResults::new(3);
390        let expr = ScalarSubqueryExpr::new_with_metadata(
391            DataType::Int32,
392            true,
393            Some(FieldMetadata::from(std::collections::HashMap::from([(
394                "ARROW:extension:name".to_string(),
395                "example.extension".to_string(),
396            )]))),
397            SubqueryIndex::new(2),
398            results.clone(),
399        );
400
401        // Encode: the expression serializes itself via try_to_proto.
402        let encoder = StubEncoder::ok();
403        let enc_ctx = PhysicalExprEncodeCtx::new(&encoder);
404        let node = expr
405            .try_to_proto(&enc_ctx)
406            .unwrap()
407            .expect("ScalarSubqueryExpr should encode to Some(node)");
408
409        assert!(node.expr_id.is_none());
410        let sq = match &node.expr_type {
411            Some(physical_expr_node::ExprType::ScalarSubquery(sq)) => sq,
412            other => panic!("expected a ScalarSubquery node, got {other:?}"),
413        };
414        assert!(sq.nullable);
415        assert_eq!(sq.index, 2);
416        let encoded_type: DataType = sq
417            .data_type
418            .as_ref()
419            .expect("data_type encoded")
420            .try_into()
421            .unwrap();
422        assert_eq!(encoded_type, DataType::Int32);
423        assert_eq!(
424            sq.metadata.get("ARROW:extension:name").map(String::as_str),
425            Some("example.extension")
426        );
427
428        // Decode: reconstruct from the proto node, threading in the shared
429        // results container the surrounding exec would provide.
430        let decoder = UnreachableDecoder;
431        let schema = Schema::empty();
432        let dec_ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
433        let decoded =
434            ScalarSubqueryExpr::try_from_proto(&node, &dec_ctx, &results).unwrap();
435        let decoded = decoded
436            .downcast_ref::<ScalarSubqueryExpr>()
437            .expect("decoded expr should be a ScalarSubqueryExpr");
438
439        // data_type + nullable survive the round-trip (observed via return_field).
440        let field = decoded.return_field(&Schema::empty()).unwrap();
441        assert_eq!(field.data_type(), &DataType::Int32);
442        assert!(field.is_nullable());
443        assert_eq!(
444            field.metadata().get("ARROW:extension:name"),
445            Some(&"example.extension".to_string())
446        );
447
448        // Same shared container + same index → equal to the original.
449        assert_eq!(decoded, &expr);
450    }
451
452    #[test]
453    fn rejects_non_scalar_subquery_node() {
454        let node = column_node("a");
455        let results = ScalarSubqueryResults::new(1);
456        let decoder = UnreachableDecoder;
457        let schema = Schema::empty();
458        let dec_ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
459
460        let err =
461            ScalarSubqueryExpr::try_from_proto(&node, &dec_ctx, &results).unwrap_err();
462        assert!(matches!(
463            err,
464            DataFusionError::Internal(msg)
465                if msg.contains("PhysicalExprNode is not a ScalarSubqueryExpr")
466        ));
467    }
468
469    #[test]
470    fn rejects_missing_data_type() {
471        let node = proto_scalar_subquery_node(None, false, 0);
472        let results = ScalarSubqueryResults::new(1);
473        let decoder = UnreachableDecoder;
474        let schema = Schema::empty();
475        let dec_ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
476
477        let err =
478            ScalarSubqueryExpr::try_from_proto(&node, &dec_ctx, &results).unwrap_err();
479        assert!(matches!(
480            err,
481            DataFusionError::Internal(msg)
482                if msg.contains("ScalarSubqueryExpr is missing required field 'data_type'")
483        ));
484    }
485}