|
| 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 | +//! [`DictionaryGroupValueBuilder`] for dictionary-encoded GROUP BY columns. |
| 19 | +
|
| 20 | +use std::marker::PhantomData; |
| 21 | + |
| 22 | +use arrow::array::{Array, ArrayRef, DictionaryArray, new_null_array}; |
| 23 | +use arrow::datatypes::{ArrowDictionaryKeyType, ArrowNativeType, DataType}; |
| 24 | +use datafusion_common::Result; |
| 25 | + |
| 26 | +use super::GroupColumn; |
| 27 | + |
| 28 | +/// A [`GroupColumn`] wrapper that transparently handles dictionary-encoded |
| 29 | +/// input arrays by resolving dictionary keys on-demand. |
| 30 | +/// |
| 31 | +/// Instead of materializing the full decoded array via `cast()` (which copies |
| 32 | +/// O(batch_size) strings per batch), this builder looks up values through |
| 33 | +/// dictionary keys, only copying data for rows that are actually appended as |
| 34 | +/// new groups. Comparisons index directly into the dictionary's values array. |
| 35 | +/// |
| 36 | +/// The inner builder stores decoded values. On emit, the existing code in |
| 37 | +/// [`GroupValuesColumn::emit`] re-encodes back to dictionary via `cast()`. |
| 38 | +/// |
| 39 | +/// [`GroupValuesColumn::emit`]: super::GroupValuesColumn |
| 40 | +pub struct DictionaryGroupValueBuilder<K: ArrowDictionaryKeyType> { |
| 41 | + /// Inner builder that operates on the dictionary's value type |
| 42 | + inner: Box<dyn GroupColumn>, |
| 43 | + /// A single-element null array of the value type, used to represent null |
| 44 | + /// dictionary keys to the inner builder |
| 45 | + null_array: ArrayRef, |
| 46 | + _phantom: PhantomData<K>, |
| 47 | +} |
| 48 | + |
| 49 | +impl<K: ArrowDictionaryKeyType> DictionaryGroupValueBuilder<K> { |
| 50 | + pub fn new(inner: Box<dyn GroupColumn>, value_type: &DataType) -> Self { |
| 51 | + let null_array = new_null_array(value_type, 1); |
| 52 | + Self { |
| 53 | + inner, |
| 54 | + null_array, |
| 55 | + _phantom: PhantomData, |
| 56 | + } |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +impl<K: ArrowDictionaryKeyType + Send + Sync> GroupColumn for DictionaryGroupValueBuilder<K> { |
| 61 | + fn equal_to(&self, lhs_row: usize, array: &ArrayRef, rhs_row: usize) -> bool { |
| 62 | + let dict = array |
| 63 | + .as_any() |
| 64 | + .downcast_ref::<DictionaryArray<K>>() |
| 65 | + .unwrap(); |
| 66 | + if dict.is_null(rhs_row) { |
| 67 | + return self.inner.equal_to(lhs_row, &self.null_array, 0); |
| 68 | + } |
| 69 | + let key = dict.keys().value(rhs_row).as_usize(); |
| 70 | + self.inner.equal_to(lhs_row, dict.values(), key) |
| 71 | + } |
| 72 | + |
| 73 | + fn append_val(&mut self, array: &ArrayRef, row: usize) -> Result<()> { |
| 74 | + let dict = array |
| 75 | + .as_any() |
| 76 | + .downcast_ref::<DictionaryArray<K>>() |
| 77 | + .unwrap(); |
| 78 | + if dict.is_null(row) { |
| 79 | + return self.inner.append_val(&self.null_array, 0); |
| 80 | + } |
| 81 | + let key = dict.keys().value(row).as_usize(); |
| 82 | + self.inner.append_val(dict.values(), key) |
| 83 | + } |
| 84 | + |
| 85 | + fn vectorized_equal_to( |
| 86 | + &self, |
| 87 | + lhs_rows: &[usize], |
| 88 | + array: &ArrayRef, |
| 89 | + rhs_rows: &[usize], |
| 90 | + equal_to_results: &mut [bool], |
| 91 | + ) { |
| 92 | + let dict = array |
| 93 | + .as_any() |
| 94 | + .downcast_ref::<DictionaryArray<K>>() |
| 95 | + .unwrap(); |
| 96 | + let keys = dict.keys(); |
| 97 | + let values = dict.values(); |
| 98 | + |
| 99 | + if dict.null_count() == 0 { |
| 100 | + // Fast path: no null keys, remap indices and delegate to inner |
| 101 | + let mapped_rhs: Vec<usize> = rhs_rows |
| 102 | + .iter() |
| 103 | + .map(|&row| keys.value(row).as_usize()) |
| 104 | + .collect(); |
| 105 | + self.inner |
| 106 | + .vectorized_equal_to(lhs_rows, values, &mapped_rhs, equal_to_results); |
| 107 | + } else { |
| 108 | + // Null keys present: fall back to scalar comparison |
| 109 | + for (i, (&lhs_row, &rhs_row)) in |
| 110 | + lhs_rows.iter().zip(rhs_rows.iter()).enumerate() |
| 111 | + { |
| 112 | + if !equal_to_results[i] { |
| 113 | + continue; |
| 114 | + } |
| 115 | + if dict.is_null(rhs_row) { |
| 116 | + equal_to_results[i] = |
| 117 | + self.inner.equal_to(lhs_row, &self.null_array, 0); |
| 118 | + } else { |
| 119 | + let key = keys.value(rhs_row).as_usize(); |
| 120 | + equal_to_results[i] = |
| 121 | + self.inner.equal_to(lhs_row, values, key); |
| 122 | + } |
| 123 | + } |
| 124 | + } |
| 125 | + } |
| 126 | + |
| 127 | + fn vectorized_append(&mut self, array: &ArrayRef, rows: &[usize]) -> Result<()> { |
| 128 | + let dict = array |
| 129 | + .as_any() |
| 130 | + .downcast_ref::<DictionaryArray<K>>() |
| 131 | + .unwrap(); |
| 132 | + let keys = dict.keys(); |
| 133 | + let values = dict.values(); |
| 134 | + |
| 135 | + if dict.null_count() == 0 { |
| 136 | + // Fast path: no null keys, remap indices and delegate to inner |
| 137 | + let mapped_rows: Vec<usize> = rows |
| 138 | + .iter() |
| 139 | + .map(|&row| keys.value(row).as_usize()) |
| 140 | + .collect(); |
| 141 | + self.inner.vectorized_append(values, &mapped_rows) |
| 142 | + } else { |
| 143 | + // Null keys present: process in order, chunking consecutive |
| 144 | + // non-null rows for vectorized processing |
| 145 | + let mut i = 0; |
| 146 | + while i < rows.len() { |
| 147 | + if dict.is_null(rows[i]) { |
| 148 | + self.inner.append_val(&self.null_array, 0)?; |
| 149 | + i += 1; |
| 150 | + } else { |
| 151 | + // Collect consecutive non-null rows |
| 152 | + let mut chunk = Vec::new(); |
| 153 | + while i < rows.len() && !dict.is_null(rows[i]) { |
| 154 | + chunk.push(keys.value(rows[i]).as_usize()); |
| 155 | + i += 1; |
| 156 | + } |
| 157 | + self.inner.vectorized_append(values, &chunk)?; |
| 158 | + } |
| 159 | + } |
| 160 | + Ok(()) |
| 161 | + } |
| 162 | + } |
| 163 | + |
| 164 | + fn len(&self) -> usize { |
| 165 | + self.inner.len() |
| 166 | + } |
| 167 | + |
| 168 | + fn size(&self) -> usize { |
| 169 | + self.inner.size() + self.null_array.get_array_memory_size() |
| 170 | + } |
| 171 | + |
| 172 | + fn build(self: Box<Self>) -> ArrayRef { |
| 173 | + self.inner.build() |
| 174 | + } |
| 175 | + |
| 176 | + fn take_n(&mut self, n: usize) -> ArrayRef { |
| 177 | + self.inner.take_n(n) |
| 178 | + } |
| 179 | +} |
0 commit comments