forked from apache/datafusion
-
Notifications
You must be signed in to change notification settings - Fork 0
/
builder.rs
1992 lines (1789 loc) · 69.2 KB
/
builder.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.
//! This module provides a builder for creating LogicalPlans
use crate::dml::{CopyOptions, CopyTo};
use crate::expr::Alias;
use crate::expr_rewriter::{
coerce_plan_expr_for_schema, normalize_col,
normalize_col_with_schemas_and_ambiguity_check, normalize_cols,
rewrite_sort_cols_by_aggs,
};
use crate::type_coercion::binary::comparison_coercion;
use crate::utils::{columnize_expr, compare_sort_expr};
use crate::{and, binary_expr, DmlStatement, Operator, WriteOp};
use crate::{
logical_plan::{
Aggregate, Analyze, CrossJoin, Distinct, EmptyRelation, Explain, Filter, Join,
JoinConstraint, JoinType, Limit, LogicalPlan, Partitioning, PlanType, Prepare,
Projection, Repartition, Sort, SubqueryAlias, TableScan, Union, Unnest, Values,
Window,
},
utils::{
can_hash, expand_qualified_wildcard, expand_wildcard,
find_valid_equijoin_key_pair, group_window_expr_by_sort_keys,
},
Expr, ExprSchemable, TableSource,
};
use arrow::datatypes::{DataType, Schema, SchemaRef};
use datafusion_common::plan_err;
use datafusion_common::UnnestOptions;
use datafusion_common::{
display::ToStringifiedPlan, Column, DFField, DFSchema, DFSchemaRef, DataFusionError,
FileType, FunctionalDependencies, OwnedTableReference, Result, ScalarValue,
TableReference, ToDFSchema,
};
use std::any::Any;
use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
use std::convert::TryFrom;
use std::sync::Arc;
/// Default table name for unnamed table
pub const UNNAMED_TABLE: &str = "?table?";
/// Builder for logical plans
///
/// ```
/// # use datafusion_expr::{lit, col, LogicalPlanBuilder, logical_plan::table_scan};
/// # use datafusion_common::Result;
/// # use arrow::datatypes::{Schema, DataType, Field};
/// #
/// # fn main() -> Result<()> {
/// #
/// # fn employee_schema() -> Schema {
/// # Schema::new(vec![
/// # Field::new("id", DataType::Int32, false),
/// # Field::new("first_name", DataType::Utf8, false),
/// # Field::new("last_name", DataType::Utf8, false),
/// # Field::new("state", DataType::Utf8, false),
/// # Field::new("salary", DataType::Int32, false),
/// # ])
/// # }
/// #
/// // Create a plan similar to
/// // SELECT last_name
/// // FROM employees
/// // WHERE salary < 1000
/// let plan = table_scan(
/// Some("employee"),
/// &employee_schema(),
/// None,
/// )?
/// // Keep only rows where salary < 1000
/// .filter(col("salary").lt_eq(lit(1000)))?
/// // only show "last_name" in the final results
/// .project(vec![col("last_name")])?
/// .build()?;
///
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct LogicalPlanBuilder {
plan: LogicalPlan,
}
impl LogicalPlanBuilder {
/// Create a builder from an existing plan
pub fn from(plan: LogicalPlan) -> Self {
Self { plan }
}
/// Return the output schema of the plan build so far
pub fn schema(&self) -> &DFSchemaRef {
self.plan.schema()
}
/// Create an empty relation.
///
/// `produce_one_row` set to true means this empty node needs to produce a placeholder row.
pub fn empty(produce_one_row: bool) -> Self {
Self::from(LogicalPlan::EmptyRelation(EmptyRelation {
produce_one_row,
schema: DFSchemaRef::new(DFSchema::empty()),
}))
}
/// Create a values list based relation, and the schema is inferred from data, consuming
/// `value`. See the [Postgres VALUES](https://www.postgresql.org/docs/current/queries-values.html)
/// documentation for more details.
///
/// By default, it assigns the names column1, column2, etc. to the columns of a VALUES table.
/// The column names are not specified by the SQL standard and different database systems do it differently,
/// so it's usually better to override the default names with a table alias list.
///
/// If the values include params/binders such as $1, $2, $3, etc, then the `param_data_types` should be provided.
pub fn values(mut values: Vec<Vec<Expr>>) -> Result<Self> {
if values.is_empty() {
return plan_err!("Values list cannot be empty");
}
let n_cols = values[0].len();
if n_cols == 0 {
return plan_err!("Values list cannot be zero length");
}
let empty_schema = DFSchema::empty();
let mut field_types: Vec<Option<DataType>> = Vec::with_capacity(n_cols);
for _ in 0..n_cols {
field_types.push(None);
}
// hold all the null holes so that we can correct their data types later
let mut nulls: Vec<(usize, usize)> = Vec::new();
for (i, row) in values.iter().enumerate() {
if row.len() != n_cols {
return plan_err!(
"Inconsistent data length across values list: got {} values in row {} but expected {}",
row.len(),
i,
n_cols
);
}
field_types = row
.iter()
.enumerate()
.map(|(j, expr)| {
if let Expr::Literal(ScalarValue::Null) = expr {
nulls.push((i, j));
Ok(field_types[j].clone())
} else {
let data_type = expr.get_type(&empty_schema)?;
if let Some(prev_data_type) = &field_types[j] {
if prev_data_type != &data_type {
return plan_err!("Inconsistent data type across values list at row {i} column {j}");
}
}
Ok(Some(data_type))
}
})
.collect::<Result<Vec<Option<DataType>>>>()?;
}
let fields = field_types
.iter()
.enumerate()
.map(|(j, data_type)| {
// naming is following convention https://www.postgresql.org/docs/current/queries-values.html
let name = &format!("column{}", j + 1);
DFField::new_unqualified(
name,
data_type.clone().unwrap_or(DataType::Utf8),
true,
)
})
.collect::<Vec<_>>();
for (i, j) in nulls {
values[i][j] = Expr::Literal(ScalarValue::try_from(fields[j].data_type())?);
}
let schema =
DFSchemaRef::new(DFSchema::new_with_metadata(fields, HashMap::new())?);
Ok(Self::from(LogicalPlan::Values(Values { schema, values })))
}
/// Convert a table provider into a builder with a TableScan
///
/// Note that if you pass a string as `table_name`, it is treated
/// as a SQL identifier, as described on [`TableReference`] and
/// thus is normalized
///
/// # Example:
/// ```
/// # use datafusion_expr::{lit, col, LogicalPlanBuilder,
/// # logical_plan::builder::LogicalTableSource, logical_plan::table_scan
/// # };
/// # use std::sync::Arc;
/// # use arrow::datatypes::{Schema, DataType, Field};
/// # use datafusion_common::TableReference;
/// #
/// # let employee_schema = Arc::new(Schema::new(vec![
/// # Field::new("id", DataType::Int32, false),
/// # ])) as _;
/// # let table_source = Arc::new(LogicalTableSource::new(employee_schema));
/// // Scan table_source with the name "mytable" (after normalization)
/// # let table = table_source.clone();
/// let scan = LogicalPlanBuilder::scan("MyTable", table, None);
///
/// // Scan table_source with the name "MyTable" by enclosing in quotes
/// # let table = table_source.clone();
/// let scan = LogicalPlanBuilder::scan(r#""MyTable""#, table, None);
///
/// // Scan table_source with the name "MyTable" by forming the table reference
/// # let table = table_source.clone();
/// let table_reference = TableReference::bare("MyTable");
/// let scan = LogicalPlanBuilder::scan(table_reference, table, None);
/// ```
pub fn scan(
table_name: impl Into<OwnedTableReference>,
table_source: Arc<dyn TableSource>,
projection: Option<Vec<usize>>,
) -> Result<Self> {
Self::scan_with_filters(table_name, table_source, projection, vec![])
}
/// Create a [CopyTo] for copying the contents of this builder to the specified file(s)
pub fn copy_to(
input: LogicalPlan,
output_url: String,
file_format: FileType,
single_file_output: bool,
copy_options: CopyOptions,
) -> Result<Self> {
Ok(Self::from(LogicalPlan::Copy(CopyTo {
input: Arc::new(input),
output_url,
file_format,
single_file_output,
copy_options,
})))
}
/// Create a [DmlStatement] for inserting the contents of this builder into the named table
pub fn insert_into(
input: LogicalPlan,
table_name: impl Into<OwnedTableReference>,
table_schema: &Schema,
overwrite: bool,
) -> Result<Self> {
let table_schema = table_schema.clone().to_dfschema_ref()?;
let op = if overwrite {
WriteOp::InsertOverwrite
} else {
WriteOp::InsertInto
};
Ok(Self::from(LogicalPlan::Dml(DmlStatement {
table_name: table_name.into(),
table_schema,
op,
input: Arc::new(input),
})))
}
/// Convert a table provider into a builder with a TableScan
pub fn scan_with_filters(
table_name: impl Into<OwnedTableReference>,
table_source: Arc<dyn TableSource>,
projection: Option<Vec<usize>>,
filters: Vec<Expr>,
) -> Result<Self> {
let table_name = table_name.into();
if table_name.table().is_empty() {
return plan_err!("table_name cannot be empty");
}
let schema = table_source.schema();
let func_dependencies = FunctionalDependencies::new_from_constraints(
table_source.constraints(),
schema.fields.len(),
);
let projected_schema = projection
.as_ref()
.map(|p| {
let projected_func_dependencies =
func_dependencies.project_functional_dependencies(p, p.len());
DFSchema::new_with_metadata(
p.iter()
.map(|i| {
DFField::from_qualified(
table_name.clone(),
schema.field(*i).clone(),
)
})
.collect(),
schema.metadata().clone(),
)
.map(|df_schema| {
df_schema.with_functional_dependencies(projected_func_dependencies)
})
})
.unwrap_or_else(|| {
DFSchema::try_from_qualified_schema(table_name.clone(), &schema).map(
|df_schema| df_schema.with_functional_dependencies(func_dependencies),
)
})?;
let table_scan = LogicalPlan::TableScan(TableScan {
table_name,
source: table_source,
projected_schema: Arc::new(projected_schema),
projection,
filters,
fetch: None,
});
Ok(Self::from(table_scan))
}
/// Wrap a plan in a window
pub fn window_plan(
input: LogicalPlan,
window_exprs: Vec<Expr>,
) -> Result<LogicalPlan> {
let mut plan = input;
let mut groups = group_window_expr_by_sort_keys(&window_exprs)?;
// To align with the behavior of PostgreSQL, we want the sort_keys sorted as same rule as PostgreSQL that first
// we compare the sort key themselves and if one window's sort keys are a prefix of another
// put the window with more sort keys first. so more deeply sorted plans gets nested further down as children.
// The sort_by() implementation here is a stable sort.
// Note that by this rule if there's an empty over, it'll be at the top level
groups.sort_by(|(key_a, _), (key_b, _)| {
for ((first, _), (second, _)) in key_a.iter().zip(key_b.iter()) {
let key_ordering = compare_sort_expr(first, second, plan.schema());
match key_ordering {
Ordering::Less => {
return Ordering::Less;
}
Ordering::Greater => {
return Ordering::Greater;
}
Ordering::Equal => {}
}
}
key_b.len().cmp(&key_a.len())
});
for (_, exprs) in groups {
let window_exprs = exprs.into_iter().cloned().collect::<Vec<_>>();
// Partition and sorting is done at physical level, see the EnforceDistribution
// and EnforceSorting rules.
plan = LogicalPlanBuilder::from(plan)
.window(window_exprs)?
.build()?;
}
Ok(plan)
}
/// Apply a projection without alias.
pub fn project(
self,
expr: impl IntoIterator<Item = impl Into<Expr>>,
) -> Result<Self> {
Ok(Self::from(project(self.plan, expr)?))
}
/// Select the given column indices
pub fn select(self, indices: impl IntoIterator<Item = usize>) -> Result<Self> {
let fields = self.plan.schema().fields();
let exprs: Vec<_> = indices
.into_iter()
.map(|x| Expr::Column(fields[x].qualified_column()))
.collect();
self.project(exprs)
}
/// Apply a filter
pub fn filter(self, expr: impl Into<Expr>) -> Result<Self> {
let expr = normalize_col(expr.into(), &self.plan)?;
Ok(Self::from(LogicalPlan::Filter(Filter::try_new(
expr,
Arc::new(self.plan),
)?)))
}
/// Make a builder for a prepare logical plan from the builder's plan
pub fn prepare(self, name: String, data_types: Vec<DataType>) -> Result<Self> {
Ok(Self::from(LogicalPlan::Prepare(Prepare {
name,
data_types,
input: Arc::new(self.plan),
})))
}
/// Limit the number of rows returned
///
/// `skip` - Number of rows to skip before fetch any row.
///
/// `fetch` - Maximum number of rows to fetch, after skipping `skip` rows,
/// if specified.
pub fn limit(self, skip: usize, fetch: Option<usize>) -> Result<Self> {
Ok(Self::from(LogicalPlan::Limit(Limit {
skip,
fetch,
input: Arc::new(self.plan),
})))
}
/// Apply an alias
pub fn alias(self, alias: impl Into<OwnedTableReference>) -> Result<Self> {
Ok(Self::from(subquery_alias(self.plan, alias)?))
}
/// Add missing sort columns to all downstream projection
///
/// Thus, if you have a LogialPlan that selects A and B and have
/// not requested a sort by C, this code will add C recursively to
/// all input projections.
///
/// Adding a new column is not correct if there is a `Distinct`
/// node, which produces only distinct values of its
/// inputs. Adding a new column to its input will result in
/// potententially different results than with the original column.
///
/// For example, if the input is like:
///
/// Distinct(A, B)
///
/// If the input looks like
///
/// a | b | c
/// --+---+---
/// 1 | 2 | 3
/// 1 | 2 | 4
///
/// Distinct (A, B) --> (1,2)
///
/// But Distinct (A, B, C) --> (1, 2, 3), (1, 2, 4)
/// (which will appear as a (1, 2), (1, 2) if a and b are projected
///
/// See <https://github.com/apache/arrow-datafusion/issues/5065> for more details
fn add_missing_columns(
curr_plan: LogicalPlan,
missing_cols: &[Column],
is_distinct: bool,
) -> Result<LogicalPlan> {
match curr_plan {
LogicalPlan::Projection(Projection {
input,
mut expr,
schema: _,
}) if missing_cols.iter().all(|c| input.schema().has_column(c)) => {
let mut missing_exprs = missing_cols
.iter()
.map(|c| normalize_col(Expr::Column(c.clone()), &input))
.collect::<Result<Vec<_>>>()?;
// Do not let duplicate columns to be added, some of the
// missing_cols may be already present but without the new
// projected alias.
missing_exprs.retain(|e| !expr.contains(e));
if is_distinct {
Self::ambiguous_distinct_check(&missing_exprs, missing_cols, &expr)?;
}
expr.extend(missing_exprs);
Ok(project((*input).clone(), expr)?)
}
_ => {
let is_distinct =
is_distinct || matches!(curr_plan, LogicalPlan::Distinct(_));
let new_inputs = curr_plan
.inputs()
.into_iter()
.map(|input_plan| {
Self::add_missing_columns(
(*input_plan).clone(),
missing_cols,
is_distinct,
)
})
.collect::<Result<Vec<_>>>()?;
curr_plan.with_new_inputs(&new_inputs)
}
}
}
fn ambiguous_distinct_check(
missing_exprs: &[Expr],
missing_cols: &[Column],
projection_exprs: &[Expr],
) -> Result<()> {
if missing_exprs.is_empty() {
return Ok(());
}
// if the missing columns are all only aliases for things in
// the existing select list, it is ok
//
// This handles the special case for
// SELECT col as <alias> ORDER BY <alias>
//
// As described in https://github.com/apache/arrow-datafusion/issues/5293
let all_aliases = missing_exprs.iter().all(|e| {
projection_exprs.iter().any(|proj_expr| {
if let Expr::Alias(Alias { expr, .. }) = proj_expr {
e == expr.as_ref()
} else {
false
}
})
});
if all_aliases {
return Ok(());
}
let missing_col_names = missing_cols
.iter()
.map(|col| col.flat_name())
.collect::<String>();
plan_err!("For SELECT DISTINCT, ORDER BY expressions {missing_col_names} must appear in select list")
}
/// Apply a sort
pub fn sort(
self,
exprs: impl IntoIterator<Item = impl Into<Expr>> + Clone,
) -> Result<Self> {
let exprs = rewrite_sort_cols_by_aggs(exprs, &self.plan)?;
let schema = self.plan.schema();
// Collect sort columns that are missing in the input plan's schema
let mut missing_cols: Vec<Column> = vec![];
exprs
.clone()
.into_iter()
.try_for_each::<_, Result<()>>(|expr| {
let columns = expr.to_columns()?;
columns.into_iter().for_each(|c| {
if schema.field_from_column(&c).is_err() {
missing_cols.push(c);
}
});
Ok(())
})?;
if missing_cols.is_empty() {
return Ok(Self::from(LogicalPlan::Sort(Sort {
expr: normalize_cols(exprs, &self.plan)?,
input: Arc::new(self.plan),
fetch: None,
})));
}
// remove pushed down sort columns
let new_expr = schema
.fields()
.iter()
.map(|f| Expr::Column(f.qualified_column()))
.collect();
let is_distinct = false;
let plan = Self::add_missing_columns(self.plan, &missing_cols, is_distinct)?;
let sort_plan = LogicalPlan::Sort(Sort {
expr: normalize_cols(exprs, &plan)?,
input: Arc::new(plan),
fetch: None,
});
Ok(Self::from(LogicalPlan::Projection(Projection::try_new(
new_expr,
Arc::new(sort_plan),
)?)))
}
/// Apply a union, preserving duplicate rows
pub fn union(self, plan: LogicalPlan) -> Result<Self> {
Ok(Self::from(union(self.plan, plan)?))
}
/// Apply a union, removing duplicate rows
pub fn union_distinct(self, plan: LogicalPlan) -> Result<Self> {
let left_plan: LogicalPlan = self.plan;
let right_plan: LogicalPlan = plan;
Ok(Self::from(LogicalPlan::Distinct(Distinct {
input: Arc::new(union(left_plan, right_plan)?),
})))
}
/// Apply deduplication: Only distinct (different) values are returned)
pub fn distinct(self) -> Result<Self> {
Ok(Self::from(LogicalPlan::Distinct(Distinct {
input: Arc::new(self.plan),
})))
}
/// Apply a join with on constraint.
///
/// Filter expression expected to contain non-equality predicates that can not be pushed
/// down to any of join inputs.
/// In case of outer join, filter applied to only matched rows.
pub fn join(
self,
right: LogicalPlan,
join_type: JoinType,
join_keys: (Vec<impl Into<Column>>, Vec<impl Into<Column>>),
filter: Option<Expr>,
) -> Result<Self> {
self.join_detailed(right, join_type, join_keys, filter, false)
}
pub(crate) fn normalize(
plan: &LogicalPlan,
column: impl Into<Column> + Clone,
) -> Result<Column> {
let schema = plan.schema();
let fallback_schemas = plan.fallback_normalize_schemas();
let using_columns = plan.using_columns()?;
column.into().normalize_with_schemas_and_ambiguity_check(
&[&[schema], &fallback_schemas],
&using_columns,
)
}
/// Apply a join with on constraint and specified null equality
/// If null_equals_null is true then null == null, else null != null
pub fn join_detailed(
self,
right: LogicalPlan,
join_type: JoinType,
join_keys: (Vec<impl Into<Column>>, Vec<impl Into<Column>>),
filter: Option<Expr>,
null_equals_null: bool,
) -> Result<Self> {
if join_keys.0.len() != join_keys.1.len() {
return plan_err!("left_keys and right_keys were not the same length");
}
let filter = if let Some(expr) = filter {
let filter = normalize_col_with_schemas_and_ambiguity_check(
expr,
&[&[self.schema(), right.schema()]],
&[],
)?;
Some(filter)
} else {
None
};
let (left_keys, right_keys): (Vec<Result<Column>>, Vec<Result<Column>>) =
join_keys
.0
.into_iter()
.zip(join_keys.1)
.map(|(l, r)| {
let l = l.into();
let r = r.into();
match (&l.relation, &r.relation) {
(Some(lr), Some(rr)) => {
let l_is_left =
self.plan.schema().field_with_qualified_name(lr, &l.name);
let l_is_right =
right.schema().field_with_qualified_name(lr, &l.name);
let r_is_left =
self.plan.schema().field_with_qualified_name(rr, &r.name);
let r_is_right =
right.schema().field_with_qualified_name(rr, &r.name);
match (l_is_left, l_is_right, r_is_left, r_is_right) {
(_, Ok(_), Ok(_), _) => (Ok(r), Ok(l)),
(Ok(_), _, _, Ok(_)) => (Ok(l), Ok(r)),
_ => (
Self::normalize(&self.plan, l),
Self::normalize(&right, r),
),
}
}
(Some(lr), None) => {
let l_is_left =
self.plan.schema().field_with_qualified_name(lr, &l.name);
let l_is_right =
right.schema().field_with_qualified_name(lr, &l.name);
match (l_is_left, l_is_right) {
(Ok(_), _) => (Ok(l), Self::normalize(&right, r)),
(_, Ok(_)) => (Self::normalize(&self.plan, r), Ok(l)),
_ => (
Self::normalize(&self.plan, l),
Self::normalize(&right, r),
),
}
}
(None, Some(rr)) => {
let r_is_left =
self.plan.schema().field_with_qualified_name(rr, &r.name);
let r_is_right =
right.schema().field_with_qualified_name(rr, &r.name);
match (r_is_left, r_is_right) {
(Ok(_), _) => (Ok(r), Self::normalize(&right, l)),
(_, Ok(_)) => (Self::normalize(&self.plan, l), Ok(r)),
_ => (
Self::normalize(&self.plan, l),
Self::normalize(&right, r),
),
}
}
(None, None) => {
let mut swap = false;
let left_key = Self::normalize(&self.plan, l.clone())
.or_else(|_| {
swap = true;
Self::normalize(&right, l)
});
if swap {
(Self::normalize(&self.plan, r), left_key)
} else {
(left_key, Self::normalize(&right, r))
}
}
}
})
.unzip();
let left_keys = left_keys.into_iter().collect::<Result<Vec<Column>>>()?;
let right_keys = right_keys.into_iter().collect::<Result<Vec<Column>>>()?;
let on = left_keys
.into_iter()
.zip(right_keys)
.map(|(l, r)| (Expr::Column(l), Expr::Column(r)))
.collect();
let join_schema =
build_join_schema(self.plan.schema(), right.schema(), &join_type)?;
Ok(Self::from(LogicalPlan::Join(Join {
left: Arc::new(self.plan),
right: Arc::new(right),
on,
filter,
join_type,
join_constraint: JoinConstraint::On,
schema: DFSchemaRef::new(join_schema),
null_equals_null,
})))
}
/// Apply a join with using constraint, which duplicates all join columns in output schema.
pub fn join_using(
self,
right: LogicalPlan,
join_type: JoinType,
using_keys: Vec<impl Into<Column> + Clone>,
) -> Result<Self> {
let left_keys: Vec<Column> = using_keys
.clone()
.into_iter()
.map(|c| Self::normalize(&self.plan, c))
.collect::<Result<_>>()?;
let right_keys: Vec<Column> = using_keys
.into_iter()
.map(|c| Self::normalize(&right, c))
.collect::<Result<_>>()?;
let on: Vec<(_, _)> = left_keys.into_iter().zip(right_keys).collect();
let join_schema =
build_join_schema(self.plan.schema(), right.schema(), &join_type)?;
let mut join_on: Vec<(Expr, Expr)> = vec![];
let mut filters: Option<Expr> = None;
for (l, r) in &on {
if self.plan.schema().has_column(l)
&& right.schema().has_column(r)
&& can_hash(self.plan.schema().field_from_column(l)?.data_type())
{
join_on.push((Expr::Column(l.clone()), Expr::Column(r.clone())));
} else if self.plan.schema().has_column(l)
&& right.schema().has_column(r)
&& can_hash(self.plan.schema().field_from_column(r)?.data_type())
{
join_on.push((Expr::Column(r.clone()), Expr::Column(l.clone())));
} else {
let expr = binary_expr(
Expr::Column(l.clone()),
Operator::Eq,
Expr::Column(r.clone()),
);
match filters {
None => filters = Some(expr),
Some(filter_expr) => filters = Some(and(expr, filter_expr)),
}
}
}
if join_on.is_empty() {
let join = Self::from(self.plan).cross_join(right)?;
join.filter(filters.ok_or_else(|| {
DataFusionError::Internal("filters should not be None here".to_string())
})?)
} else {
Ok(Self::from(LogicalPlan::Join(Join {
left: Arc::new(self.plan),
right: Arc::new(right),
on: join_on,
filter: filters,
join_type,
join_constraint: JoinConstraint::Using,
schema: DFSchemaRef::new(join_schema),
null_equals_null: false,
})))
}
}
/// Apply a cross join
pub fn cross_join(self, right: LogicalPlan) -> Result<Self> {
let join_schema =
build_join_schema(self.plan.schema(), right.schema(), &JoinType::Inner)?;
Ok(Self::from(LogicalPlan::CrossJoin(CrossJoin {
left: Arc::new(self.plan),
right: Arc::new(right),
schema: DFSchemaRef::new(join_schema),
})))
}
/// Repartition
pub fn repartition(self, partitioning_scheme: Partitioning) -> Result<Self> {
Ok(Self::from(LogicalPlan::Repartition(Repartition {
input: Arc::new(self.plan),
partitioning_scheme,
})))
}
/// Apply a window functions to extend the schema
pub fn window(
self,
window_expr: impl IntoIterator<Item = impl Into<Expr>>,
) -> Result<Self> {
let window_expr = normalize_cols(window_expr, &self.plan)?;
validate_unique_names("Windows", &window_expr)?;
Ok(Self::from(LogicalPlan::Window(Window::try_new(
window_expr,
Arc::new(self.plan),
)?)))
}
/// Apply an aggregate: grouping on the `group_expr` expressions
/// and calculating `aggr_expr` aggregates for each distinct
/// value of the `group_expr`;
pub fn aggregate(
self,
group_expr: impl IntoIterator<Item = impl Into<Expr>>,
aggr_expr: impl IntoIterator<Item = impl Into<Expr>>,
) -> Result<Self> {
let group_expr = normalize_cols(group_expr, &self.plan)?;
let aggr_expr = normalize_cols(aggr_expr, &self.plan)?;
Ok(Self::from(LogicalPlan::Aggregate(Aggregate::try_new(
Arc::new(self.plan),
group_expr,
aggr_expr,
)?)))
}
/// Create an expression to represent the explanation of the plan
///
/// if `analyze` is true, runs the actual plan and produces
/// information about metrics during run.
///
/// if `verbose` is true, prints out additional details.
pub fn explain(self, verbose: bool, analyze: bool) -> Result<Self> {
let schema = LogicalPlan::explain_schema();
let schema = schema.to_dfschema_ref()?;
if analyze {
Ok(Self::from(LogicalPlan::Analyze(Analyze {
verbose,
input: Arc::new(self.plan),
schema,
})))
} else {
let stringified_plans =
vec![self.plan.to_stringified(PlanType::InitialLogicalPlan)];
Ok(Self::from(LogicalPlan::Explain(Explain {
verbose,
plan: Arc::new(self.plan),
stringified_plans,
schema,
logical_optimization_succeeded: false,
})))
}
}
/// Process intersect set operator
pub fn intersect(
left_plan: LogicalPlan,
right_plan: LogicalPlan,
is_all: bool,
) -> Result<LogicalPlan> {
LogicalPlanBuilder::intersect_or_except(
left_plan,
right_plan,
JoinType::LeftSemi,
is_all,
)
}
/// Process except set operator
pub fn except(
left_plan: LogicalPlan,
right_plan: LogicalPlan,
is_all: bool,
) -> Result<LogicalPlan> {
LogicalPlanBuilder::intersect_or_except(
left_plan,
right_plan,
JoinType::LeftAnti,
is_all,
)
}
/// Process intersect or except
fn intersect_or_except(
left_plan: LogicalPlan,
right_plan: LogicalPlan,
join_type: JoinType,
is_all: bool,
) -> Result<LogicalPlan> {
let left_len = left_plan.schema().fields().len();
let right_len = right_plan.schema().fields().len();
if left_len != right_len {
return plan_err!(
"INTERSECT/EXCEPT query must have the same number of columns. Left is {left_len} and right is {right_len}."
);
}
let join_keys = left_plan
.schema()
.fields()
.iter()
.zip(right_plan.schema().fields().iter())
.map(|(left_field, right_field)| {
(
(Column::from_name(left_field.name())),
(Column::from_name(right_field.name())),
)
})
.unzip();
if is_all {
LogicalPlanBuilder::from(left_plan)
.join_detailed(right_plan, join_type, join_keys, None, true)?
.build()
} else {
LogicalPlanBuilder::from(left_plan)
.distinct()?
.join_detailed(right_plan, join_type, join_keys, None, true)?
.build()
}
}
/// Build the plan
pub fn build(self) -> Result<LogicalPlan> {
Ok(self.plan)
}
/// Apply a join with the expression on constraint.
///
/// equi_exprs are "equijoin" predicates expressions on the existing and right inputs, respectively.
///
/// filter: any other filter expression to apply during the join. equi_exprs predicates are likely
/// to be evaluated more quickly than the filter expressions
pub fn join_with_expr_keys(
self,
right: LogicalPlan,
join_type: JoinType,
equi_exprs: (Vec<impl Into<Expr>>, Vec<impl Into<Expr>>),
filter: Option<Expr>,
) -> Result<Self> {
if equi_exprs.0.len() != equi_exprs.1.len() {
return plan_err!("left_keys and right_keys were not the same length");
}
let join_key_pairs = equi_exprs
.0
.into_iter()
.zip(equi_exprs.1.into_iter())