|
| 1 | +// Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +// or more contributor license agreements. See the NOTICE file |
| 3 | +// distributed with this work for additional information |
| 4 | +// regarding copyright ownership. The ASF licenses this file |
| 5 | +// to you under the Apache License, Version 2.0 (the |
| 6 | +// "License"); you may not use this file except in compliance |
| 7 | +// with the License. You may obtain a copy of the License at |
| 8 | +// |
| 9 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +// |
| 11 | +// Unless required by applicable law or agreed to in writing, |
| 12 | +// software distributed under the License is distributed on an |
| 13 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +// KIND, either express or implied. See the License for the |
| 15 | +// specific language governing permissions and limitations |
| 16 | +// under the License. |
| 17 | + |
| 18 | +use std::{ffi::CString, sync::Arc}; |
| 19 | + |
| 20 | +use arrow::array::BooleanArray; |
| 21 | +use arrow_array::ArrayRef; |
| 22 | +use datafusion::common::cast::as_int64_array; |
| 23 | +use datafusion::logical_expr::create_udf; |
| 24 | +use datafusion::logical_expr::Volatility; |
| 25 | +use datafusion::physical_plan::ColumnarValue; |
| 26 | +use datafusion::{arrow::datatypes::DataType, error::Result}; |
| 27 | +use datafusion_ffi::udf::FFI_ScalarUDF; |
| 28 | +use pyo3::{prelude::*, types::PyCapsule}; |
| 29 | + |
| 30 | +#[pyclass(name = "IsEvenFunction", module = "datafusion_ffi_library", subclass)] |
| 31 | +#[derive(Clone)] |
| 32 | +pub struct IsEvenFunction {} |
| 33 | + |
| 34 | +fn is_even(args: &[ColumnarValue]) -> Result<ColumnarValue> { |
| 35 | + assert_eq!(args.len(), 1); |
| 36 | + let args = ColumnarValue::values_to_arrays(args)?; |
| 37 | + |
| 38 | + let values = as_int64_array(&args[0]).expect("cast failed"); |
| 39 | + |
| 40 | + let array = values |
| 41 | + .iter() |
| 42 | + .map(|value| value.and_then(|v| if v == 0 { None } else { Some(v % 2 == 0) })) |
| 43 | + .collect::<BooleanArray>(); |
| 44 | + |
| 45 | + Ok(ColumnarValue::from(Arc::new(array) as ArrayRef)) |
| 46 | +} |
| 47 | + |
| 48 | +#[pymethods] |
| 49 | +impl IsEvenFunction { |
| 50 | + #[new] |
| 51 | + fn new() -> Self { |
| 52 | + Self {} |
| 53 | + } |
| 54 | + |
| 55 | + fn __datafusion_scalar_udf__<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyCapsule>> { |
| 56 | + let name = CString::new("datafusion_scalar_udf").unwrap(); |
| 57 | + |
| 58 | + let func = create_udf( |
| 59 | + "is_even", |
| 60 | + vec![DataType::Int64], |
| 61 | + DataType::Boolean, |
| 62 | + Volatility::Immutable, |
| 63 | + Arc::new(is_even), |
| 64 | + ); |
| 65 | + |
| 66 | + let ffi_func: FFI_ScalarUDF = (Arc::new(func)).try_into()?; |
| 67 | + |
| 68 | + PyCapsule::new(py, ffi_func, Some(name)) |
| 69 | + } |
| 70 | +} |
0 commit comments