datafusion-physical-expr 56.0.0

Physical expression implementation for DataFusion query engine
Documentation
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements

//! Physical lambda variable reference: [`LambdaVariable`]

use std::hash::Hash;
use std::sync::Arc;

use crate::physical_expr::PhysicalExpr;
use arrow::datatypes::FieldRef;
use arrow::{
    datatypes::{DataType, Schema},
    record_batch::RecordBatch,
};

use datafusion_common::{Result, exec_err, internal_err};
use datafusion_expr::ColumnarValue;

/// Represents the lambda variable with a given index and field
#[derive(Debug, Clone)]
pub struct LambdaVariable {
    index: usize,
    field: FieldRef,
}

impl Eq for LambdaVariable {}

impl PartialEq for LambdaVariable {
    fn eq(&self, other: &Self) -> bool {
        self.index == other.index && self.field == other.field
    }
}

impl Hash for LambdaVariable {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.index.hash(state);
        self.field.hash(state);
    }
}

impl LambdaVariable {
    /// Create a new lambda variable expression
    pub fn new(index: usize, field: FieldRef) -> Self {
        Self { index, field }
    }

    /// Get the variable's name
    pub fn name(&self) -> &str {
        self.field.name()
    }

    /// Get the variable's index
    pub fn index(&self) -> usize {
        self.index
    }

    /// Get the variable's field
    pub fn field(&self) -> &FieldRef {
        &self.field
    }

    #[cfg(feature = "proto")]
    /// Reconstruct a [`LambdaVariable`] from a proto node.
    pub fn try_from_proto(
        node: &datafusion_proto_models::protobuf::PhysicalExprNode,
        _ctx: &datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx<'_>,
    ) -> Result<Arc<dyn PhysicalExpr>> {
        use datafusion_physical_expr_common::{
            expect_expr_variant, physical_expr::proto_decode::require_proto_field,
        };
        use datafusion_proto_models::protobuf;

        let var = expect_expr_variant!(
            node,
            protobuf::physical_expr_node::ExprType::LambdaVariable,
            "LambdaVariable",
        );
        let protobuf::PhysicalLambdaVariableExprNode { index, field } = var;

        Ok(Arc::new(LambdaVariable::new(
            *index as usize,
            Arc::new(
                require_proto_field(field.as_ref(), "LambdaVariable", "field")?
                    .try_into()?,
            ),
        )))
    }
}

impl std::fmt::Display for LambdaVariable {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}@{}", self.name(), self.index)
    }
}

impl PhysicalExpr for LambdaVariable {
    fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
        Ok(self.field.data_type().clone())
    }

    fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
        Ok(self.field.is_nullable())
    }

    fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
        if self.index >= batch.num_columns() {
            return internal_err!(
                "PhysicalExpr LambdaVariable references column '{}' at index {} (zero-based) but batch only has {} columns: {:?}",
                self.name(),
                self.index,
                batch.num_columns(),
                batch
                    .schema_ref()
                    .fields()
                    .iter()
                    .map(|f| f.name())
                    .collect::<Vec<_>>()
            );
        }

        if self.field.as_ref() != batch.schema_ref().field(self.index) {
            return exec_err!(
                "Field of physical LambdaVariable with index {} doesn't match batch field during evaluation {} != {}",
                self.index,
                self.field,
                batch.schema_ref().field(self.index)
            );
        }

        Ok(ColumnarValue::Array(Arc::clone(batch.column(self.index))))
    }

    fn return_field(&self, _input_schema: &Schema) -> Result<FieldRef> {
        Ok(Arc::clone(&self.field))
    }

    fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
        vec![]
    }

    fn with_new_children(
        self: Arc<Self>,
        _children: Vec<Arc<dyn PhysicalExpr>>,
    ) -> Result<Arc<dyn PhysicalExpr>> {
        Ok(self)
    }

    fn fmt_sql(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}@{}", self.name(), self.index)
    }

    #[cfg(feature = "proto")]
    fn try_to_proto(
        &self,
        _ctx: &datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx<'_>,
    ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalExprNode>> {
        use datafusion_proto_models::protobuf;

        // Exhaustive destructure: adding a field to `LambdaVariable` without
        // deciding how it is serialized is a compile error, not a silent
        // round-trip gap.
        let Self { index, field } = self;

        Ok(Some(protobuf::PhysicalExprNode {
            expr_id: None,
            expr_type: Some(protobuf::physical_expr_node::ExprType::LambdaVariable(
                protobuf::PhysicalLambdaVariableExprNode {
                    index: *index as u32,
                    field: Some(field.as_ref().try_into()?),
                },
            )),
        }))
    }
}

