datafusion_physical_expr/
async_scalar_function.rs1use crate::ScalarFunctionExpr;
19use arrow::array::RecordBatch;
20use arrow::compute::concat;
21use arrow::datatypes::{DataType, Field, FieldRef, Schema};
22use datafusion_common::Result;
23use datafusion_common::config::ConfigOptions;
24use datafusion_common::{internal_err, not_impl_err};
25use datafusion_expr::ScalarFunctionArgs;
26use datafusion_expr::async_udf::AsyncScalarUDF;
27use datafusion_expr_common::columnar_value::ColumnarValue;
28use datafusion_physical_expr_common::physical_expr::PhysicalExpr;
29use std::fmt::Display;
30use std::hash::{Hash, Hasher};
31use std::sync::Arc;
32
33#[derive(Debug, Clone, Eq)]
35pub struct AsyncFuncExpr {
36 pub name: String,
38 pub func: Arc<dyn PhysicalExpr>,
40 return_field: FieldRef,
42}
43
44impl Display for AsyncFuncExpr {
45 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
46 write!(f, "async_expr(name={}, expr={})", self.name, self.func)
47 }
48}
49
50impl PartialEq for AsyncFuncExpr {
51 fn eq(&self, other: &Self) -> bool {
52 self.name == other.name && self.func == Arc::clone(&other.func)
53 }
54}
55
56impl Hash for AsyncFuncExpr {
57 fn hash<H: Hasher>(&self, state: &mut H) {
58 self.name.hash(state);
59 self.func.as_ref().hash(state);
60 }
61}
62
63impl AsyncFuncExpr {
64 pub fn try_new(
66 name: impl Into<String>,
67 func: Arc<dyn PhysicalExpr>,
68 schema: &Schema,
69 ) -> Result<Self> {
70 let Some(_) = func.downcast_ref::<ScalarFunctionExpr>() else {
71 return internal_err!(
72 "unexpected function type, expected ScalarFunctionExpr, got: {:?}",
73 func
74 );
75 };
76
77 let return_field = func.return_field(schema)?;
78 Ok(Self {
79 name: name.into(),
80 func,
81 return_field,
82 })
83 }
84
85 pub fn name(&self) -> &str {
87 &self.name
88 }
89
90 #[deprecated(since = "55.0.0", note = "Use return_field instead")]
92 pub fn field(&self, _input_schema: &Schema) -> Result<Field> {
93 Ok(self.return_field.as_ref().clone().with_name(&self.name))
94 }
95
96 pub fn ideal_batch_size(&self) -> Result<Option<usize>> {
98 if let Some(expr) = self.func.downcast_ref::<ScalarFunctionExpr>()
99 && let Some(udf) = expr.fun().inner().downcast_ref::<AsyncScalarUDF>()
100 {
101 return Ok(udf.ideal_batch_size());
102 }
103 not_impl_err!("Can't get ideal_batch_size from {:?}", self.func)
104 }
105
106 pub async fn invoke_with_args(
110 &self,
111 batch: &RecordBatch,
112 config_options: Arc<ConfigOptions>,
113 ) -> Result<ColumnarValue> {
114 let Some(scalar_function_expr) = self.func.downcast_ref::<ScalarFunctionExpr>()
115 else {
116 return internal_err!(
117 "unexpected function type, expected ScalarFunctionExpr, got: {:?}",
118 self.func
119 );
120 };
121
122 let Some(async_udf) = scalar_function_expr
123 .fun()
124 .inner()
125 .downcast_ref::<AsyncScalarUDF>()
126 else {
127 return not_impl_err!(
128 "Don't know how to evaluate async function: {:?}",
129 scalar_function_expr
130 );
131 };
132
133 let arg_fields = scalar_function_expr
134 .args()
135 .iter()
136 .map(|e| e.return_field(batch.schema_ref()))
137 .collect::<Result<Vec<_>>>()?;
138
139 let mut result_batches = vec![];
140 if let Some(ideal_batch_size) = self.ideal_batch_size()? {
141 let mut remainder = batch.clone();
142 while remainder.num_rows() > 0 {
143 let size = if ideal_batch_size > remainder.num_rows() {
144 remainder.num_rows()
145 } else {
146 ideal_batch_size
147 };
148
149 let current_batch = remainder.slice(0, size); remainder = remainder.slice(size, remainder.num_rows() - size);
151 let args = scalar_function_expr
152 .args()
153 .iter()
154 .map(|e| e.evaluate(¤t_batch))
155 .collect::<Result<Vec<_>>>()?;
156 result_batches.push(
157 async_udf
158 .invoke_async_with_args(ScalarFunctionArgs {
159 args,
160 arg_fields: arg_fields.clone(),
161 number_rows: current_batch.num_rows(),
162 return_field: Arc::clone(&self.return_field),
163 config_options: Arc::clone(&config_options),
164 })
165 .await?
166 .into_array_of_size(current_batch.num_rows())?,
167 );
168 }
169 } else {
170 let args = scalar_function_expr
171 .args()
172 .iter()
173 .map(|e| e.evaluate(batch))
174 .collect::<Result<Vec<_>>>()?;
175
176 result_batches.push(
177 async_udf
178 .invoke_async_with_args(ScalarFunctionArgs {
179 args: args.to_vec(),
180 arg_fields,
181 number_rows: batch.num_rows(),
182 return_field: Arc::clone(&self.return_field),
183 config_options: Arc::clone(&config_options),
184 })
185 .await?
186 .into_array_of_size(batch.num_rows())?,
187 );
188 }
189
190 let dyn_arrays = result_batches
192 .iter()
193 .map(|arr| arr as &dyn arrow::array::Array)
194 .collect::<Vec<_>>();
195 let result_array = concat(&dyn_arrays)?;
196 Ok(ColumnarValue::Array(result_array))
197 }
198}
199
200impl PhysicalExpr for AsyncFuncExpr {
201 fn data_type(&self, input_schema: &Schema) -> Result<DataType> {
202 self.func.data_type(input_schema)
203 }
204
205 fn return_field(&self, _input_schema: &Schema) -> Result<FieldRef> {
206 Ok(Arc::new(
207 self.return_field.as_ref().clone().with_name(&self.name),
208 ))
209 }
210
211 fn nullable(&self, input_schema: &Schema) -> Result<bool> {
212 self.func.nullable(input_schema)
213 }
214
215 fn evaluate(&self, _batch: &RecordBatch) -> Result<ColumnarValue> {
216 not_impl_err!("AsyncFuncExpr.evaluate")
218 }
219
220 fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
221 self.func.children()
222 }
223
224 fn with_new_children(
225 self: Arc<Self>,
226 children: Vec<Arc<dyn PhysicalExpr>>,
227 ) -> Result<Arc<dyn PhysicalExpr>> {
228 let new_func = Arc::clone(&self.func).with_new_children(children)?;
229 Ok(Arc::new(AsyncFuncExpr {
230 name: self.name.clone(),
231 func: new_func,
232 return_field: Arc::clone(&self.return_field),
233 }))
234 }
235
236 fn fmt_sql(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
237 write!(f, "{}", self.func)
238 }
239}