forked from apache/datafusion
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdistinct_expressions.rs
746 lines (636 loc) · 24 KB
/
distinct_expressions.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//! Implementations for DISTINCT expressions, e.g. `COUNT(DISTINCT c)`
use std::any::Any;
use std::convert::TryFrom;
use std::fmt::Debug;
use std::hash::Hash;
use std::sync::Arc;
use arrow::datatypes::{DataType, Field};
use crate::error::{DataFusionError, Result};
use crate::physical_plan::group_scalar::GroupByScalar;
use crate::physical_plan::groups_accumulator::GroupsAccumulator;
use crate::physical_plan::groups_accumulator_flat_adapter::GroupsAccumulatorFlatAdapter;
use crate::physical_plan::{Accumulator, AggregateExpr, PhysicalExpr};
use crate::scalar::ScalarValue;
use itertools::Itertools;
use smallvec::SmallVec;
use std::collections::hash_map::RandomState;
use std::collections::HashSet;
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
struct DistinctScalarValues(Vec<GroupByScalar>);
fn format_state_name(name: &str, state_name: &str) -> String {
format!("{}[{}]", name, state_name)
}
/// Expression for a COUNT(DISTINCT) aggregation.
#[derive(Debug)]
pub struct DistinctCount {
/// Column name
name: String,
/// The DataType for the final count
data_type: DataType,
/// The DataType used to hold the state for each input
state_data_types: Vec<DataType>,
/// The input arguments
exprs: Vec<Arc<dyn PhysicalExpr>>,
}
impl DistinctCount {
/// Create a new COUNT(DISTINCT) aggregate function.
pub fn new(
input_data_types: Vec<DataType>,
exprs: Vec<Arc<dyn PhysicalExpr>>,
name: String,
data_type: DataType,
) -> Self {
let state_data_types = input_data_types.into_iter().map(state_type).collect();
Self {
name,
data_type,
state_data_types,
exprs,
}
}
}
/// return the type to use to accumulate state for the specified input type
fn state_type(data_type: DataType) -> DataType {
match data_type {
// when aggregating dictionary values, use the underlying value type
DataType::Dictionary(_key_type, value_type) => *value_type,
t => t,
}
}
impl AggregateExpr for DistinctCount {
/// Return a reference to Any that can be used for downcasting
fn as_any(&self) -> &dyn Any {
self
}
fn field(&self) -> Result<Field> {
Ok(Field::new(&self.name, self.data_type.clone(), true))
}
fn state_fields(&self) -> Result<Vec<Field>> {
Ok(self
.state_data_types
.iter()
.map(|state_data_type| {
Field::new(
&format_state_name(&self.name, "count distinct"),
DataType::List(Box::new(Field::new(
"item",
state_data_type.clone(),
true,
))),
false,
)
})
.collect::<Vec<_>>())
}
fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
self.exprs.clone()
}
fn create_accumulator(&self) -> Result<Box<dyn Accumulator>> {
Ok(Box::new(DistinctCountAccumulator {
values: HashSet::default(),
state_data_types: self.state_data_types.clone(),
count_data_type: self.data_type.clone(),
}))
}
fn uses_groups_accumulator(&self) -> bool {
return true;
}
fn create_groups_accumulator(
&self,
) -> arrow::error::Result<Option<Box<dyn GroupsAccumulator>>> {
let state_data_types = self.state_data_types.clone();
let count_data_type = self.data_type.clone();
Ok(Some(Box::new(GroupsAccumulatorFlatAdapter::<
DistinctCountAccumulator,
>::new(move || {
Ok(DistinctCountAccumulator {
values: HashSet::default(),
state_data_types: state_data_types.clone(),
count_data_type: count_data_type.clone(),
})
}))))
}
fn name(&self) -> &str {
&self.name
}
}
#[derive(Debug)]
struct DistinctCountAccumulator {
values: HashSet<DistinctScalarValues, RandomState>,
state_data_types: Vec<DataType>,
count_data_type: DataType,
}
impl Accumulator for DistinctCountAccumulator {
fn reset(&mut self) {
self.values.clear();
}
fn update(&mut self, values: &[ScalarValue]) -> Result<()> {
// If a row has a NULL, it is not included in the final count.
if !values.iter().any(|v| v.is_null()) {
self.values.insert(DistinctScalarValues(
values
.iter()
.map(GroupByScalar::try_from)
.collect::<Result<Vec<_>>>()?,
));
}
Ok(())
}
fn merge(&mut self, states: &[ScalarValue]) -> Result<()> {
if states.is_empty() {
return Ok(());
}
let col_values = states
.iter()
.map(|state| match state {
ScalarValue::List(Some(values), _) => Ok(values),
_ => Err(DataFusionError::Internal(format!(
"Unexpected accumulator state {:?}",
state
))),
})
.collect::<Result<Vec<_>>>()?;
(0..col_values[0].len()).try_for_each(|row_index| {
let row_values = col_values
.iter()
.map(|col| col[row_index].clone())
.collect::<Vec<_>>();
self.update(&row_values)
})
}
fn state(&self) -> Result<SmallVec<[ScalarValue; 2]>> {
let mut cols_out = self
.state_data_types
.iter()
.map(|state_data_type| {
let values = Box::new(Vec::new());
let data_type = Box::new(state_data_type.clone());
ScalarValue::List(Some(values), data_type)
})
.collect::<SmallVec<_>>();
let mut cols_vec = cols_out
.iter_mut()
.map(|c| match c {
ScalarValue::List(Some(ref mut v), _) => v,
_ => unreachable!(),
})
.collect::<Vec<_>>();
self.values.iter().unique().for_each(|distinct_values| {
distinct_values.0.iter().enumerate().for_each(
|(col_index, distinct_value)| {
cols_vec[col_index].push(
distinct_value.to_scalar(&self.state_data_types[col_index]),
);
},
)
});
Ok(cols_out)
}
fn evaluate(&self) -> Result<ScalarValue> {
match &self.count_data_type {
DataType::UInt64 => Ok(ScalarValue::UInt64(Some(
self.values.iter().unique().count() as u64,
))),
t => Err(DataFusionError::Internal(format!(
"Invalid data type {:?} for count distinct aggregation",
t
))),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use arrow::array::{
ArrayRef, BooleanArray, Float32Array, Float64Array, Int16Array, Int32Array,
Int64Array, Int8Array, ListArray, UInt16Array, UInt32Array, UInt64Array,
UInt8Array,
};
use arrow::array::{Int32Builder, ListBuilder, UInt64Builder};
use arrow::datatypes::DataType;
macro_rules! build_list {
($LISTS:expr, $BUILDER_TYPE:ident) => {{
let mut builder = ListBuilder::new($BUILDER_TYPE::new(0));
for list in $LISTS.iter() {
match list {
Some(values) => {
for value in values.iter() {
match value {
Some(v) => builder.values().append_value((*v).into())?,
None => builder.values().append_null()?,
}
}
builder.append(true)?;
}
None => {
builder.append(false)?;
}
}
}
let array = Arc::new(builder.finish()) as ArrayRef;
Ok(array) as Result<ArrayRef>
}};
}
macro_rules! state_to_vec {
($LIST:expr, $DATA_TYPE:ident, $PRIM_TY:ty) => {{
match $LIST {
ScalarValue::List(_, data_type) => match data_type.as_ref() {
&DataType::$DATA_TYPE => (),
_ => panic!("Unexpected DataType for list"),
},
_ => panic!("Expected a ScalarValue::List"),
}
match $LIST {
ScalarValue::List(None, _) => None,
ScalarValue::List(Some(scalar_values), _) => {
let vec = scalar_values
.iter()
.map(|scalar_value| match scalar_value {
ScalarValue::$DATA_TYPE(value) => *value,
_ => panic!("Unexpected ScalarValue variant"),
})
.collect::<Vec<Option<$PRIM_TY>>>();
Some(vec)
}
_ => unreachable!(),
}
}};
}
fn collect_states<T: Ord + Clone, S: Ord + Clone>(
state1: &[Option<T>],
state2: &[Option<S>],
) -> Vec<(Option<T>, Option<S>)> {
let mut states = state1
.iter()
.zip(state2.iter())
.map(|(l, r)| (l.clone(), r.clone()))
.collect::<Vec<(Option<T>, Option<S>)>>();
states.sort();
states
}
fn run_update_batch(arrays: &[ArrayRef]) -> Result<(Vec<ScalarValue>, ScalarValue)> {
let agg = DistinctCount::new(
arrays
.iter()
.map(|a| a.data_type().clone())
.collect::<Vec<_>>(),
vec![],
String::from("__col_name__"),
DataType::UInt64,
);
let mut accum = agg.create_accumulator()?;
accum.update_batch(arrays)?;
Ok((accum.state()?.to_vec(), accum.evaluate()?))
}
fn run_update(
data_types: &[DataType],
rows: &[Vec<ScalarValue>],
) -> Result<(Vec<ScalarValue>, ScalarValue)> {
let agg = DistinctCount::new(
data_types.to_vec(),
vec![],
String::from("__col_name__"),
DataType::UInt64,
);
let mut accum = agg.create_accumulator()?;
for row in rows.iter() {
accum.update(row)?
}
Ok((accum.state()?.to_vec(), accum.evaluate()?))
}
fn run_merge_batch(arrays: &[ArrayRef]) -> Result<(Vec<ScalarValue>, ScalarValue)> {
let agg = DistinctCount::new(
arrays
.iter()
.map(|a| a.as_any().downcast_ref::<ListArray>().unwrap())
.map(|a| a.values().data_type().clone())
.collect::<Vec<_>>(),
vec![],
String::from("__col_name__"),
DataType::UInt64,
);
let mut accum = agg.create_accumulator()?;
accum.merge_batch(arrays)?;
Ok((accum.state()?.to_vec(), accum.evaluate()?))
}
macro_rules! test_count_distinct_update_batch_numeric {
($ARRAY_TYPE:ident, $DATA_TYPE:ident, $PRIM_TYPE:ty) => {{
let values: Vec<Option<$PRIM_TYPE>> = vec![
Some(1),
Some(1),
None,
Some(3),
Some(2),
None,
Some(2),
Some(3),
Some(1),
];
let arrays = vec![Arc::new($ARRAY_TYPE::from(values)) as ArrayRef];
let (states, result) = run_update_batch(&arrays)?;
let mut state_vec =
state_to_vec!(&states[0], $DATA_TYPE, $PRIM_TYPE).unwrap();
state_vec.sort();
assert_eq!(states.len(), 1);
assert_eq!(state_vec, vec![Some(1), Some(2), Some(3)]);
assert_eq!(result, ScalarValue::UInt64(Some(3)));
Ok(())
}};
}
//Used trait to create associated constant for f32 and f64
trait SubNormal: 'static {
const SUBNORMAL: Self;
}
impl SubNormal for f64 {
const SUBNORMAL: Self = 1.0e-308_f64;
}
impl SubNormal for f32 {
const SUBNORMAL: Self = 1.0e-38_f32;
}
macro_rules! test_count_distinct_update_batch_floating_point {
($ARRAY_TYPE:ident, $DATA_TYPE:ident, $PRIM_TYPE:ty) => {{
use ordered_float::OrderedFloat;
let values: Vec<Option<$PRIM_TYPE>> = vec![
Some(<$PRIM_TYPE>::INFINITY),
Some(<$PRIM_TYPE>::NAN),
Some(1.0),
Some(<$PRIM_TYPE as SubNormal>::SUBNORMAL),
Some(1.0),
Some(<$PRIM_TYPE>::INFINITY),
None,
Some(3.0),
Some(-4.5),
Some(2.0),
None,
Some(2.0),
Some(3.0),
Some(<$PRIM_TYPE>::NEG_INFINITY),
Some(1.0),
Some(<$PRIM_TYPE>::NAN),
Some(<$PRIM_TYPE>::NEG_INFINITY),
];
let arrays = vec![Arc::new($ARRAY_TYPE::from(values)) as ArrayRef];
let (states, result) = run_update_batch(&arrays)?;
let mut state_vec =
state_to_vec!(&states[0], $DATA_TYPE, $PRIM_TYPE).unwrap();
state_vec.sort_by(|a, b| match (a, b) {
(Some(lhs), Some(rhs)) => {
OrderedFloat::from(*lhs).cmp(&OrderedFloat::from(*rhs))
}
_ => a.partial_cmp(b).unwrap(),
});
let nan_idx = state_vec.len() - 1;
assert_eq!(states.len(), 1);
assert_eq!(
&state_vec[..nan_idx],
vec![
Some(<$PRIM_TYPE>::NEG_INFINITY),
Some(-4.5),
Some(<$PRIM_TYPE as SubNormal>::SUBNORMAL),
Some(1.0),
Some(2.0),
Some(3.0),
Some(<$PRIM_TYPE>::INFINITY)
]
);
assert!(state_vec[nan_idx].unwrap_or_default().is_nan());
assert_eq!(result, ScalarValue::UInt64(Some(8)));
Ok(())
}};
}
#[test]
fn count_distinct_update_batch_i8() -> Result<()> {
test_count_distinct_update_batch_numeric!(Int8Array, Int8, i8)
}
#[test]
fn count_distinct_update_batch_i16() -> Result<()> {
test_count_distinct_update_batch_numeric!(Int16Array, Int16, i16)
}
#[test]
fn count_distinct_update_batch_i32() -> Result<()> {
test_count_distinct_update_batch_numeric!(Int32Array, Int32, i32)
}
#[test]
fn count_distinct_update_batch_i64() -> Result<()> {
test_count_distinct_update_batch_numeric!(Int64Array, Int64, i64)
}
#[test]
fn count_distinct_update_batch_u8() -> Result<()> {
test_count_distinct_update_batch_numeric!(UInt8Array, UInt8, u8)
}
#[test]
fn count_distinct_update_batch_u16() -> Result<()> {
test_count_distinct_update_batch_numeric!(UInt16Array, UInt16, u16)
}
#[test]
fn count_distinct_update_batch_u32() -> Result<()> {
test_count_distinct_update_batch_numeric!(UInt32Array, UInt32, u32)
}
#[test]
fn count_distinct_update_batch_u64() -> Result<()> {
test_count_distinct_update_batch_numeric!(UInt64Array, UInt64, u64)
}
#[test]
fn count_distinct_update_batch_f32() -> Result<()> {
test_count_distinct_update_batch_floating_point!(Float32Array, Float32, f32)
}
#[test]
fn count_distinct_update_batch_f64() -> Result<()> {
test_count_distinct_update_batch_floating_point!(Float64Array, Float64, f64)
}
#[test]
fn count_distinct_update_batch_boolean() -> Result<()> {
let get_count = |data: BooleanArray| -> Result<(Vec<Option<bool>>, u64)> {
let arrays = vec![Arc::new(data) as ArrayRef];
let (states, result) = run_update_batch(&arrays)?;
let mut state_vec = state_to_vec!(&states[0], Boolean, bool).unwrap();
state_vec.sort();
let count = match result {
ScalarValue::UInt64(c) => c.ok_or_else(|| {
DataFusionError::Internal("Found None count".to_string())
}),
scalar => Err(DataFusionError::Internal(format!(
"Found non Uint64 scalar value from count: {}",
scalar
))),
}?;
Ok((state_vec, count))
};
let zero_count_values = BooleanArray::from(Vec::<bool>::new());
let one_count_values = BooleanArray::from(vec![false, false]);
let one_count_values_with_null =
BooleanArray::from(vec![Some(true), Some(true), None, None]);
let two_count_values = BooleanArray::from(vec![true, false, true, false, true]);
let two_count_values_with_null = BooleanArray::from(vec![
Some(true),
Some(false),
None,
None,
Some(true),
Some(false),
]);
assert_eq!(
get_count(zero_count_values)?,
(Vec::<Option<bool>>::new(), 0)
);
assert_eq!(get_count(one_count_values)?, (vec![Some(false)], 1));
assert_eq!(
get_count(one_count_values_with_null)?,
(vec![Some(true)], 1)
);
assert_eq!(
get_count(two_count_values)?,
(vec![Some(false), Some(true)], 2)
);
assert_eq!(
get_count(two_count_values_with_null)?,
(vec![Some(false), Some(true)], 2)
);
Ok(())
}
#[test]
fn count_distinct_update_batch_all_nulls() -> Result<()> {
let arrays = vec![Arc::new(Int32Array::from(
vec![None, None, None, None] as Vec<Option<i32>>
)) as ArrayRef];
let (states, result) = run_update_batch(&arrays)?;
assert_eq!(states.len(), 1);
assert_eq!(state_to_vec!(&states[0], Int32, i32), Some(vec![]));
assert_eq!(result, ScalarValue::UInt64(Some(0)));
Ok(())
}
#[test]
fn count_distinct_update_batch_empty() -> Result<()> {
let arrays =
vec![Arc::new(Int32Array::from(vec![] as Vec<Option<i32>>)) as ArrayRef];
let (states, result) = run_update_batch(&arrays)?;
assert_eq!(states.len(), 1);
assert_eq!(state_to_vec!(&states[0], Int32, i32), Some(vec![]));
assert_eq!(result, ScalarValue::UInt64(Some(0)));
Ok(())
}
#[test]
fn count_distinct_update_batch_multiple_columns() -> Result<()> {
let array_int8: ArrayRef = Arc::new(Int8Array::from(vec![1, 1, 2]));
let array_int16: ArrayRef = Arc::new(Int16Array::from(vec![3, 3, 4]));
let arrays = vec![array_int8, array_int16];
let (states, result) = run_update_batch(&arrays)?;
let state_vec1 = state_to_vec!(&states[0], Int8, i8).unwrap();
let state_vec2 = state_to_vec!(&states[1], Int16, i16).unwrap();
let state_pairs = collect_states::<i8, i16>(&state_vec1, &state_vec2);
assert_eq!(states.len(), 2);
assert_eq!(
state_pairs,
vec![(Some(1_i8), Some(3_i16)), (Some(2_i8), Some(4_i16))]
);
assert_eq!(result, ScalarValue::UInt64(Some(2)));
Ok(())
}
#[test]
fn count_distinct_update() -> Result<()> {
let (states, result) = run_update(
&[DataType::Int32, DataType::UInt64],
&[
vec![ScalarValue::Int32(Some(-1)), ScalarValue::UInt64(Some(5))],
vec![ScalarValue::Int32(Some(5)), ScalarValue::UInt64(Some(1))],
vec![ScalarValue::Int32(Some(-1)), ScalarValue::UInt64(Some(5))],
vec![ScalarValue::Int32(Some(5)), ScalarValue::UInt64(Some(1))],
vec![ScalarValue::Int32(Some(-1)), ScalarValue::UInt64(Some(6))],
vec![ScalarValue::Int32(Some(-1)), ScalarValue::UInt64(Some(7))],
vec![ScalarValue::Int32(Some(2)), ScalarValue::UInt64(Some(7))],
],
)?;
let state_vec1 = state_to_vec!(&states[0], Int32, i32).unwrap();
let state_vec2 = state_to_vec!(&states[1], UInt64, u64).unwrap();
let state_pairs = collect_states::<i32, u64>(&state_vec1, &state_vec2);
assert_eq!(states.len(), 2);
assert_eq!(
state_pairs,
vec![
(Some(-1_i32), Some(5_u64)),
(Some(-1_i32), Some(6_u64)),
(Some(-1_i32), Some(7_u64)),
(Some(2_i32), Some(7_u64)),
(Some(5_i32), Some(1_u64)),
]
);
assert_eq!(result, ScalarValue::UInt64(Some(5)));
Ok(())
}
#[test]
fn count_distinct_update_with_nulls() -> Result<()> {
let (states, result) = run_update(
&[DataType::Int32, DataType::UInt64],
&[
// None of these updates contains a None, so these are accumulated.
vec![ScalarValue::Int32(Some(-1)), ScalarValue::UInt64(Some(5))],
vec![ScalarValue::Int32(Some(-1)), ScalarValue::UInt64(Some(5))],
vec![ScalarValue::Int32(Some(-2)), ScalarValue::UInt64(Some(5))],
// Each of these updates contains at least one None, so these
// won't be accumulated.
vec![ScalarValue::Int32(Some(-1)), ScalarValue::UInt64(None)],
vec![ScalarValue::Int32(None), ScalarValue::UInt64(Some(5))],
vec![ScalarValue::Int32(None), ScalarValue::UInt64(None)],
],
)?;
let state_vec1 = state_to_vec!(&states[0], Int32, i32).unwrap();
let state_vec2 = state_to_vec!(&states[1], UInt64, u64).unwrap();
let state_pairs = collect_states::<i32, u64>(&state_vec1, &state_vec2);
assert_eq!(states.len(), 2);
assert_eq!(
state_pairs,
vec![(Some(-2_i32), Some(5_u64)), (Some(-1_i32), Some(5_u64))]
);
assert_eq!(result, ScalarValue::UInt64(Some(2)));
Ok(())
}
#[test]
fn count_distinct_merge_batch() -> Result<()> {
let state_in1 = build_list!(
vec![
Some(vec![Some(-1_i32), Some(-1_i32), Some(-2_i32), Some(-2_i32)]),
Some(vec![Some(-2_i32), Some(-3_i32)]),
],
Int32Builder
)?;
let state_in2 = build_list!(
vec![
Some(vec![Some(5_u64), Some(6_u64), Some(5_u64), Some(7_u64)]),
Some(vec![Some(5_u64), Some(7_u64)]),
],
UInt64Builder
)?;
let (states, result) = run_merge_batch(&[state_in1, state_in2])?;
let state_out_vec1 = state_to_vec!(&states[0], Int32, i32).unwrap();
let state_out_vec2 = state_to_vec!(&states[1], UInt64, u64).unwrap();
let state_pairs = collect_states::<i32, u64>(&state_out_vec1, &state_out_vec2);
assert_eq!(
state_pairs,
vec![
(Some(-3_i32), Some(7_u64)),
(Some(-2_i32), Some(5_u64)),
(Some(-2_i32), Some(7_u64)),
(Some(-1_i32), Some(5_u64)),
(Some(-1_i32), Some(6_u64)),
]
);
assert_eq!(result, ScalarValue::UInt64(Some(5)));
Ok(())
}
}