|
| 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 | +//! `ARRAY_AGG` aggregate implementation: [`ArrayAgg`] |
| 19 | +
|
| 20 | +use arrow::array::{Array, ArrayRef, AsArray}; |
| 21 | +use arrow::datatypes::DataType; |
| 22 | +use arrow_schema::Field; |
| 23 | + |
| 24 | +use datafusion_common::cast::as_list_array; |
| 25 | +use datafusion_common::utils::array_into_list_array_nullable; |
| 26 | +use datafusion_common::ScalarValue; |
| 27 | +use datafusion_common::{internal_err, Result}; |
| 28 | +use datafusion_expr::function::{AccumulatorArgs, StateFieldsArgs}; |
| 29 | +use datafusion_expr::utils::format_state_name; |
| 30 | +use datafusion_expr::AggregateUDFImpl; |
| 31 | +use datafusion_expr::{Accumulator, Signature, Volatility}; |
| 32 | +use std::collections::HashSet; |
| 33 | +use std::sync::Arc; |
| 34 | + |
| 35 | +make_udaf_expr_and_func!( |
| 36 | + ArrayAgg, |
| 37 | + array_agg, |
| 38 | + expression, |
| 39 | + "input values, including nulls, concatenated into an array", |
| 40 | + array_agg_udaf |
| 41 | +); |
| 42 | + |
| 43 | +#[derive(Debug)] |
| 44 | +/// ARRAY_AGG aggregate expression |
| 45 | +pub struct ArrayAgg { |
| 46 | + signature: Signature, |
| 47 | + alias: Vec<String>, |
| 48 | +} |
| 49 | + |
| 50 | +impl Default for ArrayAgg { |
| 51 | + fn default() -> Self { |
| 52 | + Self { |
| 53 | + signature: Signature::any(1, Volatility::Immutable), |
| 54 | + alias: vec!["array_agg".to_string()], |
| 55 | + } |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +impl AggregateUDFImpl for ArrayAgg { |
| 60 | + fn as_any(&self) -> &dyn std::any::Any { |
| 61 | + self |
| 62 | + } |
| 63 | + |
| 64 | + // TODO: change name to lowercase |
| 65 | + fn name(&self) -> &str { |
| 66 | + "ARRAY_AGG" |
| 67 | + } |
| 68 | + |
| 69 | + fn aliases(&self) -> &[String] { |
| 70 | + &self.alias |
| 71 | + } |
| 72 | + |
| 73 | + fn signature(&self) -> &Signature { |
| 74 | + &self.signature |
| 75 | + } |
| 76 | + |
| 77 | + fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> { |
| 78 | + Ok(DataType::List(Arc::new(Field::new( |
| 79 | + "item", |
| 80 | + arg_types[0].clone(), |
| 81 | + true, |
| 82 | + )))) |
| 83 | + } |
| 84 | + |
| 85 | + fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<Field>> { |
| 86 | + if args.is_distinct { |
| 87 | + return Ok(vec![Field::new_list( |
| 88 | + format_state_name(args.name, "distinct_array_agg"), |
| 89 | + Field::new("item", args.input_type.clone(), true), |
| 90 | + true, |
| 91 | + )]); |
| 92 | + } |
| 93 | + |
| 94 | + Ok(vec![Field::new_list( |
| 95 | + format_state_name(args.name, "array_agg"), |
| 96 | + Field::new("item", args.input_type.clone(), true), |
| 97 | + true, |
| 98 | + )]) |
| 99 | + } |
| 100 | + |
| 101 | + fn accumulator(&self, acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> { |
| 102 | + if acc_args.is_distinct { |
| 103 | + return Ok(Box::new(DistinctArrayAggAccumulator::try_new( |
| 104 | + acc_args.input_type, |
| 105 | + )?)); |
| 106 | + } |
| 107 | + |
| 108 | + Ok(Box::new(ArrayAggAccumulator::try_new(acc_args.input_type)?)) |
| 109 | + } |
| 110 | +} |
| 111 | + |
| 112 | +#[derive(Debug)] |
| 113 | +pub struct ArrayAggAccumulator { |
| 114 | + values: Vec<ArrayRef>, |
| 115 | + datatype: DataType, |
| 116 | +} |
| 117 | + |
| 118 | +impl ArrayAggAccumulator { |
| 119 | + /// new array_agg accumulator based on given item data type |
| 120 | + pub fn try_new(datatype: &DataType) -> Result<Self> { |
| 121 | + Ok(Self { |
| 122 | + values: vec![], |
| 123 | + datatype: datatype.clone(), |
| 124 | + }) |
| 125 | + } |
| 126 | +} |
| 127 | + |
| 128 | +impl Accumulator for ArrayAggAccumulator { |
| 129 | + fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> { |
| 130 | + // Append value like Int64Array(1,2,3) |
| 131 | + if values.is_empty() { |
| 132 | + return Ok(()); |
| 133 | + } |
| 134 | + |
| 135 | + if values.len() != 1 { |
| 136 | + return internal_err!("expects single batch"); |
| 137 | + } |
| 138 | + |
| 139 | + let val = Arc::clone(&values[0]); |
| 140 | + if val.len() > 0 { |
| 141 | + self.values.push(val); |
| 142 | + } |
| 143 | + Ok(()) |
| 144 | + } |
| 145 | + |
| 146 | + fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> { |
| 147 | + // Append value like ListArray(Int64Array(1,2,3), Int64Array(4,5,6)) |
| 148 | + if states.is_empty() { |
| 149 | + return Ok(()); |
| 150 | + } |
| 151 | + |
| 152 | + if states.len() != 1 { |
| 153 | + return internal_err!("expects single state"); |
| 154 | + } |
| 155 | + |
| 156 | + let list_arr = as_list_array(&states[0])?; |
| 157 | + for arr in list_arr.iter().flatten() { |
| 158 | + self.values.push(arr); |
| 159 | + } |
| 160 | + Ok(()) |
| 161 | + } |
| 162 | + |
| 163 | + fn state(&mut self) -> Result<Vec<ScalarValue>> { |
| 164 | + Ok(vec![self.evaluate()?]) |
| 165 | + } |
| 166 | + |
| 167 | + fn evaluate(&mut self) -> Result<ScalarValue> { |
| 168 | + // Transform Vec<ListArr> to ListArr |
| 169 | + let element_arrays: Vec<&dyn Array> = |
| 170 | + self.values.iter().map(|a| a.as_ref()).collect(); |
| 171 | + |
| 172 | + if element_arrays.is_empty() { |
| 173 | + return Ok(ScalarValue::new_null_list(self.datatype.clone(), true, 1)); |
| 174 | + } |
| 175 | + |
| 176 | + let concated_array = arrow::compute::concat(&element_arrays)?; |
| 177 | + let list_array = array_into_list_array_nullable(concated_array); |
| 178 | + |
| 179 | + Ok(ScalarValue::List(Arc::new(list_array))) |
| 180 | + } |
| 181 | + |
| 182 | + fn size(&self) -> usize { |
| 183 | + std::mem::size_of_val(self) |
| 184 | + + (std::mem::size_of::<ArrayRef>() * self.values.capacity()) |
| 185 | + + self |
| 186 | + .values |
| 187 | + .iter() |
| 188 | + .map(|arr| arr.get_array_memory_size()) |
| 189 | + .sum::<usize>() |
| 190 | + + self.datatype.size() |
| 191 | + - std::mem::size_of_val(&self.datatype) |
| 192 | + } |
| 193 | +} |
| 194 | + |
| 195 | +#[derive(Debug)] |
| 196 | +struct DistinctArrayAggAccumulator { |
| 197 | + values: HashSet<ScalarValue>, |
| 198 | + datatype: DataType, |
| 199 | +} |
| 200 | + |
| 201 | +impl DistinctArrayAggAccumulator { |
| 202 | + pub fn try_new(datatype: &DataType) -> Result<Self> { |
| 203 | + Ok(Self { |
| 204 | + values: HashSet::new(), |
| 205 | + datatype: datatype.clone(), |
| 206 | + }) |
| 207 | + } |
| 208 | +} |
| 209 | + |
| 210 | +impl Accumulator for DistinctArrayAggAccumulator { |
| 211 | + fn state(&mut self) -> Result<Vec<ScalarValue>> { |
| 212 | + Ok(vec![self.evaluate()?]) |
| 213 | + } |
| 214 | + |
| 215 | + fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> { |
| 216 | + if values.len() != 1 { |
| 217 | + return internal_err!("expects single batch"); |
| 218 | + } |
| 219 | + |
| 220 | + let array = &values[0]; |
| 221 | + |
| 222 | + for i in 0..array.len() { |
| 223 | + let scalar = ScalarValue::try_from_array(&array, i)?; |
| 224 | + self.values.insert(scalar); |
| 225 | + } |
| 226 | + |
| 227 | + Ok(()) |
| 228 | + } |
| 229 | + |
| 230 | + fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> { |
| 231 | + if states.is_empty() { |
| 232 | + return Ok(()); |
| 233 | + } |
| 234 | + |
| 235 | + if states.len() != 1 { |
| 236 | + return internal_err!("expects single state"); |
| 237 | + } |
| 238 | + |
| 239 | + states[0] |
| 240 | + .as_list::<i32>() |
| 241 | + .iter() |
| 242 | + .flatten() |
| 243 | + .try_for_each(|val| self.update_batch(&[val])) |
| 244 | + } |
| 245 | + |
| 246 | + fn evaluate(&mut self) -> Result<ScalarValue> { |
| 247 | + let values: Vec<ScalarValue> = self.values.iter().cloned().collect(); |
| 248 | + if values.is_empty() { |
| 249 | + return Ok(ScalarValue::new_null_list(self.datatype.clone(), true, 1)); |
| 250 | + } |
| 251 | + let arr = ScalarValue::new_list(&values, &self.datatype, true); |
| 252 | + Ok(ScalarValue::List(arr)) |
| 253 | + } |
| 254 | + |
| 255 | + fn size(&self) -> usize { |
| 256 | + std::mem::size_of_val(self) + ScalarValue::size_of_hashset(&self.values) |
| 257 | + - std::mem::size_of_val(&self.values) |
| 258 | + + self.datatype.size() |
| 259 | + - std::mem::size_of_val(&self.datatype) |
| 260 | + } |
| 261 | +} |
0 commit comments