-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
utils.rs
1795 lines (1641 loc) · 63.9 KB
/
utils.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
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.
//! Join related functionality used both on logical and physical plans
use std::collections::HashSet;
use std::future::Future;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::usize;
use crate::joins::hash_join_utils::{build_filter_input_order, SortedFilterExpr};
use crate::metrics::{self, ExecutionPlanMetricsSet, MetricBuilder};
use crate::{ColumnStatistics, ExecutionPlan, Partitioning, Statistics};
use arrow::array::{
downcast_array, new_null_array, Array, BooleanBufferBuilder, UInt32Array,
UInt32Builder, UInt64Array,
};
use arrow::compute;
use arrow::datatypes::{Field, Schema, SchemaBuilder};
use arrow::record_batch::{RecordBatch, RecordBatchOptions};
use datafusion_common::cast::as_boolean_array;
use datafusion_common::stats::Precision;
use datafusion_common::{
plan_datafusion_err, plan_err, DataFusionError, JoinSide, JoinType, Result,
SharedResult,
};
use datafusion_physical_expr::equivalence::add_offset_to_expr;
use datafusion_physical_expr::expressions::Column;
use datafusion_physical_expr::intervals::{ExprIntervalGraph, Interval, IntervalBound};
use datafusion_physical_expr::utils::merge_vectors;
use datafusion_physical_expr::{
LexOrdering, LexOrderingRef, PhysicalExpr, PhysicalSortExpr,
};
use futures::future::{BoxFuture, Shared};
use futures::{ready, FutureExt};
use parking_lot::Mutex;
/// The on clause of the join, as vector of (left, right) columns.
pub type JoinOn = Vec<(Column, Column)>;
/// Reference for JoinOn.
pub type JoinOnRef<'a> = &'a [(Column, Column)];
/// Checks whether the schemas "left" and "right" and columns "on" represent a valid join.
/// They are valid whenever their columns' intersection equals the set `on`
pub fn check_join_is_valid(left: &Schema, right: &Schema, on: JoinOnRef) -> Result<()> {
let left: HashSet<Column> = left
.fields()
.iter()
.enumerate()
.map(|(idx, f)| Column::new(f.name(), idx))
.collect();
let right: HashSet<Column> = right
.fields()
.iter()
.enumerate()
.map(|(idx, f)| Column::new(f.name(), idx))
.collect();
check_join_set_is_valid(&left, &right, on)
}
/// Checks whether the sets left, right and on compose a valid join.
/// They are valid whenever their intersection equals the set `on`
fn check_join_set_is_valid(
left: &HashSet<Column>,
right: &HashSet<Column>,
on: &[(Column, Column)],
) -> Result<()> {
let on_left = &on.iter().map(|on| on.0.clone()).collect::<HashSet<_>>();
let left_missing = on_left.difference(left).collect::<HashSet<_>>();
let on_right = &on.iter().map(|on| on.1.clone()).collect::<HashSet<_>>();
let right_missing = on_right.difference(right).collect::<HashSet<_>>();
if !left_missing.is_empty() | !right_missing.is_empty() {
return plan_err!(
"The left or right side of the join does not have all columns on \"on\": \nMissing on the left: {left_missing:?}\nMissing on the right: {right_missing:?}"
);
};
Ok(())
}
/// Calculate the OutputPartitioning for Partitioned Join
pub fn partitioned_join_output_partitioning(
join_type: JoinType,
left_partitioning: Partitioning,
right_partitioning: Partitioning,
left_columns_len: usize,
) -> Partitioning {
match join_type {
JoinType::Inner | JoinType::Left | JoinType::LeftSemi | JoinType::LeftAnti => {
left_partitioning
}
JoinType::RightSemi | JoinType::RightAnti => right_partitioning,
JoinType::Right => {
adjust_right_output_partitioning(right_partitioning, left_columns_len)
}
JoinType::Full => {
Partitioning::UnknownPartitioning(right_partitioning.partition_count())
}
}
}
/// Adjust the right out partitioning to new Column Index
pub fn adjust_right_output_partitioning(
right_partitioning: Partitioning,
left_columns_len: usize,
) -> Partitioning {
match right_partitioning {
Partitioning::RoundRobinBatch(size) => Partitioning::RoundRobinBatch(size),
Partitioning::UnknownPartitioning(size) => {
Partitioning::UnknownPartitioning(size)
}
Partitioning::Hash(exprs, size) => {
let new_exprs = exprs
.into_iter()
.map(|expr| add_offset_to_expr(expr, left_columns_len))
.collect();
Partitioning::Hash(new_exprs, size)
}
}
}
/// Replaces the right column (first index in the `on_column` tuple) with
/// the left column (zeroth index in the tuple) inside `right_ordering`.
fn replace_on_columns_of_right_ordering(
on_columns: &[(Column, Column)],
right_ordering: &mut [PhysicalSortExpr],
left_columns_len: usize,
) {
for (left_col, right_col) in on_columns {
let right_col =
Column::new(right_col.name(), right_col.index() + left_columns_len);
for item in right_ordering.iter_mut() {
if let Some(col) = item.expr.as_any().downcast_ref::<Column>() {
if right_col.eq(col) {
item.expr = Arc::new(left_col.clone()) as _;
}
}
}
}
}
/// Calculate the output ordering of a given join operation.
pub fn calculate_join_output_ordering(
left_ordering: LexOrderingRef,
right_ordering: LexOrderingRef,
join_type: JoinType,
on_columns: &[(Column, Column)],
left_columns_len: usize,
maintains_input_order: &[bool],
probe_side: Option<JoinSide>,
) -> Option<LexOrdering> {
let mut right_ordering = match join_type {
// In the case below, right ordering should be offseted with the left
// side length, since we append the right table to the left table.
JoinType::Inner | JoinType::Left | JoinType::Right | JoinType::Full => {
right_ordering
.iter()
.map(|sort_expr| PhysicalSortExpr {
expr: add_offset_to_expr(sort_expr.expr.clone(), left_columns_len),
options: sort_expr.options,
})
.collect()
}
_ => right_ordering.to_vec(),
};
let output_ordering = match maintains_input_order {
[true, false] => {
// Special case, we can prefix ordering of right side with the ordering of left side.
if join_type == JoinType::Inner && probe_side == Some(JoinSide::Left) {
replace_on_columns_of_right_ordering(
on_columns,
&mut right_ordering,
left_columns_len,
);
merge_vectors(left_ordering, &right_ordering)
} else {
left_ordering.to_vec()
}
}
[false, true] => {
// Special case, we can prefix ordering of left side with the ordering of right side.
if join_type == JoinType::Inner && probe_side == Some(JoinSide::Right) {
replace_on_columns_of_right_ordering(
on_columns,
&mut right_ordering,
left_columns_len,
);
merge_vectors(&right_ordering, left_ordering)
} else {
right_ordering.to_vec()
}
}
// Doesn't maintain ordering, output ordering is None.
[false, false] => return None,
[true, true] => unreachable!("Cannot maintain ordering of both sides"),
_ => unreachable!("Join operators can not have more than two children"),
};
(!output_ordering.is_empty()).then_some(output_ordering)
}
/// Information about the index and placement (left or right) of the columns
#[derive(Debug, Clone, PartialEq)]
pub struct ColumnIndex {
/// Index of the column
pub index: usize,
/// Whether the column is at the left or right side
pub side: JoinSide,
}
/// Filter applied before join output
#[derive(Debug, Clone)]
pub struct JoinFilter {
/// Filter expression
expression: Arc<dyn PhysicalExpr>,
/// Column indices required to construct intermediate batch for filtering
column_indices: Vec<ColumnIndex>,
/// Physical schema of intermediate batch
schema: Schema,
}
impl JoinFilter {
/// Creates new JoinFilter
pub fn new(
expression: Arc<dyn PhysicalExpr>,
column_indices: Vec<ColumnIndex>,
schema: Schema,
) -> JoinFilter {
JoinFilter {
expression,
column_indices,
schema,
}
}
/// Helper for building ColumnIndex vector from left and right indices
pub fn build_column_indices(
left_indices: Vec<usize>,
right_indices: Vec<usize>,
) -> Vec<ColumnIndex> {
left_indices
.into_iter()
.map(|i| ColumnIndex {
index: i,
side: JoinSide::Left,
})
.chain(right_indices.into_iter().map(|i| ColumnIndex {
index: i,
side: JoinSide::Right,
}))
.collect()
}
/// Filter expression
pub fn expression(&self) -> &Arc<dyn PhysicalExpr> {
&self.expression
}
/// Column indices for intermediate batch creation
pub fn column_indices(&self) -> &[ColumnIndex] {
&self.column_indices
}
/// Intermediate batch schema
pub fn schema(&self) -> &Schema {
&self.schema
}
}
/// Returns the output field given the input field. Outer joins may
/// insert nulls even if the input was not null
///
fn output_join_field(old_field: &Field, join_type: &JoinType, is_left: bool) -> Field {
let force_nullable = match join_type {
JoinType::Inner => false,
JoinType::Left => !is_left, // right input is padded with nulls
JoinType::Right => is_left, // left input is padded with nulls
JoinType::Full => true, // both inputs can be padded with nulls
JoinType::LeftSemi => false, // doesn't introduce nulls
JoinType::RightSemi => false, // doesn't introduce nulls
JoinType::LeftAnti => false, // doesn't introduce nulls (or can it??)
JoinType::RightAnti => false, // doesn't introduce nulls (or can it??)
};
if force_nullable {
old_field.clone().with_nullable(true)
} else {
old_field.clone()
}
}
/// Creates a schema for a join operation.
/// The fields from the left side are first
pub fn build_join_schema(
left: &Schema,
right: &Schema,
join_type: &JoinType,
) -> (Schema, Vec<ColumnIndex>) {
let (fields, column_indices): (SchemaBuilder, Vec<ColumnIndex>) = match join_type {
JoinType::Inner | JoinType::Left | JoinType::Full | JoinType::Right => {
let left_fields = left
.fields()
.iter()
.map(|f| output_join_field(f, join_type, true))
.enumerate()
.map(|(index, f)| {
(
f,
ColumnIndex {
index,
side: JoinSide::Left,
},
)
});
let right_fields = right
.fields()
.iter()
.map(|f| output_join_field(f, join_type, false))
.enumerate()
.map(|(index, f)| {
(
f,
ColumnIndex {
index,
side: JoinSide::Right,
},
)
});
// left then right
left_fields.chain(right_fields).unzip()
}
JoinType::LeftSemi | JoinType::LeftAnti => left
.fields()
.iter()
.cloned()
.enumerate()
.map(|(index, f)| {
(
f,
ColumnIndex {
index,
side: JoinSide::Left,
},
)
})
.unzip(),
JoinType::RightSemi | JoinType::RightAnti => right
.fields()
.iter()
.cloned()
.enumerate()
.map(|(index, f)| {
(
f,
ColumnIndex {
index,
side: JoinSide::Right,
},
)
})
.unzip(),
};
(fields.finish(), column_indices)
}
/// A [`OnceAsync`] can be used to run an async closure once, with subsequent calls
/// to [`OnceAsync::once`] returning a [`OnceFut`] to the same asynchronous computation
///
/// This is useful for joins where the results of one child are buffered in memory
/// and shared across potentially multiple output partitions
pub(crate) struct OnceAsync<T> {
fut: Mutex<Option<OnceFut<T>>>,
}
impl<T> Default for OnceAsync<T> {
fn default() -> Self {
Self {
fut: Mutex::new(None),
}
}
}
impl<T> std::fmt::Debug for OnceAsync<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "OnceAsync")
}
}
impl<T: 'static> OnceAsync<T> {
/// If this is the first call to this function on this object, will invoke
/// `f` to obtain a future and return a [`OnceFut`] referring to this
///
/// If this is not the first call, will return a [`OnceFut`] referring
/// to the same future as was returned by the first call
pub(crate) fn once<F, Fut>(&self, f: F) -> OnceFut<T>
where
F: FnOnce() -> Fut,
Fut: Future<Output = Result<T>> + Send + 'static,
{
self.fut
.lock()
.get_or_insert_with(|| OnceFut::new(f()))
.clone()
}
}
/// The shared future type used internally within [`OnceAsync`]
type OnceFutPending<T> = Shared<BoxFuture<'static, SharedResult<Arc<T>>>>;
/// A [`OnceFut`] represents a shared asynchronous computation, that will be evaluated
/// once for all [`Clone`]'s, with [`OnceFut::get`] providing a non-consuming interface
/// to drive the underlying [`Future`] to completion
pub(crate) struct OnceFut<T> {
state: OnceFutState<T>,
}
impl<T> Clone for OnceFut<T> {
fn clone(&self) -> Self {
Self {
state: self.state.clone(),
}
}
}
/// A shared state between statistic aggregators for a join
/// operation.
#[derive(Clone, Debug, Default)]
struct PartialJoinStatistics {
pub num_rows: usize,
pub column_statistics: Vec<ColumnStatistics>,
}
/// Estimate the statistics for the given join's output.
pub(crate) fn estimate_join_statistics(
left: Arc<dyn ExecutionPlan>,
right: Arc<dyn ExecutionPlan>,
on: JoinOn,
join_type: &JoinType,
schema: &Schema,
) -> Result<Statistics> {
let left_stats = left.statistics()?;
let right_stats = right.statistics()?;
let join_stats = estimate_join_cardinality(join_type, left_stats, right_stats, &on);
let (num_rows, column_statistics) = match join_stats {
Some(stats) => (Precision::Inexact(stats.num_rows), stats.column_statistics),
None => (Precision::Absent, Statistics::unknown_column(schema)),
};
Ok(Statistics {
num_rows,
total_byte_size: Precision::Absent,
column_statistics,
})
}
// Estimate the cardinality for the given join with input statistics.
fn estimate_join_cardinality(
join_type: &JoinType,
left_stats: Statistics,
right_stats: Statistics,
on: &JoinOn,
) -> Option<PartialJoinStatistics> {
match join_type {
JoinType::Inner | JoinType::Left | JoinType::Right | JoinType::Full => {
let (left_col_stats, right_col_stats) = on
.iter()
.map(|(left, right)| {
(
left_stats.column_statistics[left.index()].clone(),
right_stats.column_statistics[right.index()].clone(),
)
})
.unzip::<_, _, Vec<_>, Vec<_>>();
let ij_cardinality = estimate_inner_join_cardinality(
Statistics {
num_rows: left_stats.num_rows.clone(),
total_byte_size: Precision::Absent,
column_statistics: left_col_stats,
},
Statistics {
num_rows: right_stats.num_rows.clone(),
total_byte_size: Precision::Absent,
column_statistics: right_col_stats,
},
)?;
// The cardinality for inner join can also be used to estimate
// the cardinality of left/right/full outer joins as long as it
// it is greater than the minimum cardinality constraints of these
// joins (so that we don't underestimate the cardinality).
let cardinality = match join_type {
JoinType::Inner => ij_cardinality,
JoinType::Left => ij_cardinality.max(&left_stats.num_rows),
JoinType::Right => ij_cardinality.max(&right_stats.num_rows),
JoinType::Full => ij_cardinality
.max(&left_stats.num_rows)
.add(&ij_cardinality.max(&right_stats.num_rows))
.sub(&ij_cardinality),
_ => unreachable!(),
};
Some(PartialJoinStatistics {
num_rows: *cardinality.get_value()?,
// We don't do anything specific here, just combine the existing
// statistics which might yield subpar results (although it is
// true, esp regarding min/max). For a better estimation, we need
// filter selectivity analysis first.
column_statistics: left_stats
.column_statistics
.into_iter()
.chain(right_stats.column_statistics)
.collect(),
})
}
JoinType::LeftSemi
| JoinType::RightSemi
| JoinType::LeftAnti
| JoinType::RightAnti => None,
}
}
/// Estimate the inner join cardinality by using the basic building blocks of
/// column-level statistics and the total row count. This is a very naive and
/// a very conservative implementation that can quickly give up if there is not
/// enough input statistics.
fn estimate_inner_join_cardinality(
left_stats: Statistics,
right_stats: Statistics,
) -> Option<Precision<usize>> {
// The algorithm here is partly based on the non-histogram selectivity estimation
// from Spark's Catalyst optimizer.
let mut join_selectivity = Precision::Absent;
for (left_stat, right_stat) in left_stats
.column_statistics
.iter()
.zip(right_stats.column_statistics.iter())
{
// If there is no overlap in any of the join columns, this means the join
// itself is disjoint and the cardinality is 0. Though we can only assume
// this when the statistics are exact (since it is a very strong assumption).
if left_stat.min_value.get_value()? > right_stat.max_value.get_value()? {
return Some(
if left_stat.min_value.is_exact().unwrap_or(false)
&& right_stat.max_value.is_exact().unwrap_or(false)
{
Precision::Exact(0)
} else {
Precision::Inexact(0)
},
);
}
if left_stat.max_value.get_value()? < right_stat.min_value.get_value()? {
return Some(
if left_stat.max_value.is_exact().unwrap_or(false)
&& right_stat.min_value.is_exact().unwrap_or(false)
{
Precision::Exact(0)
} else {
Precision::Inexact(0)
},
);
}
let left_max_distinct = max_distinct_count(&left_stats.num_rows, left_stat)?;
let right_max_distinct = max_distinct_count(&right_stats.num_rows, right_stat)?;
let max_distinct = left_max_distinct.max(&right_max_distinct);
if max_distinct.get_value().is_some() {
// Seems like there are a few implementations of this algorithm that implement
// exponential decay for the selectivity (like Hive's Optiq Optimizer). Needs
// further exploration.
join_selectivity = max_distinct;
}
}
// With the assumption that the smaller input's domain is generally represented in the bigger
// input's domain, we can estimate the inner join's cardinality by taking the cartesian product
// of the two inputs and normalizing it by the selectivity factor.
let left_num_rows = left_stats.num_rows.get_value()?;
let right_num_rows = right_stats.num_rows.get_value()?;
match join_selectivity {
Precision::Exact(value) if value > 0 => {
Some(Precision::Exact((left_num_rows * right_num_rows) / value))
}
Precision::Inexact(value) if value > 0 => {
Some(Precision::Inexact((left_num_rows * right_num_rows) / value))
}
// Since we don't have any information about the selectivity (which is derived
// from the number of distinct rows information) we can give up here for now.
// And let other passes handle this (otherwise we would need to produce an
// overestimation using just the cartesian product).
_ => None,
}
}
/// Estimate the number of maximum distinct values that can be present in the
/// given column from its statistics.
///
/// If distinct_count is available, uses it directly. If the column numeric, and
/// has min/max values, then they might be used as a fallback option. Otherwise,
/// returns None.
fn max_distinct_count(
num_rows: &Precision<usize>,
stats: &ColumnStatistics,
) -> Option<Precision<usize>> {
match (
&stats.distinct_count,
stats.max_value.get_value(),
stats.min_value.get_value(),
) {
(Precision::Exact(_), _, _) | (Precision::Inexact(_), _, _) => {
Some(stats.distinct_count.clone())
}
(_, Some(max), Some(min)) => {
let numeric_range = Interval::new(
IntervalBound::new(min.clone(), false),
IntervalBound::new(max.clone(), false),
)
.cardinality()
.ok()
.flatten()? as usize;
// The number can never be greater than the number of rows we have (minus
// the nulls, since they don't count as distinct values).
let ceiling =
num_rows.get_value()? - stats.null_count.get_value().unwrap_or(&0);
Some(
if num_rows.is_exact().unwrap_or(false)
&& stats.max_value.is_exact().unwrap_or(false)
&& stats.min_value.is_exact().unwrap_or(false)
{
Precision::Exact(numeric_range.min(ceiling))
} else {
Precision::Inexact(numeric_range.min(ceiling))
},
)
}
_ => None,
}
}
enum OnceFutState<T> {
Pending(OnceFutPending<T>),
Ready(SharedResult<Arc<T>>),
}
impl<T> Clone for OnceFutState<T> {
fn clone(&self) -> Self {
match self {
Self::Pending(p) => Self::Pending(p.clone()),
Self::Ready(r) => Self::Ready(r.clone()),
}
}
}
impl<T: 'static> OnceFut<T> {
/// Create a new [`OnceFut`] from a [`Future`]
pub(crate) fn new<Fut>(fut: Fut) -> Self
where
Fut: Future<Output = Result<T>> + Send + 'static,
{
Self {
state: OnceFutState::Pending(
fut.map(|res| res.map(Arc::new).map_err(Arc::new))
.boxed()
.shared(),
),
}
}
/// Get the result of the computation if it is ready, without consuming it
pub(crate) fn get(&mut self, cx: &mut Context<'_>) -> Poll<Result<&T>> {
if let OnceFutState::Pending(fut) = &mut self.state {
let r = ready!(fut.poll_unpin(cx));
self.state = OnceFutState::Ready(r);
}
// Cannot use loop as this would trip up the borrow checker
match &self.state {
OnceFutState::Pending(_) => unreachable!(),
OnceFutState::Ready(r) => Poll::Ready(
r.as_ref()
.map(|r| r.as_ref())
.map_err(|e| DataFusionError::External(Box::new(e.clone()))),
),
}
}
}
/// Some type `join_type` of join need to maintain the matched indices bit map for the left side, and
/// use the bit map to generate the part of result of the join.
///
/// For example of the `Left` join, in each iteration of right side, can get the matched result, but need
/// to maintain the matched indices bit map to get the unmatched row for the left side.
pub(crate) fn need_produce_result_in_final(join_type: JoinType) -> bool {
matches!(
join_type,
JoinType::Left | JoinType::LeftAnti | JoinType::LeftSemi | JoinType::Full
)
}
/// In the end of join execution, need to use bit map of the matched
/// indices to generate the final left and right indices.
///
/// For example:
///
/// 1. left_bit_map: `[true, false, true, true, false]`
/// 2. join_type: `Left`
///
/// The result is: `([1,4], [null, null])`
pub(crate) fn get_final_indices_from_bit_map(
left_bit_map: &BooleanBufferBuilder,
join_type: JoinType,
) -> (UInt64Array, UInt32Array) {
let left_size = left_bit_map.len();
let left_indices = if join_type == JoinType::LeftSemi {
(0..left_size)
.filter_map(|idx| (left_bit_map.get_bit(idx)).then_some(idx as u64))
.collect::<UInt64Array>()
} else {
// just for `Left`, `LeftAnti` and `Full` join
// `LeftAnti`, `Left` and `Full` will produce the unmatched left row finally
(0..left_size)
.filter_map(|idx| (!left_bit_map.get_bit(idx)).then_some(idx as u64))
.collect::<UInt64Array>()
};
// right_indices
// all the element in the right side is None
let mut builder = UInt32Builder::with_capacity(left_indices.len());
builder.append_nulls(left_indices.len());
let right_indices = builder.finish();
(left_indices, right_indices)
}
pub(crate) fn apply_join_filter_to_indices(
build_input_buffer: &RecordBatch,
probe_batch: &RecordBatch,
build_indices: UInt64Array,
probe_indices: UInt32Array,
filter: &JoinFilter,
build_side: JoinSide,
) -> Result<(UInt64Array, UInt32Array)> {
if build_indices.is_empty() && probe_indices.is_empty() {
return Ok((build_indices, probe_indices));
};
let intermediate_batch = build_batch_from_indices(
filter.schema(),
build_input_buffer,
probe_batch,
&build_indices,
&probe_indices,
filter.column_indices(),
build_side,
)?;
let filter_result = filter
.expression()
.evaluate(&intermediate_batch)?
.into_array(intermediate_batch.num_rows())?;
let mask = as_boolean_array(&filter_result)?;
let left_filtered = compute::filter(&build_indices, mask)?;
let right_filtered = compute::filter(&probe_indices, mask)?;
Ok((
downcast_array(left_filtered.as_ref()),
downcast_array(right_filtered.as_ref()),
))
}
/// Returns a new [RecordBatch] by combining the `left` and `right` according to `indices`.
/// The resulting batch has [Schema] `schema`.
pub(crate) fn build_batch_from_indices(
schema: &Schema,
build_input_buffer: &RecordBatch,
probe_batch: &RecordBatch,
build_indices: &UInt64Array,
probe_indices: &UInt32Array,
column_indices: &[ColumnIndex],
build_side: JoinSide,
) -> Result<RecordBatch> {
if schema.fields().is_empty() {
let options = RecordBatchOptions::new()
.with_match_field_names(true)
.with_row_count(Some(build_indices.len()));
return Ok(RecordBatch::try_new_with_options(
Arc::new(schema.clone()),
vec![],
&options,
)?);
}
// build the columns of the new [RecordBatch]:
// 1. pick whether the column is from the left or right
// 2. based on the pick, `take` items from the different RecordBatches
let mut columns: Vec<Arc<dyn Array>> = Vec::with_capacity(schema.fields().len());
for column_index in column_indices {
let array = if column_index.side == build_side {
let array = build_input_buffer.column(column_index.index);
if array.is_empty() || build_indices.null_count() == build_indices.len() {
// Outer join would generate a null index when finding no match at our side.
// Therefore, it's possible we are empty but need to populate an n-length null array,
// where n is the length of the index array.
assert_eq!(build_indices.null_count(), build_indices.len());
new_null_array(array.data_type(), build_indices.len())
} else {
compute::take(array.as_ref(), build_indices, None)?
}
} else {
let array = probe_batch.column(column_index.index);
if array.is_empty() || probe_indices.null_count() == probe_indices.len() {
assert_eq!(probe_indices.null_count(), probe_indices.len());
new_null_array(array.data_type(), probe_indices.len())
} else {
compute::take(array.as_ref(), probe_indices, None)?
}
};
columns.push(array);
}
Ok(RecordBatch::try_new(Arc::new(schema.clone()), columns)?)
}
/// The input is the matched indices for left and right and
/// adjust the indices according to the join type
pub(crate) fn adjust_indices_by_join_type(
left_indices: UInt64Array,
right_indices: UInt32Array,
count_right_batch: usize,
join_type: JoinType,
) -> (UInt64Array, UInt32Array) {
match join_type {
JoinType::Inner => {
// matched
(left_indices, right_indices)
}
JoinType::Left => {
// matched
(left_indices, right_indices)
// unmatched left row will be produced in the end of loop, and it has been set in the left visited bitmap
}
JoinType::Right | JoinType::Full => {
// matched
// unmatched right row will be produced in this batch
let right_unmatched_indices =
get_anti_indices(count_right_batch, &right_indices);
// combine the matched and unmatched right result together
append_right_indices(left_indices, right_indices, right_unmatched_indices)
}
JoinType::RightSemi => {
// need to remove the duplicated record in the right side
let right_indices = get_semi_indices(count_right_batch, &right_indices);
// the left_indices will not be used later for the `right semi` join
(left_indices, right_indices)
}
JoinType::RightAnti => {
// need to remove the duplicated record in the right side
// get the anti index for the right side
let right_indices = get_anti_indices(count_right_batch, &right_indices);
// the left_indices will not be used later for the `right anti` join
(left_indices, right_indices)
}
JoinType::LeftSemi | JoinType::LeftAnti => {
// matched or unmatched left row will be produced in the end of loop
// When visit the right batch, we can output the matched left row and don't need to wait the end of loop
(
UInt64Array::from_iter_values(vec![]),
UInt32Array::from_iter_values(vec![]),
)
}
}
}
/// Appends the `right_unmatched_indices` to the `right_indices`,
/// and fills Null to tail of `left_indices` to
/// keep the length of `right_indices` and `left_indices` consistent.
pub(crate) fn append_right_indices(
left_indices: UInt64Array,
right_indices: UInt32Array,
right_unmatched_indices: UInt32Array,
) -> (UInt64Array, UInt32Array) {
// left_indices, right_indices and right_unmatched_indices must not contain the null value
if right_unmatched_indices.is_empty() {
(left_indices, right_indices)
} else {
let unmatched_size = right_unmatched_indices.len();
// the new left indices: left_indices + null array
// the new right indices: right_indices + right_unmatched_indices
let new_left_indices = left_indices
.iter()
.chain(std::iter::repeat(None).take(unmatched_size))
.collect::<UInt64Array>();
let new_right_indices = right_indices
.iter()
.chain(right_unmatched_indices.iter())
.collect::<UInt32Array>();
(new_left_indices, new_right_indices)
}
}
/// Get unmatched and deduplicated indices
pub(crate) fn get_anti_indices(
row_count: usize,
input_indices: &UInt32Array,
) -> UInt32Array {
let mut bitmap = BooleanBufferBuilder::new(row_count);
bitmap.append_n(row_count, false);
input_indices.iter().flatten().for_each(|v| {
bitmap.set_bit(v as usize, true);
});
// get the anti index
(0..row_count)
.filter_map(|idx| (!bitmap.get_bit(idx)).then_some(idx as u32))
.collect::<UInt32Array>()
}
/// Get unmatched and deduplicated indices
pub(crate) fn get_anti_u64_indices(
row_count: usize,
input_indices: &UInt64Array,
) -> UInt64Array {
let mut bitmap = BooleanBufferBuilder::new(row_count);
bitmap.append_n(row_count, false);
input_indices.iter().flatten().for_each(|v| {
bitmap.set_bit(v as usize, true);
});
// get the anti index
(0..row_count)
.filter_map(|idx| (!bitmap.get_bit(idx)).then_some(idx as u64))
.collect::<UInt64Array>()
}
/// Get matched and deduplicated indices
pub(crate) fn get_semi_indices(
row_count: usize,
input_indices: &UInt32Array,
) -> UInt32Array {
let mut bitmap = BooleanBufferBuilder::new(row_count);
bitmap.append_n(row_count, false);
input_indices.iter().flatten().for_each(|v| {
bitmap.set_bit(v as usize, true);
});
// get the semi index
(0..row_count)
.filter_map(|idx| (bitmap.get_bit(idx)).then_some(idx as u32))
.collect::<UInt32Array>()
}
/// Get matched and deduplicated indices
pub(crate) fn get_semi_u64_indices(
row_count: usize,
input_indices: &UInt64Array,
) -> UInt64Array {
let mut bitmap = BooleanBufferBuilder::new(row_count);
bitmap.append_n(row_count, false);
input_indices.iter().flatten().for_each(|v| {
bitmap.set_bit(v as usize, true);
});
// get the semi index
(0..row_count)
.filter_map(|idx| (bitmap.get_bit(idx)).then_some(idx as u64))
.collect::<UInt64Array>()
}
/// Metrics for build & probe joins
#[derive(Clone, Debug)]
pub(crate) struct BuildProbeJoinMetrics {
/// Total time for collecting build-side of join
pub(crate) build_time: metrics::Time,
/// Number of batches consumed by build-side
pub(crate) build_input_batches: metrics::Count,
/// Number of rows consumed by build-side
pub(crate) build_input_rows: metrics::Count,
/// Memory used by build-side in bytes