forked from apache/datafusion
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmerge_sort.rs
More file actions
1344 lines (1211 loc) · 40.7 KB
/
merge_sort.rs
File metadata and controls
1344 lines (1211 loc) · 40.7 KB
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
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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.
//! Merge Sort implementation
use std::any::Any;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use futures::stream::{Fuse, Stream};
use futures::StreamExt;
use arrow::array::{build_compare, ArrayRef, BooleanArray, DynComparator};
pub use arrow::compute::SortOptions;
use arrow::compute::{
filter_record_batch, lexsort_to_indices, take, SortColumn, TakeOptions,
};
use arrow::datatypes::SchemaRef;
use arrow::error::Result as ArrowResult;
use arrow::record_batch::RecordBatch;
use super::{RecordBatchStream, SendableRecordBatchStream};
use crate::error::{DataFusionError, Result};
use crate::physical_plan::{ExecutionPlan, OptimizerHints, Partitioning};
use crate::cube_ext::util::{cmp_array_row_same_types, lexcmp_array_rows};
use crate::physical_plan::expressions::Column;
use crate::physical_plan::memory::MemoryStream;
use arrow::array::{make_array, MutableArrayData};
use async_trait::async_trait;
use futures::future::join_all;
use std::cmp::{Ordering, Reverse};
use std::collections::BinaryHeap;
/// Sort execution plan
#[derive(Debug)]
pub struct MergeSortExec {
input: Arc<dyn ExecutionPlan>,
/// Columns to sort on
pub columns: Vec<Column>,
}
impl MergeSortExec {
/// Create a new sort execution plan
pub fn try_new(input: Arc<dyn ExecutionPlan>, columns: Vec<Column>) -> Result<Self> {
if columns.is_empty() {
return Err(DataFusionError::Internal(
"Empty columns passed for MergeSortExec".to_string(),
));
}
Ok(Self { input, columns })
}
/// Input execution plan
pub fn input(&self) -> &Arc<dyn ExecutionPlan> {
&self.input
}
}
#[async_trait]
impl ExecutionPlan for MergeSortExec {
fn as_any(&self) -> &dyn Any {
self
}
fn schema(&self) -> SchemaRef {
self.input.schema()
}
fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {
vec![self.input.clone()]
}
fn output_partitioning(&self) -> Partitioning {
Partitioning::UnknownPartitioning(1)
}
fn with_new_children(
&self,
children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {
Ok(Arc::new(MergeSortExec::try_new(
children[0].clone(),
self.columns.clone(),
)?))
}
fn output_hints(&self) -> OptimizerHints {
OptimizerHints {
single_value_columns: self.input.output_hints().single_value_columns,
sort_order: Some(self.columns.iter().map(|c| c.index()).collect()),
}
}
async fn execute(&self, partition: usize) -> Result<SendableRecordBatchStream> {
if 0 != partition {
return Err(DataFusionError::Internal(format!(
"MergeSortExec invalid partition {}",
partition
)));
}
let inputs = join_all(
(0..self.input.output_partitioning().partition_count())
.map(|i| self.input.execute(i))
.collect::<Vec<_>>(),
)
.await
.into_iter()
.collect::<Result<Vec<_>>>()?;
if inputs.len() == 1 {
return Ok(inputs.into_iter().next().unwrap());
}
Ok(Box::pin(MergeSortStream::new(
self.input.schema(),
inputs,
self.columns.clone(),
)))
}
}
/// Sort execution plan to resort merge join results
#[derive(Debug)]
pub struct MergeReSortExec {
input: Arc<dyn ExecutionPlan>,
columns: Vec<Column>,
}
impl MergeReSortExec {
/// Create a new sort execution plan
pub fn try_new(input: Arc<dyn ExecutionPlan>, columns: Vec<Column>) -> Result<Self> {
Ok(Self { input, columns })
}
}
#[async_trait]
impl ExecutionPlan for MergeReSortExec {
fn as_any(&self) -> &dyn Any {
self
}
fn schema(&self) -> SchemaRef {
self.input.schema()
}
fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {
vec![self.input.clone()]
}
fn output_partitioning(&self) -> Partitioning {
Partitioning::UnknownPartitioning(1)
}
fn with_new_children(
&self,
children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {
Ok(Arc::new(MergeReSortExec::try_new(
children[0].clone(),
self.columns.clone(),
)?))
}
async fn execute(&self, partition: usize) -> Result<SendableRecordBatchStream> {
if 0 != partition {
return Err(DataFusionError::Internal(format!(
"MergeReSortExec invalid partition {}",
partition
)));
}
if 1 != self.input.output_partitioning().partition_count() {
return Err(DataFusionError::Internal(format!(
"MergeReSortExec expects only one partition but got {}",
self.input.output_partitioning().partition_count()
)));
}
let stream = self.input.execute(0).await?;
let all_batches = stream
.collect::<Vec<_>>()
.await
.into_iter()
.collect::<ArrowResult<Vec<_>>>()?;
let schema = self.input.schema();
let sorted_batches = all_batches
.into_iter()
.map(|b| -> Result<SendableRecordBatchStream> {
Ok(Box::pin(MemoryStream::try_new(
vec![sort_batch(&self.columns, &schema, b)?],
schema.clone(),
None,
)?))
})
.collect::<Result<Vec<_>>>()?;
Ok(Box::pin(MergeSortStream::new(
self.input.schema(),
sorted_batches,
self.columns.clone(),
)))
}
}
fn sort_batch(
columns: &Vec<Column>,
schema: &SchemaRef,
batch: RecordBatch,
) -> ArrowResult<RecordBatch> {
let columns_to_sort = columns
.iter()
.map(|c| -> ArrowResult<SortColumn> {
Ok(SortColumn {
values: batch.column(c.index()).clone(),
options: None,
})
})
.collect::<ArrowResult<Vec<_>>>()?;
let indices = lexsort_to_indices(columns_to_sort.as_slice(), None)?;
RecordBatch::try_new(
schema.clone(),
batch
.columns()
.iter()
.map(|column| {
take(
column.as_ref(),
&indices,
// disable bound check overhead since indices are already generated from
// the same record batch
Some(TakeOptions {
check_bounds: false,
}),
)
})
.collect::<ArrowResult<Vec<ArrayRef>>>()?,
)
}
struct MergeSortStream {
schema: SchemaRef,
columns: Vec<Column>,
poll_states: Vec<MergeSortStreamState>,
}
impl MergeSortStream {
fn new(
schema: SchemaRef,
inputs: Vec<SendableRecordBatchStream>,
columns: Vec<Column>,
) -> Self {
Self {
schema,
columns,
poll_states: inputs
.into_iter()
.map(|stream| MergeSortStreamState::new(stream))
.collect(),
}
}
}
struct MergeSortStreamState {
stream: Fuse<SendableRecordBatchStream>,
poll_state: Poll<Option<ArrowResult<(usize, RecordBatch)>>>,
}
impl MergeSortStreamState {
fn new(stream: SendableRecordBatchStream) -> Self {
Self {
stream: stream.fuse(),
poll_state: Poll::Pending,
}
}
pub fn update_state(&mut self, cx: &mut std::task::Context<'_>) {
if !self.poll_state.is_pending() {
return;
}
let inner = self.stream.poll_next_unpin(cx);
match inner {
// skip empty batches and wait for the next poll.
Poll::Ready(Some(Ok(b))) if b.num_rows() == 0 => {
cx.waker().wake_by_ref();
return;
}
_ => {}
}
self.poll_state = inner.map(|option| match option {
Some(batch) => Some(batch.map(|b| (0, b))),
None => None,
});
}
pub fn take_batch(&mut self) -> Option<ArrowResult<(usize, RecordBatch)>> {
let mut res = Poll::Pending;
std::mem::swap(&mut res, &mut self.poll_state);
if let Poll::Ready(option) = &mut res {
option.take()
} else {
panic!(
"Invalid merge sort state: unexpected empty state: {:?}",
self.poll_state
);
}
}
pub fn update_batch(&mut self, new_cursor: usize, batch: RecordBatch) {
if let Poll::Ready(_) = self.poll_state {
panic!(
"Invalid merge sort state: unexpected ready state: {:?}",
self.poll_state
);
} else {
self.poll_state = if new_cursor == batch.num_rows() {
Poll::Pending
} else {
Poll::Ready(Some(Ok((new_cursor, batch))))
}
}
}
}
impl Stream for MergeSortStream {
type Item = ArrowResult<RecordBatch>;
fn poll_next(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
for state in self.poll_states.iter_mut() {
state.update_state(cx);
}
// TODO: pass the value from ExecutionConfig.
const MAX_BATCH_ROWS: usize = 4096;
if self.poll_states.iter().all(|s| s.poll_state.is_ready()) {
let res = self
.poll_states
.iter_mut()
.map(|s| s.take_batch().transpose())
.collect::<ArrowResult<Vec<_>>>()
.and_then(|all_batches| -> ArrowResult<Option<RecordBatch>> {
let mut batches = Vec::with_capacity(all_batches.len());
let mut batch_indices = Vec::with_capacity(all_batches.len());
for (i, b) in all_batches.into_iter().enumerate() {
if let Some(b) = b {
batch_indices.push(i);
batches.push(b);
}
}
if batches.is_empty() {
return Ok(None);
}
let (new_cursors, sorted_batch) = merge_sort(
&batches.iter().map(|(c, b)| (*c, b)).collect::<Vec<_>>(),
&self.columns,
MAX_BATCH_ROWS,
)?;
assert_eq!(new_cursors.len(), batches.len());
for (i, b) in batches.into_iter().enumerate() {
self.poll_states[batch_indices[i]]
.update_batch(new_cursors[i], b.1);
}
Ok(Some(sorted_batch))
});
Poll::Ready(res.transpose())
} else {
Poll::Pending
}
}
}
fn merge_sort(
batches: &[(usize, &RecordBatch)],
columns: &[Column],
max_batch_rows: usize,
) -> ArrowResult<(Vec<usize>, RecordBatch)> {
assert!(!columns.is_empty());
assert!(!batches.is_empty());
let mut sort_keys = Vec::with_capacity(batches.len());
let mut pos = Vec::with_capacity(batches.len());
for (p, b) in batches {
let mut key_cols = Vec::with_capacity(columns.len());
for c in columns {
key_cols.push(b.column(c.index()));
}
sort_keys.push(key_cols);
pos.push(*p);
}
struct Key<'a> {
values: &'a [&'a ArrayRef],
index: usize,
row: usize,
}
impl PartialEq for Key<'_> {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl Eq for Key<'_> {}
impl PartialOrd for Key<'_> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Key<'_> {
fn cmp(&self, other: &Self) -> Ordering {
for i in 0..self.values.len() {
let o = cmp_array_row_same_types(
&self.values[i],
self.row,
&other.values[i],
other.row,
);
if o != Ordering::Equal {
return o;
}
}
self.index.cmp(&other.index) // This comparison makes pop order deterministic.
}
}
let mut candidates = BinaryHeap::with_capacity(sort_keys.len());
for i in 0..sort_keys.len() {
if pos[i] == sort_keys[i][0].len() {
continue;
}
let k = Key {
values: &sort_keys[i],
index: i,
row: pos[i],
};
candidates.push(Reverse(k));
}
let num_cols = batches[0].1.num_columns();
let mut result_cols = Vec::with_capacity(num_cols);
let mut num_result_rows = 0;
for i in 0..num_cols {
result_cols.push(MutableArrayData::new(
batches.iter().map(|(_, b)| b.column(i).data()).collect(),
false,
max_batch_rows,
));
}
while let Some(Reverse(c)) = candidates.pop() {
let mut len = 1;
if let Some(next) = candidates.peek() {
loop {
if num_result_rows + len == max_batch_rows
|| c.row + len == sort_keys[c.index][0].len()
{
break;
}
assert!(
lexcmp_array_rows(
sort_keys[c.index].iter().map(|a| *a),
c.row + len - 1,
c.row + len
) <= Ordering::Equal,
"unsorted data in merge. row {}. data: {:?}",
c.row + len,
sort_keys[c.index]
.iter()
.map(|a| a.slice(pos[c.index] + len - 1, 2))
);
let k = Key {
values: &sort_keys[c.index],
index: c.index,
row: c.row + len,
};
if k.cmp(&next.0) <= Ordering::Equal {
len += 1;
} else {
break;
}
}
}
for i in 0..num_cols {
result_cols[i].extend(c.index, c.row, c.row + len);
}
num_result_rows += len;
assert_eq!(pos[c.index], c.row);
pos[c.index] += len;
if num_result_rows == max_batch_rows
|| pos[c.index] == sort_keys[c.index][0].len()
{
break;
}
candidates.push(Reverse(Key {
values: &sort_keys[c.index],
index: c.index,
row: pos[c.index],
}));
}
let result_cols: Vec<ArrayRef> = result_cols
.into_iter()
.map(|r| make_array(r.freeze()))
.collect();
#[cfg(debug_assertions)]
{
let key_cols = columns
.iter()
.map(|c| &result_cols[c.index()])
.collect::<Vec<_>>();
for i in 1..result_cols[0].len() {
debug_assert!(
lexcmp_array_rows(key_cols.iter().map(|a| *a), i - 1, i,)
<= Ordering::Equal,
"unsorted data after merge. row {}. data: {:?}",
i - 1,
key_cols.iter().map(|a| a.slice(i - 1, 2))
);
}
}
Ok((
pos,
RecordBatch::try_new(batches[0].1.schema(), result_cols)?,
))
}
impl RecordBatchStream for MergeSortStream {
fn schema(&self) -> SchemaRef {
self.schema.clone()
}
}
/// Filter out all but last row by unique key execution plan
#[derive(Debug)]
pub struct LastRowByUniqueKeyExec {
input: Arc<dyn ExecutionPlan>,
/// Columns to sort on
pub unique_key: Vec<Column>,
}
impl LastRowByUniqueKeyExec {
/// Create a new execution plan
pub fn try_new(
input: Arc<dyn ExecutionPlan>,
unique_key: Vec<Column>,
) -> Result<Self> {
if unique_key.is_empty() {
return Err(DataFusionError::Internal(
"Empty unique_key passed for LastRowByUniqueKeyExec".to_string(),
));
}
Ok(Self { input, unique_key })
}
/// Input execution plan
pub fn input(&self) -> &Arc<dyn ExecutionPlan> {
&self.input
}
}
#[async_trait]
impl ExecutionPlan for LastRowByUniqueKeyExec {
fn as_any(&self) -> &dyn Any {
self
}
fn schema(&self) -> SchemaRef {
self.input.schema()
}
fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {
vec![self.input.clone()]
}
fn output_partitioning(&self) -> Partitioning {
Partitioning::UnknownPartitioning(1)
}
fn with_new_children(
&self,
children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {
Ok(Arc::new(LastRowByUniqueKeyExec::try_new(
children[0].clone(),
self.unique_key.clone(),
)?))
}
fn output_hints(&self) -> OptimizerHints {
OptimizerHints {
single_value_columns: self.input.output_hints().single_value_columns,
sort_order: self.input.output_hints().sort_order,
}
}
async fn execute(&self, partition: usize) -> Result<SendableRecordBatchStream> {
if 0 != partition {
return Err(DataFusionError::Internal(format!(
"LastRowByUniqueKeyExec invalid partition {}",
partition
)));
}
if self.input.output_partitioning().partition_count() != 1 {
return Err(DataFusionError::Internal(format!(
"LastRowByUniqueKeyExec expects only one partition but got {}",
self.input.output_partitioning().partition_count()
)));
}
let input_stream = self.input.execute(0).await?;
Ok(Box::pin(LastRowByUniqueKeyExecStream {
schema: self.input.schema(),
input: input_stream,
unique_key: self.unique_key.clone(),
current_record_batch: None,
}))
}
}
/// Filter out all but last row by unique key stream
struct LastRowByUniqueKeyExecStream {
/// Output schema, which is the same as the input schema for this operator
schema: SchemaRef,
/// The input stream to filter.
input: SendableRecordBatchStream,
/// Key columns
unique_key: Vec<Column>,
/// Current Record Batch
current_record_batch: Option<RecordBatch>,
}
impl LastRowByUniqueKeyExecStream {
fn row_equals(comparators: &Vec<DynComparator>, a: usize, b: usize) -> bool {
for comparator in comparators.iter().rev() {
if comparator(a, b) != Ordering::Equal {
return false;
}
}
true
}
fn keep_only_last_rows_by_key(
&mut self,
next_batch: Option<RecordBatch>,
) -> ArrowResult<RecordBatch> {
let batch = self.current_record_batch.take().unwrap();
let num_rows = batch.num_rows();
let mut builder = BooleanArray::builder(num_rows);
let key_columns = self
.unique_key
.iter()
.map(|k| batch.column(k.index()).clone())
.collect::<Vec<ArrayRef>>();
let mut requires_filtering = false;
let self_column_comparators = key_columns
.iter()
.map(|c| build_compare(c.as_ref(), c.as_ref()))
.collect::<ArrowResult<Vec<_>>>()?;
for i in 0..num_rows {
let filter_value = if i == num_rows - 1 && next_batch.is_none() {
true
} else if i == num_rows - 1 {
let next_key_columns = self
.unique_key
.iter()
.map(|k| next_batch.as_ref().unwrap().column(k.index()).clone())
.collect::<Vec<ArrayRef>>();
let next_column_comparators = key_columns
.iter()
.zip(next_key_columns.iter())
.map(|(c, n)| build_compare(c.as_ref(), n.as_ref()))
.collect::<ArrowResult<Vec<_>>>()?;
!Self::row_equals(&next_column_comparators, i, 0)
} else {
!Self::row_equals(&self_column_comparators, i, i + 1)
};
if !filter_value {
requires_filtering = true;
}
builder.append_value(filter_value)?;
}
self.current_record_batch = next_batch;
if requires_filtering {
let filter_array = builder.finish();
filter_record_batch(&batch, &filter_array)
} else {
Ok(batch)
}
}
}
impl Stream for LastRowByUniqueKeyExecStream {
type Item = ArrowResult<RecordBatch>;
fn poll_next(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
self.input.poll_next_unpin(cx).map(|x| {
match x {
Some(Ok(batch)) => {
if self.current_record_batch.is_none() {
let schema = batch.schema();
self.current_record_batch = Some(batch);
// TODO get rid of empty batch. Returning Poll::Pending here results in stuck stream.
Some(Ok(RecordBatch::new_empty(schema)))
} else {
Some(self.keep_only_last_rows_by_key(Some(batch)))
}
}
None => {
if self.current_record_batch.is_some() {
Some(self.keep_only_last_rows_by_key(None))
} else {
None
}
}
other => other,
}
})
}
fn size_hint(&self) -> (usize, Option<usize>) {
let (lower, upper) = self.input.size_hint();
(lower, upper.map(|u| u + 1))
}
}
impl RecordBatchStream for LastRowByUniqueKeyExecStream {
fn schema(&self) -> SchemaRef {
self.schema.clone()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::arrow::compute::kernels::concat::concat;
use crate::physical_plan::collect;
use crate::physical_plan::memory::MemoryExec;
use arrow::array::*;
use arrow::datatypes::*;
use itertools::Itertools;
#[tokio::test]
async fn two_inputs_three_batches() -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("a", DataType::UInt32, true),
Field::new("b", DataType::UInt64, true),
]));
// define data.
let batch1_1 = RecordBatch::try_new(
schema.clone(),
vec![
Arc::new(UInt32Array::from(vec![
None,
None,
Some(1),
Some(1),
Some(3),
Some(5),
Some(5),
])),
Arc::new(UInt64Array::from(vec![
Some(1),
Some(2),
Some(1),
Some(2),
Some(2),
None,
Some(2),
])),
],
)?;
let batch1_2 = RecordBatch::try_new(
schema.clone(),
vec![
Arc::new(UInt32Array::from(vec![
Some(7),
Some(8),
Some(8),
Some(8),
Some(9),
])),
Arc::new(UInt64Array::from(vec![
Some(1),
Some(2),
Some(2),
Some(3),
None,
])),
],
)?;
let batch2 = RecordBatch::try_new(
schema.clone(),
vec![
Arc::new(UInt32Array::from(vec![Some(3), Some(5), Some(10)])),
Arc::new(UInt64Array::from(vec![Some(2), Some(2), None])),
],
)?;
let sort_exec = Arc::new(MergeSortExec::try_new(
Arc::new(MemoryExec::try_new(
&vec![vec![batch1_1, batch1_2], vec![batch2]],
schema.clone(),
None,
)?),
vec![col("a", &schema), col("b", &schema)],
)?);
assert_eq!(DataType::UInt32, *sort_exec.schema().field(0).data_type());
assert_eq!(DataType::UInt64, *sort_exec.schema().field(1).data_type());
let result: Vec<RecordBatch> = collect(sort_exec).await?;
assert_eq!(result.len(), 3);
assert_eq!(
vec![
(None, Some("1".to_owned())),
(None, Some("2".to_owned())),
(Some("1".to_owned()), Some("1".to_owned())),
(Some("1".to_owned()), Some("2".to_owned())),
(Some("3".to_owned()), Some("2".to_owned())),
(Some("3".to_owned()), Some("2".to_owned())),
(Some("5".to_owned()), None),
(Some("5".to_owned()), Some("2".to_owned())),
],
transform_batch_for_assert(&result[0])
);
assert_eq!(
vec![
(Some("5".to_owned()), Some("2".to_owned())),
(Some("7".to_owned()), Some("1".to_owned())),
(Some("8".to_owned()), Some("2".to_owned())),
(Some("8".to_owned()), Some("2".to_owned())),
(Some("8".to_owned()), Some("3".to_owned())),
(Some("9".to_owned()), None),
],
transform_batch_for_assert(&result[1])
);
assert_eq!(
vec![(Some("10".to_owned()), None),],
transform_batch_for_assert(&result[2])
);
Ok(())
}
#[tokio::test]
async fn resort() -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("a", DataType::UInt32, true),
Field::new("b", DataType::UInt64, true),
]));
// define data.
let batch1_1 = RecordBatch::try_new(
schema.clone(),
vec![
Arc::new(UInt32Array::from(vec![
None,
None,
Some(1),
Some(1),
Some(3),
Some(5),
Some(5),
])),
Arc::new(UInt64Array::from(vec![
Some(1),
Some(2),
Some(1),
Some(2),
Some(2),
None,
Some(2),
])),
],
)?;
let batch1_2 = RecordBatch::try_new(
schema.clone(),
vec![
Arc::new(UInt32Array::from(vec![
Some(7),
Some(8),
Some(8),
Some(8),
Some(9),
])),
Arc::new(UInt64Array::from(vec![
Some(1),
Some(2),
Some(2),
Some(3),
None,
])),
],
)?;
let batch2 = RecordBatch::try_new(
schema.clone(),
vec![
Arc::new(UInt32Array::from(vec![Some(3), Some(5), Some(10)])),
Arc::new(UInt64Array::from(vec![Some(2), Some(2), None])),
],
)?;
let sort_exec = Arc::new(MergeReSortExec::try_new(
Arc::new(MemoryExec::try_new(
&vec![vec![batch1_2, batch1_1, batch2]],
schema.clone(),
None,
)?),
vec![col("a", &schema), col("b", &schema)],
)?);
assert_eq!(DataType::UInt32, *sort_exec.schema().field(0).data_type());
assert_eq!(DataType::UInt64, *sort_exec.schema().field(1).data_type());
let result: Vec<RecordBatch> = collect(sort_exec).await?;
assert_eq!(result.len(), 3);
assert_eq!(
vec![
(None, Some("1".to_owned())),
(None, Some("2".to_owned())),
(Some("1".to_owned()), Some("1".to_owned())),
(Some("1".to_owned()), Some("2".to_owned())),
(Some("3".to_owned()), Some("2".to_owned())),
(Some("3".to_owned()), Some("2".to_owned())),
(Some("5".to_owned()), None),
(Some("5".to_owned()), Some("2".to_owned())),
],
transform_batch_for_assert(&result[0])
);
assert_eq!(
vec![
(Some("5".to_owned()), Some("2".to_owned())),
(Some("7".to_owned()), Some("1".to_owned())),
(Some("8".to_owned()), Some("2".to_owned())),
(Some("8".to_owned()), Some("2".to_owned())),
(Some("8".to_owned()), Some("3".to_owned())),
(Some("9".to_owned()), None),
],
transform_batch_for_assert(&result[1])
);
assert_eq!(
vec![(Some("10".to_owned()), None),],
transform_batch_for_assert(&result[2])
);
Ok(())
}
#[tokio::test]
async fn empty_batches() -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("a", DataType::UInt32, true),
Field::new("b", DataType::UInt64, true),
]));
// define data.
let batch1_1 = RecordBatch::try_new(
schema.clone(),
vec![
Arc::new(UInt32Array::from(Vec::<u32>::new())),
Arc::new(UInt64Array::from(Vec::<u64>::new())),
],