Repository navigation
Expand file tree
/
Copy pathutils.rs
More file actions
6249 lines (5804 loc) · 227 KB
/
Copy pathutils.rs
File metadata and controls
6249 lines (5804 loc) · 227 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
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
//! Join related functionality used both on logical and physical plans
use std::cmp::{Ordering, min};
use std::collections::HashSet;
use std::fmt::{self, Debug};
use std::future::Future;
use std::iter::once;
use std::ops::Range;
use std::sync::Arc;
use std::task::{Context, Poll};
use crate::metrics::{
self, BaselineMetrics, ExecutionPlanMetricsSet, MetricBuilder, MetricCategory,
MetricType,
};
use crate::projection::{ProjectionExec, ProjectionExpr};
use crate::{
ColumnStatistics, ExecutionPlan, ExecutionPlanProperties, Partitioning,
RangePartitioning, Statistics,
};
// compatibility
pub use super::join_filter::JoinFilter;
///
/// # Public Only for Internal Use:
///
/// This is not a public API and is for internal use only; see [API policy] for details.
///
/// [API policy]: https://datafusion.apache.org/contributor-guide/api-health.html#internal-public-apis
#[doc(hidden)]
pub use super::join_hash_map::JoinHashMapType;
pub use super::join_hash_map::ProbeOffset;
pub use crate::joins::{JoinOn, JoinOnRef};
use arrow::array::{
Array, ArrowPrimitiveType, BooleanBufferBuilder, NativeAdapter, PrimitiveArray,
RecordBatch, RecordBatchOptions, UInt32Array, UInt32Builder, UInt64Array,
builder::UInt64Builder, downcast_array, new_null_array,
};
use arrow::array::{
ArrayRef, BinaryArray, BinaryViewArray, BooleanArray, Date32Array, Date64Array,
Decimal128Array, FixedSizeBinaryArray, Float32Array, Float64Array, Int8Array,
Int16Array, Int32Array, Int64Array, LargeBinaryArray, LargeStringArray, StringArray,
StringViewArray, TimestampMicrosecondArray, TimestampMillisecondArray,
TimestampNanosecondArray, TimestampSecondArray, UInt8Array, UInt16Array,
};
use arrow::buffer::{BooleanBuffer, NullBuffer};
use arrow::compute::{self, take};
use arrow::datatypes::{
ArrowNativeType, Field, Schema, SchemaBuilder, SchemaRef, UInt32Type, UInt64Type,
};
use arrow_ord::ord::{DynComparator, make_comparator};
use arrow_schema::{DataType, SortOptions, TimeUnit};
use datafusion_common::cast::as_boolean_array;
use datafusion_common::float_semantics;
use datafusion_common::hash_utils::RandomState;
use datafusion_common::hash_utils::create_hashes;
use datafusion_common::stats::Precision;
use datafusion_common::utils::memory::RecordBatchMemoryCounter;
use datafusion_common::{
DataFusionError, JoinSide, JoinType, NullEquality, Result, SharedResult,
internal_datafusion_err, internal_err, not_impl_err, plan_err,
};
use datafusion_expr::Operator;
use datafusion_expr::interval_arithmetic::{Interval, comparison_selectivity};
use datafusion_physical_expr::expressions::{BinaryExpr, Column};
use datafusion_physical_expr::utils::collect_columns;
use datafusion_physical_expr::{
LexOrdering, PhysicalExpr, PhysicalExprRef, add_offset_to_expr,
add_offset_to_physical_sort_exprs,
};
use datafusion_physical_expr_common::utils::evaluate_expressions_to_arrays;
use futures::future::{BoxFuture, Shared};
use futures::{FutureExt, ready};
use parking_lot::Mutex;
/// 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: &[(PhysicalExprRef, PhysicalExprRef)],
) -> Result<()> {
let on_left = &on
.iter()
.flat_map(|on| collect_columns(&on.0))
.collect::<HashSet<_>>();
let left_missing = on_left.difference(left).collect::<HashSet<_>>();
let on_right = &on
.iter()
.flat_map(|on| collect_columns(&on.1))
.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(())
}
/// Adjust the right out partitioning to new Column Index
pub fn adjust_right_output_partitioning(
right_partitioning: &Partitioning,
left_columns_len: usize,
) -> Result<Partitioning> {
let result = match right_partitioning {
Partitioning::Hash(exprs, size) => {
let new_exprs = exprs
.iter()
.map(|expr| add_offset_to_expr(Arc::clone(expr), left_columns_len as _))
.collect::<Result<_>>()?;
Partitioning::Hash(new_exprs, *size)
}
Partitioning::Range(range) => {
let ordering = add_offset_to_physical_sort_exprs(
range.ordering().iter().cloned(),
left_columns_len as _,
)?;
let ordering = LexOrdering::new(ordering).ok_or_else(|| {
internal_datafusion_err!(
"Offsetting range partitioning produced an empty ordering"
)
})?;
Partitioning::Range(RangePartitioning::try_new_with_samples(
ordering,
range.samples().to_vec(),
range.partition_count(),
)?)
}
result => result.clone(),
};
Ok(result)
}
/// Calculate the output ordering of a given join operation.
pub fn calculate_join_output_ordering(
left_ordering: Option<&LexOrdering>,
right_ordering: Option<&LexOrdering>,
join_type: JoinType,
left_columns_len: usize,
maintains_input_order: &[bool],
probe_side: Option<JoinSide>,
) -> Result<Option<LexOrdering>> {
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)
&& let Some(right_ordering) = right_ordering.cloned()
{
let right_offset = add_offset_to_physical_sort_exprs(
right_ordering,
left_columns_len as _,
)?;
return if let Some(left_ordering) = left_ordering {
let mut result = left_ordering.clone();
result.extend(right_offset);
Ok(Some(result))
} else {
Ok(LexOrdering::new(right_offset))
};
}
Ok(left_ordering.cloned())
}
[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) {
return if let Some(right_ordering) = right_ordering.cloned() {
let mut right_offset = add_offset_to_physical_sort_exprs(
right_ordering,
left_columns_len as _,
)?;
if let Some(left_ordering) = left_ordering {
right_offset.extend(left_ordering.clone());
}
Ok(LexOrdering::new(right_offset))
} else {
Ok(left_ordering.cloned())
};
}
let Some(right_ordering) = right_ordering else {
return Ok(None);
};
match join_type {
JoinType::Inner | JoinType::Left | JoinType::Full | JoinType::Right => {
add_offset_to_physical_sort_exprs(
right_ordering.clone(),
left_columns_len as _,
)
.map(LexOrdering::new)
}
_ => Ok(Some(right_ordering.clone())),
}
}
// Doesn't maintain ordering, output ordering is None.
[false, false] => Ok(None),
[true, true] => unreachable!("Cannot maintain ordering of both sides"),
_ => unreachable!("Join operators can not have more than two children"),
}
}
/// 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,
}
/// 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??)
JoinType::LeftMark => false,
JoinType::RightMark => false,
};
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 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,
},
)
})
};
let (fields, column_indices): (SchemaBuilder, Vec<ColumnIndex>) = match join_type {
JoinType::Inner | JoinType::Left | JoinType::Full | JoinType::Right => {
// left then right
left_fields().chain(right_fields()).unzip()
}
JoinType::LeftSemi | JoinType::LeftAnti => left_fields().unzip(),
JoinType::LeftMark => {
let right_field = once((
// Nullable: null-aware `LeftMark` joins use NULL for SQL UNKNOWN.
Field::new("mark", DataType::Boolean, true),
ColumnIndex {
index: 0,
side: JoinSide::None,
},
));
left_fields().chain(right_field).unzip()
}
JoinType::RightSemi | JoinType::RightAnti => right_fields().unzip(),
JoinType::RightMark => {
let left_field = once((
// Nullable for symmetry with `LeftMark`; never actually NULL.
Field::new("mark", DataType::Boolean, true),
ColumnIndex {
index: 0,
side: JoinSide::None,
},
));
right_fields().chain(left_field).unzip()
}
};
let (schema1, schema2) = match join_type {
JoinType::Right
| JoinType::RightSemi
| JoinType::RightAnti
| JoinType::RightMark => (left, right),
_ => (right, left),
};
let mut metadata = schema1.metadata().clone();
metadata.extend(schema2.metadata().clone());
(fields.finish().with_metadata(metadata), column_indices)
}
/// A [`OnceAsync`] runs an `async` closure once, where multiple calls to
/// [`OnceAsync::try_once`] return a [`OnceFut`] that resolves to the result of the
/// same computation.
///
/// This is useful for joins where the results of one child are needed to proceed
/// with multiple output stream
///
///
/// For example, in a hash join, one input is buffered and shared across
/// potentially multiple output partitions. Each output partition must wait for
/// the hash table to be built before proceeding.
///
/// Each output partition waits on the same `OnceAsync` before proceeding.
pub(crate) struct OnceAsync<T> {
fut: Mutex<Option<SharedResult<OnceFut<T>>>>,
}
impl<T> Default for OnceAsync<T> {
fn default() -> Self {
Self {
fut: Mutex::new(None),
}
}
}
impl<T> Debug for OnceAsync<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> 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. `f`
/// may fail, in which case its error is returned.
///
/// If this is not the first call, will return a [`OnceFut`] referring
/// to the same future as was returned by the first call - or the same
/// error if the initial call to `f` failed.
pub(crate) fn try_once<F, Fut>(&self, f: F) -> Result<OnceFut<T>>
where
F: FnOnce() -> Result<Fut>,
Fut: Future<Output = Result<T>> + Send + 'static,
{
self.fut
.lock()
.get_or_insert_with(|| f().map(OnceFut::new).map_err(Arc::new))
.clone()
.map_err(DataFusionError::Shared)
}
}
/// 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 total_byte_size: Precision<usize>,
pub column_statistics: Vec<ColumnStatistics>,
}
/// Estimates the output statistics for a join operation based on input statistics.
///
/// # Statistics Propagation
///
/// This function estimates join output statistics using the following approach:
/// - **Row count estimation**: Uses the `on` parameter (equijoin keys) to estimate
/// output cardinality via [`estimate_join_cardinality`]. The estimation is based on
/// column-level statistics (distinct counts, min/max values) of the join keys.
/// - **Column statistics**: Combines column statistics from both inputs. For join types
/// that preserve all columns (Inner, Left, Right, Full), statistics from both sides
/// are concatenated, except null counts: a join repeats and drops rows, so null
/// counts are scaled to the output rows, NULL-padded rows of an outer join add
/// NULLs, and join keys under `NullEqualsNothing` keep only the NULLs of unmatched
/// rows. For semi/anti joins, the preserved side's statistics are normalized as
/// subset estimates.
/// - **Byte size**: For semi/anti joins, sums normalized column byte-size estimates
/// when every output column has one. Other join types return `Precision::Absent`
/// because join output size is difficult to estimate without knowing the actual data.
///
/// # The `on` Parameter
///
/// The `on` parameter represents equijoin keys (e.g., `t1.id = t2.id`). When `on` is
/// empty (as in NestedLoopJoinExec which handles non-equijoin predicates), the
/// cardinality estimation cannot compute selectivity from join keys, and this function
/// returns unknown statistics (`num_rows: Precision::Absent`).
///
/// # Limitations
///
/// - Accounts only for direct column-to-column ordered comparisons in inner join
/// filters. Arbitrary expressions (e.g., `(t1.v1 + t2.v1) % 2 = 0`) are not
/// factored into the cardinality estimation.
/// - Apart from null counts, column statistics for inner/outer joins are simply
/// combined from inputs without adjusting for join selectivity (acknowledged in
/// the code as needing "filter selectivity analysis").
pub(crate) fn estimate_join_statistics(
left_stats: Statistics,
right_stats: Statistics,
on: &JoinOn,
null_equality: NullEquality,
join_type: &JoinType,
schema: &Schema,
filter: Option<&JoinFilter>,
) -> Result<Statistics> {
let filter_selectivity = if *join_type == JoinType::Inner {
filter
.map(|filter| {
estimate_join_filter_selectivity(filter, &left_stats, &right_stats)
})
.transpose()?
.flatten()
} else {
None
};
let join_stats =
estimate_join_cardinality(join_type, left_stats, right_stats, on, null_equality);
let (num_rows, total_byte_size, column_statistics) = match join_stats {
Some(stats) => {
let num_rows = Precision::Inexact(stats.num_rows);
let num_rows = filter_selectivity
.map(|selectivity| num_rows.with_estimated_selectivity(selectivity))
.unwrap_or(num_rows);
(num_rows, stats.total_byte_size, stats.column_statistics)
}
None => (
Precision::Absent,
Precision::Absent,
Statistics::unknown_column(schema),
),
};
Ok(Statistics {
num_rows,
total_byte_size,
column_statistics,
})
}
fn estimate_join_filter_selectivity(
filter: &JoinFilter,
left_stats: &Statistics,
right_stats: &Statistics,
) -> Result<Option<f64>> {
let Some(comparison) = filter.expression().downcast_ref::<BinaryExpr>() else {
return Ok(None);
};
let Some(left_column) = comparison.left().downcast_ref::<Column>() else {
return Ok(None);
};
let Some(right_column) = comparison.right().downcast_ref::<Column>() else {
return Ok(None);
};
if filter.schema().fields().len() != filter.column_indices().len() {
return internal_err!(
"JoinFilter schema has {} fields but {} column mappings",
filter.schema().fields().len(),
filter.column_indices().len()
);
}
let (left_column_stats, left_field) =
join_filter_column_statistics(filter, left_column, left_stats, right_stats)?;
let (right_column_stats, right_field) =
join_filter_column_statistics(filter, right_column, left_stats, right_stats)?;
if !matches!(
comparison.op(),
Operator::Lt | Operator::LtEq | Operator::Gt | Operator::GtEq
) {
return Ok(None);
}
let Some(left_interval) = column_statistics_interval(left_column_stats, left_field)?
else {
return Ok(None);
};
let Some(right_interval) =
column_statistics_interval(right_column_stats, right_field)?
else {
return Ok(None);
};
comparison_selectivity(comparison.op(), &left_interval, &right_interval)
}
fn join_filter_column_statistics<'a>(
filter: &'a JoinFilter,
column: &Column,
left_stats: &'a Statistics,
right_stats: &'a Statistics,
) -> Result<(&'a ColumnStatistics, &'a Field)> {
let compact_index = column.index();
let Some(column_index) = filter.column_indices().get(compact_index) else {
return internal_err!(
"JoinFilter expression column index {compact_index} is outside its {} column mappings",
filter.column_indices().len()
);
};
let Some(field) = filter.schema().fields().get(compact_index) else {
return internal_err!(
"JoinFilter expression column index {compact_index} is outside its {} schema fields",
filter.schema().fields().len()
);
};
let input_column_stats = match column_index.side {
JoinSide::Left => left_stats.column_statistics.get(column_index.index),
JoinSide::Right => right_stats.column_statistics.get(column_index.index),
JoinSide::None => {
return internal_err!("JoinFilter column mapping has no input side");
}
};
let Some(input_column_stats) = input_column_stats else {
return internal_err!(
"JoinFilter {:?} column index {} is outside the input statistics",
column_index.side,
column_index.index
);
};
Ok((input_column_stats, field))
}
fn column_statistics_interval(
column_stats: &ColumnStatistics,
field: &Field,
) -> Result<Option<Interval>> {
let (Some(min), Some(max)) = (
column_stats.min_value.get_value(),
column_stats.max_value.get_value(),
) else {
return Ok(None);
};
if min.is_null()
|| max.is_null()
|| min.data_type() != max.data_type()
|| min.data_type() != *field.data_type()
|| min > max
{
return Ok(None);
}
Interval::try_new(min.clone(), max.clone()).map(Some)
}
// 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,
null_equality: NullEquality,
) -> Option<PartialJoinStatistics> {
let on_column_indices = on
.iter()
.map(|(left, right)| equijoin_column_indices(left, right))
.collect::<Vec<_>>();
let (left_key_stats, right_key_stats) = on_column_indices
.iter()
.map(|indices| match indices {
Some((left_index, right_index)) => (
left_stats.column_statistics[*left_index].clone(),
right_stats.column_statistics[*right_index].clone(),
),
None => (
ColumnStatistics::new_unknown(),
ColumnStatistics::new_unknown(),
),
})
.unzip::<_, _, Vec<_>, Vec<_>>();
match join_type {
JoinType::Inner | JoinType::Left | JoinType::Right | JoinType::Full => {
let left_keys_stats = Statistics {
num_rows: left_stats.num_rows,
total_byte_size: Precision::Absent,
column_statistics: left_key_stats,
};
let right_keys_stats = Statistics {
num_rows: right_stats.num_rows,
total_byte_size: Precision::Absent,
column_statistics: right_key_stats,
};
// For a single null-safe key, every left NULL matches every right
// NULL. With more keys their correlation is unknown.
let null_matches =
if null_equality == NullEquality::NullEqualsNull && on.len() == 1 {
left_keys_stats.column_statistics[0]
.null_count
.multiply(&right_keys_stats.column_statistics[0].null_count)
.to_inexact()
} else {
Precision::Absent
};
let inner_rows =
*estimate_inner_join_cardinality(&left_keys_stats, &right_keys_stats)?
.get_value()?;
let inner_rows =
inner_rows.max(null_matches.get_value().copied().unwrap_or(0));
let left_rows = left_stats.num_rows.get_value().copied();
let right_rows = right_stats.num_rows.get_value().copied();
let left_preserved = matches!(join_type, JoinType::Left | JoinType::Full);
let right_preserved = matches!(join_type, JoinType::Right | JoinType::Full);
let unmatched_left = if left_preserved {
estimate_join_unmatched_rows(
&left_keys_stats,
&right_keys_stats,
inner_rows,
null_equality,
)?
} else {
0
};
let unmatched_right = if right_preserved {
estimate_join_unmatched_rows(
&right_keys_stats,
&left_keys_stats,
inner_rows,
null_equality,
)?
} else {
0
};
let left_side = JoinSideRows {
input: left_rows,
own: inner_rows.saturating_add(unmatched_left),
padded: right_preserved.then_some(unmatched_right),
preserved: left_preserved,
};
let right_side = JoinSideRows {
input: right_rows,
own: inner_rows.saturating_add(unmatched_right),
padded: left_preserved.then_some(unmatched_left),
preserved: right_preserved,
};
let mut left_column_statistics = left_stats.column_statistics;
let mut right_column_statistics = right_stats.column_statistics;
let (left_keys, right_keys): (Vec<_>, Vec<_>) = on_column_indices
.iter()
.flatten()
.map(|&(left, right)| {
(
(left, right_column_statistics[right].null_count),
(right, left_column_statistics[left].null_count),
)
})
.unzip();
estimate_join_null_counts(
&mut left_column_statistics,
&left_side,
&left_keys,
null_equality,
null_matches,
);
estimate_join_null_counts(
&mut right_column_statistics,
&right_side,
&right_keys,
null_equality,
null_matches,
);
Some(PartialJoinStatistics {
num_rows: inner_rows
.saturating_add(unmatched_left)
.saturating_add(unmatched_right),
total_byte_size: Precision::Absent,
// Apart from the null counts estimated above, we 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_column_statistics
.into_iter()
.chain(right_column_statistics)
.collect(),
})
}
JoinType::LeftSemi
| JoinType::RightSemi
| JoinType::LeftAnti
| JoinType::RightAnti => {
let is_left = matches!(join_type, JoinType::LeftSemi | JoinType::LeftAnti);
let is_anti = matches!(join_type, JoinType::LeftAnti | JoinType::RightAnti);
let (outer_stats, inner_stats, outer_key_stats, inner_key_stats) = if is_left
{
(left_stats, right_stats, left_key_stats, right_key_stats)
} else {
(right_stats, left_stats, right_key_stats, left_key_stats)
};
let outer_rows = *outer_stats.num_rows.get_value()?;
let outer_join_key_stats = Statistics {
num_rows: outer_stats.num_rows,
total_byte_size: Precision::Absent,
column_statistics: outer_key_stats.clone(),
};
let inner_join_key_stats = Statistics {
num_rows: inner_stats.num_rows,
total_byte_size: Precision::Absent,
column_statistics: inner_key_stats.clone(),
};
let semi_cardinality =
if estimate_disjoint_inputs(&outer_join_key_stats, &inner_join_key_stats)
.is_some()
{
// If join keys are disjoint, no rows will match
Some(0)
} else {
estimate_semi_join_cardinality(
&outer_stats.num_rows,
&inner_stats.num_rows,
&outer_key_stats,
&inner_key_stats,
null_equality,
)
};
// Semi joins keep the matching rows; anti joins keep the rest. When no
// estimate is available, conservatively assume all outer rows pass.
let cardinality = match (semi_cardinality, is_anti) {
(Some(semi), true) => outer_rows.saturating_sub(semi),
(Some(semi), false) => semi,
(None, _) => outer_rows,
};
// The outer side is the one whose columns a semi/anti join emits, so
// its statistics are the ones to normalize into the subset estimate.
let Statistics {
num_rows: preserved_num_rows,
column_statistics: preserved_column_statistics,
..
} = outer_stats;
let preserved_join_key_indices = on_column_indices
.iter()
.filter_map(|&indices| {
indices.map(
|(left_index, right_index)| {
if is_left { left_index } else { right_index }
},
)
})
.collect::<Vec<_>>();
let column_statistics = normalize_semi_anti_join_column_statistics(
preserved_column_statistics,
&preserved_num_rows,
cardinality,
&preserved_join_key_indices,
is_anti,
null_equality,
);
let total_byte_size =
total_byte_size_from_column_statistics(&column_statistics);
Some(PartialJoinStatistics {
num_rows: cardinality,
total_byte_size,
column_statistics,
})
}
JoinType::LeftMark => {
let num_rows = *left_stats.num_rows.get_value()?;
let mut column_statistics = left_stats.column_statistics;
column_statistics.push(ColumnStatistics::new_unknown());
Some(PartialJoinStatistics {
num_rows,
total_byte_size: Precision::Absent,
column_statistics,
})
}
JoinType::RightMark => {
let num_rows = *right_stats.num_rows.get_value()?;
let mut column_statistics = right_stats.column_statistics;
column_statistics.push(ColumnStatistics::new_unknown());
Some(PartialJoinStatistics {
num_rows,
total_byte_size: Precision::Absent,
column_statistics,
})
}
}
}
fn equijoin_column_indices(
left: &PhysicalExprRef,
right: &PhysicalExprRef,
) -> Option<(usize, usize)> {
Some((
left.downcast_ref::<Column>()?.index(),
right.downcast_ref::<Column>()?.index(),
))
}
/// Adjusts the preserved input's column statistics to describe the subset of
/// rows a semi or anti join emits. Most values become estimates (marked
/// inexact) bounded by the smaller output row count:
///
/// - `null_count` and `byte_size` are scaled by the output/input row ratio.
/// - `distinct_count` is capped at the number of non-null output rows.
/// - `sum_value` is dropped, since the input sum does not apply to the subset.
///
/// Join-key columns are the exception for `null_count`: under regular SQL
/// equality, null keys never match, so a semi join keeps none of those rows and
/// an anti join keeps all of them. Under null-equal joins, null keys can match
/// and are treated like the rest of the subset.
fn normalize_semi_anti_join_column_statistics(
column_statistics: Vec<ColumnStatistics>,
input_num_rows: &Precision<usize>,
output_num_rows: usize,
join_key_indices: &[usize],
is_anti: bool,
null_equality: NullEquality,
) -> Vec<ColumnStatistics> {
let input_num_rows = input_num_rows.get_value().copied().unwrap_or(0);
column_statistics
.into_iter()
.enumerate()
.map(|(idx, stats)| {
let mut stats = stats.to_inexact();
stats.null_count = if join_key_indices.contains(&idx) {
normalize_semi_anti_join_key_null_count(
stats.null_count,
input_num_rows,
output_num_rows,
is_anti,
null_equality,
)
} else {
scale_subset_count(stats.null_count, input_num_rows, output_num_rows)
.min(&Precision::Inexact(output_num_rows))
};
let max_distinct_count = stats
.null_count
.get_value()
.map(|null_count| output_num_rows.saturating_sub(*null_count))
.unwrap_or(output_num_rows);
stats.distinct_count = stats
.distinct_count
.min(&Precision::Inexact(max_distinct_count));
stats.byte_size =
scale_subset_count(stats.byte_size, input_num_rows, output_num_rows);
stats.sum_value = Precision::Absent;
stats
})
.collect()
}
fn normalize_semi_anti_join_key_null_count(
null_count: Precision<usize>,
input_num_rows: usize,
output_num_rows: usize,
is_anti: bool,
null_equality: NullEquality,
) -> Precision<usize> {
match (is_anti, null_equality) {
(false, NullEquality::NullEqualsNothing) => Precision::Exact(0),
(true, NullEquality::NullEqualsNothing) => null_count
.to_inexact()
.min(&Precision::Inexact(output_num_rows)),
(_, NullEquality::NullEqualsNull) => {
scale_subset_count(null_count, input_num_rows, output_num_rows)
.min(&Precision::Inexact(output_num_rows))
}
}
}
/// Estimates input rows with no match. Inner-join rows count pairs, so they
/// only bound the number of matching input rows when the keys repeat.
fn estimate_join_unmatched_rows(
input: &Statistics,
other: &Statistics,
inner_rows: usize,
null_equality: NullEquality,
) -> Option<usize> {
let rows = *input.num_rows.get_value()?;
// The semi estimate uses non-NULL NDV overlap, so it can miss NULL
// matches. With one null-safe key, every input NULL has a match if the
// other side has any NULLs. This bounds matched input rows, not pairs.
let matched_nulls = match (
null_equality,
input.column_statistics.as_slice(),
other.column_statistics.as_slice(),
) {
(NullEquality::NullEqualsNull, [input], [other])
if other.null_count.get_value().is_some_and(|&count| count > 0) =>
{
input.null_count.get_value().copied().unwrap_or(0)
}
_ => 0,
};
let matched = estimate_semi_join_cardinality(
&input.num_rows,
&other.num_rows,
&input.column_statistics,
&other.column_statistics,
null_equality,
)
.unwrap_or(inner_rows)
.max(matched_nulls)
.min(inner_rows);
// A NULL in any key prevents a match under ordinary equality. The same
// holds for null-safe equality when the other key has no NULLs.
let unmatched_nulls = input
.column_statistics
.iter()
.zip(&other.column_statistics)
.filter(|(_, other)| {
null_equality == NullEquality::NullEqualsNothing
|| other.null_count == Precision::Exact(0)
})
.filter_map(|(input, _)| input.null_count.get_value().copied())
.max()
.unwrap_or(0)
.min(rows);
Some(rows.saturating_sub(matched).max(unmatched_nulls))
}
/// Row counts for one side of a join that keeps both sides' columns.
struct JoinSideRows {
/// Rows of this side's input, when known.
input: Option<usize>,
/// Output rows that carry this side's values.
own: usize,
/// Estimated output rows where this side's columns are NULL padding, or
/// `None` when the join never pads this side.
padded: Option<usize>,
/// Whether the join keeps this side's unmatched rows.
preserved: bool,
}
/// Estimates the null counts of one side's columns in the output of a join
/// that keeps both sides' columns. A join repeats and drops rows, so a null
/// count scales with the rows that carry the column, and padding adds NULLs.