Skip to main content

datafusion_expr/
async_udf.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 crate::{ReturnFieldArgs, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl};
6use arrow::datatypes::{DataType, FieldRef};
7use async_trait::async_trait;
8use datafusion_common::error::Result;
9use datafusion_common::internal_err;
10use datafusion_expr_common::columnar_value::ColumnarValue;
11use datafusion_expr_common::signature::Signature;
12use std::any::Any;
13use std::fmt::{Debug, Display};
14use std::hash::{Hash, Hasher};
15use std::sync::Arc;
16
17/// A scalar UDF that can invoke using async methods
18///
19/// Note this is less efficient than the ScalarUDFImpl, but it can be used
20/// to register remote functions in the context.
21///
22/// The name is chosen to mirror ScalarUDFImpl
23#[async_trait]
24pub trait AsyncScalarUDFImpl: ScalarUDFImpl {
25    /// The ideal batch size for this function.
26    ///
27    /// This is used to determine what size of data to be evaluated at once.
28    /// If None, the whole batch will be evaluated at once.
29    fn ideal_batch_size(&self) -> Option<usize> {
30        None
31    }
32
33    /// Invoke the function asynchronously with the async arguments
34    async fn invoke_async_with_args(
35        &self,
36        args: ScalarFunctionArgs,
37    ) -> Result<ColumnarValue>;
38}
39
40/// A scalar UDF that must be invoked using async methods
41///
42/// Note this is not meant to be used directly, but is meant to be an implementation detail
43/// for AsyncUDFImpl.
44#[derive(Debug)]
45pub struct AsyncScalarUDF {
46    inner: Arc<dyn AsyncScalarUDFImpl>,
47}
48
49impl PartialEq for AsyncScalarUDF {
50    fn eq(&self, other: &Self) -> bool {
51        // Deconstruct to catch any new fields added in future
52        let Self { inner } = self;
53        inner.as_ref().dyn_eq(other.inner.as_ref() as &dyn Any)
54    }
55}
56impl Eq for AsyncScalarUDF {}
57
58impl Hash for AsyncScalarUDF {
59    fn hash<H: Hasher>(&self, state: &mut H) {
60        // Deconstruct to catch any new fields added in future
61        let Self { inner } = self;
62        inner.dyn_hash(state);
63    }
64}
65
66impl AsyncScalarUDF {
67    pub fn new(inner: Arc<dyn AsyncScalarUDFImpl>) -> Self {
68        Self { inner }
69    }
70
71    /// The ideal batch size for this function
72    pub fn ideal_batch_size(&self) -> Option<usize> {
73        self.inner.ideal_batch_size()
74    }
75
76    /// Turn this AsyncUDF into a ScalarUDF, suitable for
77    /// registering in the context
78    pub fn into_scalar_udf(self) -> ScalarUDF {
79        ScalarUDF::new_from_impl(self)
80    }
81
82    /// Invoke the function asynchronously with the async arguments
83    pub async fn invoke_async_with_args(
84        &self,
85        args: ScalarFunctionArgs,
86    ) -> Result<ColumnarValue> {
87        self.inner.invoke_async_with_args(args).await
88    }
89}
90
91impl ScalarUDFImpl for AsyncScalarUDF {
92    fn name(&self) -> &str {
93        self.inner.name()
94    }
95
96    fn signature(&self) -> &Signature {
97        self.inner.signature()
98    }
99
100    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
101        self.inner.return_type(arg_types)
102    }
103
104    fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> {
105        self.inner.return_field_from_args(args)
106    }
107
108    fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> {
109        internal_err!("async functions should not be called directly")
110    }
111}
112
113impl Display for AsyncScalarUDF {
114    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
115        write!(f, "AsyncScalarUDF: {}", self.inner.name())
116    }
117}
118
119#[cfg(test)]
120mod tests {
121    use std::{
122        hash::{DefaultHasher, Hash, Hasher},
123        sync::Arc,
124    };
125
126    use arrow::datatypes::DataType;
127    use async_trait::async_trait;
128    use datafusion_common::error::Result;
129    use datafusion_expr_common::{columnar_value::ColumnarValue, signature::Signature};
130
131    use crate::{
132        ScalarFunctionArgs, ScalarUDFImpl,
133        async_udf::{AsyncScalarUDF, AsyncScalarUDFImpl},
134    };
135
136    #[derive(Debug, PartialEq, Eq, Hash, Clone)]
137    struct TestAsyncUDFImpl1 {
138        a: i32,
139    }
140
141    impl ScalarUDFImpl for TestAsyncUDFImpl1 {
142        fn name(&self) -> &str {
143            todo!()
144        }
145
146        fn signature(&self) -> &Signature {
147            todo!()
148        }
149
150        fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
151            todo!()
152        }
153
154        fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> {
155            todo!()
156        }
157    }
158
159    #[async_trait]
160    impl AsyncScalarUDFImpl for TestAsyncUDFImpl1 {
161        async fn invoke_async_with_args(
162            &self,
163            _args: ScalarFunctionArgs,
164        ) -> Result<ColumnarValue> {
165            todo!()
166        }
167    }
168
169    #[derive(Debug, PartialEq, Eq, Hash, Clone)]
170    struct TestAsyncUDFImpl2 {
171        a: i32,
172    }
173
174    impl ScalarUDFImpl for TestAsyncUDFImpl2 {
175        fn name(&self) -> &str {
176            todo!()
177        }
178
179        fn signature(&self) -> &Signature {
180            todo!()
181        }
182
183        fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
184            todo!()
185        }
186
187        fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> {
188            todo!()
189        }
190    }
191
192    #[async_trait]
193    impl AsyncScalarUDFImpl for TestAsyncUDFImpl2 {
194        async fn invoke_async_with_args(
195            &self,
196            _args: ScalarFunctionArgs,
197        ) -> Result<ColumnarValue> {
198            todo!()
199        }
200    }
201
202    fn hash<T: Hash>(value: &T) -> u64 {
203        let hasher = &mut DefaultHasher::new();
204        value.hash(hasher);
205        hasher.finish()
206    }
207
208    #[test]
209    fn test_async_udf_partial_eq_and_hash() {
210        // Inner is same cloned arc -> equal
211        let inner = Arc::new(TestAsyncUDFImpl1 { a: 1 });
212        let a = AsyncScalarUDF::new(Arc::clone(&inner) as Arc<dyn AsyncScalarUDFImpl>);
213        let b = AsyncScalarUDF::new(inner);
214        assert_eq!(a, b);
215        assert_eq!(hash(&a), hash(&b));
216
217        // Inner is distinct arc -> still equal
218        let a = AsyncScalarUDF::new(Arc::new(TestAsyncUDFImpl1 { a: 1 }));
219        let b = AsyncScalarUDF::new(Arc::new(TestAsyncUDFImpl1 { a: 1 }));
220        assert_eq!(a, b);
221        assert_eq!(hash(&a), hash(&b));
222
223        // Negative case: inner is different value -> not equal
224        let a = AsyncScalarUDF::new(Arc::new(TestAsyncUDFImpl1 { a: 1 }));
225        let b = AsyncScalarUDF::new(Arc::new(TestAsyncUDFImpl1 { a: 2 }));
226        assert_ne!(a, b);
227        assert_ne!(hash(&a), hash(&b));
228
229        // Negative case: different functions -> not equal
230        let a = AsyncScalarUDF::new(Arc::new(TestAsyncUDFImpl1 { a: 1 }));
231        let b = AsyncScalarUDF::new(Arc::new(TestAsyncUDFImpl2 { a: 1 }));
232        assert_ne!(a, b);
233        assert_ne!(hash(&a), hash(&b));
234    }
235}