|
| 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 arrow::array::{Array, ArrayRef, Int32Builder, OffsetSizeTrait}; |
| 19 | +use arrow::datatypes::DataType; |
| 20 | +use datafusion::common::cast::as_generic_string_array; |
| 21 | +use datafusion::common::{exec_err, Result, ScalarValue}; |
| 22 | +use datafusion::logical_expr::{ |
| 23 | + ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility, |
| 24 | +}; |
| 25 | + |
| 26 | +use std::any::Any; |
| 27 | + |
| 28 | +use serde::de::{IgnoredAny, SeqAccess, Visitor}; |
| 29 | +use serde::Deserializer; |
| 30 | +use std::fmt; |
| 31 | +use std::sync::Arc; |
| 32 | + |
| 33 | +#[derive(Debug, PartialEq, Eq, Hash)] |
| 34 | +pub struct JsonArrayLength { |
| 35 | + signature: Signature, |
| 36 | +} |
| 37 | + |
| 38 | +impl Default for JsonArrayLength { |
| 39 | + fn default() -> Self { |
| 40 | + Self::new() |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +impl JsonArrayLength { |
| 45 | + pub fn new() -> Self { |
| 46 | + Self { |
| 47 | + signature: Signature::variadic( |
| 48 | + vec![DataType::Utf8, DataType::LargeUtf8], |
| 49 | + Volatility::Immutable, |
| 50 | + ), |
| 51 | + } |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +impl ScalarUDFImpl for JsonArrayLength { |
| 56 | + fn as_any(&self) -> &dyn Any { |
| 57 | + self |
| 58 | + } |
| 59 | + |
| 60 | + fn name(&self) -> &str { |
| 61 | + "json_array_length" |
| 62 | + } |
| 63 | + |
| 64 | + fn signature(&self) -> &Signature { |
| 65 | + &self.signature |
| 66 | + } |
| 67 | + |
| 68 | + fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> { |
| 69 | + Ok(DataType::Int32) |
| 70 | + } |
| 71 | + |
| 72 | + fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> { |
| 73 | + spark_json_array_length(&args.args) |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +fn spark_json_array_length(args: &[ColumnarValue]) -> Result<ColumnarValue> { |
| 78 | + if args.len() != 1 { |
| 79 | + return exec_err!("json_array_length function takes exactly one argument"); |
| 80 | + } |
| 81 | + match &args[0] { |
| 82 | + ColumnarValue::Array(array) => { |
| 83 | + let result = spark_json_array_length_array(array)?; |
| 84 | + Ok(ColumnarValue::Array(result)) |
| 85 | + } |
| 86 | + ColumnarValue::Scalar(scalar) => { |
| 87 | + let result = spark_json_array_length_scalar(scalar)?; |
| 88 | + Ok(ColumnarValue::Scalar(result)) |
| 89 | + } |
| 90 | + } |
| 91 | +} |
| 92 | + |
| 93 | +fn spark_json_array_length_array(array: &ArrayRef) -> Result<ArrayRef> { |
| 94 | + match array.data_type() { |
| 95 | + DataType::Utf8 => spark_json_array_length_array_inner::<i32>(array), |
| 96 | + DataType::LargeUtf8 => spark_json_array_length_array_inner::<i64>(array), |
| 97 | + other => { |
| 98 | + exec_err!("Unsupported data type {other:?} for function `json_array_length`") |
| 99 | + } |
| 100 | + } |
| 101 | +} |
| 102 | + |
| 103 | +fn spark_json_array_length_scalar(scalar: &ScalarValue) -> Result<ScalarValue> { |
| 104 | + match scalar { |
| 105 | + ScalarValue::Utf8(value) => spark_json_array_length_scalar_inner(value), |
| 106 | + ScalarValue::LargeUtf8(value) => spark_json_array_length_scalar_inner(value), |
| 107 | + other => { |
| 108 | + exec_err!("Unsupported data type {other:?} for function `json_array_length`") |
| 109 | + } |
| 110 | + } |
| 111 | +} |
| 112 | + |
| 113 | +fn spark_json_array_length_scalar_inner(json_str: &Option<String>) -> Result<ScalarValue> { |
| 114 | + let array_length = json_str |
| 115 | + .clone() |
| 116 | + .and_then(|json_str| get_json_array_length(&json_str)); |
| 117 | + Ok(ScalarValue::Int32(array_length)) |
| 118 | +} |
| 119 | + |
| 120 | +fn spark_json_array_length_array_inner<T: OffsetSizeTrait>(array: &ArrayRef) -> Result<ArrayRef> { |
| 121 | + let str_array = as_generic_string_array::<T>(array)?; |
| 122 | + let mut builder = Int32Builder::with_capacity(str_array.len()); |
| 123 | + for row_idx in 0..str_array.len() { |
| 124 | + if str_array.is_null(row_idx) { |
| 125 | + builder.append_null(); |
| 126 | + } else { |
| 127 | + let json_str = str_array.value(row_idx); |
| 128 | + if let Some(json_array_length) = get_json_array_length(json_str) { |
| 129 | + builder.append_value(json_array_length); |
| 130 | + } else { |
| 131 | + builder.append_null() |
| 132 | + } |
| 133 | + } |
| 134 | + } |
| 135 | + Ok(Arc::new(builder.finish())) |
| 136 | +} |
| 137 | + |
| 138 | +struct ArrayItemCounter; |
| 139 | + |
| 140 | +impl<'de> Visitor<'de> for ArrayItemCounter { |
| 141 | + type Value = i32; |
| 142 | + |
| 143 | + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 144 | + f.write_str("a JSON array") |
| 145 | + } |
| 146 | + |
| 147 | + fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> { |
| 148 | + let mut len = 0i32; |
| 149 | + while seq.next_element::<IgnoredAny>()?.is_some() { |
| 150 | + len += 1; |
| 151 | + } |
| 152 | + Ok(len) |
| 153 | + } |
| 154 | +} |
| 155 | + |
| 156 | +fn get_json_array_length(json: &str) -> Option<i32> { |
| 157 | + let mut deserializer = serde_json::Deserializer::from_str(json); |
| 158 | + deserializer.deserialize_seq(ArrayItemCounter).ok() |
| 159 | +} |
0 commit comments