/// Create a lambda variable expression
pub fn lambda_variable(name: &str, schema: &Schema) -> Result<Arc<dyn PhysicalExpr>> {
    let index = schema.index_of(name)?;
    let field = Arc::clone(&schema.fields()[index]);

    Ok(Arc::new(LambdaVariable::new(index, field)))
}

/// Tests for the `try_to_proto` / `try_from_proto` hooks.
#[cfg(all(test, feature = "proto"))]
mod proto_tests {
    use super::*;
    use crate::proto_test_util::{StubEncoder, UnreachableDecoder, column_node};
    use arrow::datatypes::Field;
    use datafusion_common::DataFusionError;
    use datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx;
    use datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx;
    use datafusion_proto_models::protobuf::{self, physical_expr_node};

    fn v_field() -> FieldRef {
        Arc::new(Field::new("v", DataType::Int32, true))
    }

    #[test]
    fn try_to_proto_encodes_lambda_variable() {
        let var = LambdaVariable::new(3, v_field());
        // LambdaVariable has no child exprs so the encoder is never called.
        let encoder = StubEncoder::ok();
        let ctx = PhysicalExprEncodeCtx::new(&encoder);

        let node = var
            .try_to_proto(&ctx)
            .unwrap()
            .expect("LambdaVariable should encode to Some(node)");

        assert!(node.expr_id.is_none());
        let protobuf::PhysicalLambdaVariableExprNode { index, field } =
            match node.expr_type {
                Some(physical_expr_node::ExprType::LambdaVariable(v)) => v,
                other => panic!("expected a LambdaVariable node, got {other:?}"),
            };
        assert_eq!(index, 3);
        let field = field.expect("field should be encoded");
        assert_eq!(field.name, "v");
        assert!(field.nullable);
    }

    #[test]
    fn try_from_proto_rejects_non_lambda_variable_node() {
        let node = column_node("a");
        let schema = Schema::empty();
        let decoder = UnreachableDecoder;
        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);

        let err = LambdaVariable::try_from_proto(&node, &ctx).unwrap_err();
        assert!(
            matches!(err, DataFusionError::Internal(msg) if msg.contains("PhysicalExprNode is not a LambdaVariable"))
        );
    }

    #[test]
    fn try_from_proto_rejects_missing_field() {
        let node = protobuf::PhysicalExprNode {
            expr_id: None,
            expr_type: Some(physical_expr_node::ExprType::LambdaVariable(
                protobuf::PhysicalLambdaVariableExprNode {
                    index: 0,
                    field: None,
                },
            )),
        };
        let schema = Schema::empty();
        let decoder = UnreachableDecoder;
        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);

        let err = LambdaVariable::try_from_proto(&node, &ctx).unwrap_err();
        assert!(
            matches!(err, DataFusionError::Internal(msg) if msg.contains("LambdaVariable is missing required field 'field'"))
        );
    }

    /// `PartialEq` covers every field of `LambdaVariable`, so equality after
    /// the roundtrip proves the encoding is lossless.
    #[test]
    fn lambda_variable_proto_roundtrip() {
        let var = LambdaVariable::new(5, v_field());
        let encoder = StubEncoder::ok();
        let enc_ctx = PhysicalExprEncodeCtx::new(&encoder);

        let node = var
            .try_to_proto(&enc_ctx)
            .unwrap()
            .expect("LambdaVariable should encode to Some(node)");

        let schema = Schema::empty();
        let decoder = UnreachableDecoder;
        let dec_ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);

        let decoded = LambdaVariable::try_from_proto(&node, &dec_ctx).unwrap();
        let decoded = decoded
            .downcast_ref::<LambdaVariable>()
            .expect("decoded expr should be a LambdaVariable");

        assert_eq!(decoded, &var);
    }
}