-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathplan.rs
3239 lines (3014 loc) · 121 KB
/
plan.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.
//! Logical plan types
use std::collections::{HashMap, HashSet};
use std::fmt::{self, Debug, Display, Formatter};
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use super::dml::CopyTo;
use super::DdlStatement;
use crate::dml::CopyOptions;
use crate::expr::{Alias, Exists, InSubquery, Placeholder, Sort as SortExpr};
use crate::expr_rewriter::{create_col_from_scalar_expr, normalize_cols};
use crate::logical_plan::display::{GraphvizVisitor, IndentVisitor};
use crate::logical_plan::extension::UserDefinedLogicalNode;
use crate::logical_plan::{DmlStatement, Statement};
use crate::utils::{
enumerate_grouping_sets, exprlist_to_fields, find_out_reference_exprs,
grouping_set_expr_count, grouping_set_to_exprlist, inspect_expr_pre,
split_conjunction,
};
use crate::{
build_join_schema, expr_vec_fmt, BinaryExpr, CreateMemoryTable, CreateView, Expr,
ExprSchemable, LogicalPlanBuilder, Operator, TableProviderFilterPushDown,
TableSource,
};
use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
use datafusion_common::tree_node::{
RewriteRecursion, Transformed, TreeNode, TreeNodeRewriter, TreeNodeVisitor,
VisitRecursion,
};
use datafusion_common::{
aggregate_functional_dependencies, internal_err, plan_err, Column, Constraints,
DFField, DFSchema, DFSchemaRef, DataFusionError, Dependency, FunctionalDependencies,
OwnedTableReference, ParamValues, Result, UnnestOptions,
};
// backwards compatibility
pub use datafusion_common::display::{PlanType, StringifiedPlan, ToStringifiedPlan};
pub use datafusion_common::{JoinConstraint, JoinType};
/// A LogicalPlan represents the different types of relational
/// operators (such as Projection, Filter, etc) and can be created by
/// the SQL query planner and the DataFrame API.
///
/// A LogicalPlan represents transforming an input relation (table) to
/// an output relation (table) with a (potentially) different
/// schema. A plan represents a dataflow tree where data flows
/// from leaves up to the root to produce the query result.
#[derive(Clone, PartialEq, Eq, Hash)]
pub enum LogicalPlan {
/// Evaluates an arbitrary list of expressions (essentially a
/// SELECT with an expression list) on its input.
Projection(Projection),
/// Filters rows from its input that do not match an
/// expression (essentially a WHERE clause with a predicate
/// expression).
///
/// Semantically, `<predicate>` is evaluated for each row of the
/// input; If the value of `<predicate>` is true, the input row is
/// passed to the output. If the value of `<predicate>` is false
/// (or null), the row is discarded.
Filter(Filter),
/// Windows input based on a set of window spec and window
/// function (e.g. SUM or RANK). This is used to implement SQL
/// window functions, and the `OVER` clause.
Window(Window),
/// Aggregates its input based on a set of grouping and aggregate
/// expressions (e.g. SUM). This is used to implement SQL aggregates
/// and `GROUP BY`.
Aggregate(Aggregate),
/// Sorts its input according to a list of sort expressions. This
/// is used to implement SQL `ORDER BY`
Sort(Sort),
/// Join two logical plans on one or more join columns.
/// This is used to implement SQL `JOIN`
Join(Join),
/// Apply Cross Join to two logical plans.
/// This is used to implement SQL `CROSS JOIN`
CrossJoin(CrossJoin),
/// Repartitions the input based on a partitioning scheme. This is
/// used to add parallelism and is sometimes referred to as an
/// "exchange" operator in other systems
Repartition(Repartition),
/// Union multiple inputs with the same schema into a single
/// output stream. This is used to implement SQL `UNION [ALL]` and
/// `INTERSECT [ALL]`.
Union(Union),
/// Produces rows from a [`TableSource`], used to implement SQL
/// `FROM` tables or views.
TableScan(TableScan),
/// Produces no rows: An empty relation with an empty schema that
/// produces 0 or 1 row. This is used to implement SQL `SELECT`
/// that has no values in the `FROM` clause.
EmptyRelation(EmptyRelation),
/// Produces the output of running another query. This is used to
/// implement SQL subqueries
Subquery(Subquery),
/// Aliased relation provides, or changes, the name of a relation.
SubqueryAlias(SubqueryAlias),
/// Skip some number of rows, and then fetch some number of rows.
Limit(Limit),
/// A DataFusion [`Statement`] such as `SET VARIABLE` or `START TRANSACTION`
Statement(Statement),
/// Values expression. See
/// [Postgres VALUES](https://www.postgresql.org/docs/current/queries-values.html)
/// documentation for more details. This is used to implement SQL such as
/// `VALUES (1, 2), (3, 4)`
Values(Values),
/// Produces a relation with string representations of
/// various parts of the plan. This is used to implement SQL `EXPLAIN`.
Explain(Explain),
/// Runs the input, and prints annotated physical plan as a string
/// with execution metric. This is used to implement SQL
/// `EXPLAIN ANALYZE`.
Analyze(Analyze),
/// Extension operator defined outside of DataFusion. This is used
/// to extend DataFusion with custom relational operations that
Extension(Extension),
/// Remove duplicate rows from the input. This is used to
/// implement SQL `SELECT DISTINCT ...`.
Distinct(Distinct),
/// Prepare a statement and find any bind parameters
/// (e.g. `?`). This is used to implement SQL-prepared statements.
Prepare(Prepare),
/// Data Manipulaton Language (DML): Insert / Update / Delete
Dml(DmlStatement),
/// Data Definition Language (DDL): CREATE / DROP TABLES / VIEWS / SCHEMAS
Ddl(DdlStatement),
/// `COPY TO` for writing plan results to files
Copy(CopyTo),
/// Describe the schema of the table. This is used to implement the
/// SQL `DESCRIBE` command from MySQL.
DescribeTable(DescribeTable),
/// Unnest a column that contains a nested list type such as an
/// ARRAY. This is used to implement SQL `UNNEST`
Unnest(Unnest),
}
impl LogicalPlan {
/// Get a reference to the logical plan's schema
pub fn schema(&self) -> &DFSchemaRef {
match self {
LogicalPlan::EmptyRelation(EmptyRelation { schema, .. }) => schema,
LogicalPlan::Values(Values { schema, .. }) => schema,
LogicalPlan::TableScan(TableScan {
projected_schema, ..
}) => projected_schema,
LogicalPlan::Projection(Projection { schema, .. }) => schema,
LogicalPlan::Filter(Filter { input, .. }) => input.schema(),
LogicalPlan::Distinct(Distinct::All(input)) => input.schema(),
LogicalPlan::Distinct(Distinct::On(DistinctOn { schema, .. })) => schema,
LogicalPlan::Window(Window { schema, .. }) => schema,
LogicalPlan::Aggregate(Aggregate { schema, .. }) => schema,
LogicalPlan::Sort(Sort { input, .. }) => input.schema(),
LogicalPlan::Join(Join { schema, .. }) => schema,
LogicalPlan::CrossJoin(CrossJoin { schema, .. }) => schema,
LogicalPlan::Repartition(Repartition { input, .. }) => input.schema(),
LogicalPlan::Limit(Limit { input, .. }) => input.schema(),
LogicalPlan::Statement(statement) => statement.schema(),
LogicalPlan::Subquery(Subquery { subquery, .. }) => subquery.schema(),
LogicalPlan::SubqueryAlias(SubqueryAlias { schema, .. }) => schema,
LogicalPlan::Prepare(Prepare { input, .. }) => input.schema(),
LogicalPlan::Explain(explain) => &explain.schema,
LogicalPlan::Analyze(analyze) => &analyze.schema,
LogicalPlan::Extension(extension) => extension.node.schema(),
LogicalPlan::Union(Union { schema, .. }) => schema,
LogicalPlan::DescribeTable(DescribeTable { output_schema, .. }) => {
output_schema
}
LogicalPlan::Dml(DmlStatement { table_schema, .. }) => table_schema,
LogicalPlan::Copy(CopyTo { input, .. }) => input.schema(),
LogicalPlan::Ddl(ddl) => ddl.schema(),
LogicalPlan::Unnest(Unnest { schema, .. }) => schema,
}
}
/// Used for normalizing columns, as the fallback schemas to the main schema
/// of the plan.
pub fn fallback_normalize_schemas(&self) -> Vec<&DFSchema> {
match self {
LogicalPlan::Window(_)
| LogicalPlan::Projection(_)
| LogicalPlan::Aggregate(_)
| LogicalPlan::Unnest(_)
| LogicalPlan::Join(_)
| LogicalPlan::CrossJoin(_) => self
.inputs()
.iter()
.map(|input| input.schema().as_ref())
.collect(),
_ => vec![],
}
}
/// Get all meaningful schemas of a plan and its children plan.
#[deprecated(since = "20.0.0")]
pub fn all_schemas(&self) -> Vec<&DFSchemaRef> {
match self {
// return self and children schemas
LogicalPlan::Window(_)
| LogicalPlan::Projection(_)
| LogicalPlan::Aggregate(_)
| LogicalPlan::Unnest(_)
| LogicalPlan::Join(_)
| LogicalPlan::CrossJoin(_) => {
let mut schemas = vec![self.schema()];
self.inputs().iter().for_each(|input| {
schemas.push(input.schema());
});
schemas
}
// just return self.schema()
LogicalPlan::Explain(_)
| LogicalPlan::Analyze(_)
| LogicalPlan::EmptyRelation(_)
| LogicalPlan::Ddl(_)
| LogicalPlan::Dml(_)
| LogicalPlan::Copy(_)
| LogicalPlan::Values(_)
| LogicalPlan::SubqueryAlias(_)
| LogicalPlan::Union(_)
| LogicalPlan::Extension(_)
| LogicalPlan::TableScan(_) => {
vec![self.schema()]
}
// return children schemas
LogicalPlan::Limit(_)
| LogicalPlan::Subquery(_)
| LogicalPlan::Repartition(_)
| LogicalPlan::Sort(_)
| LogicalPlan::Filter(_)
| LogicalPlan::Distinct(_)
| LogicalPlan::Prepare(_) => {
self.inputs().iter().map(|p| p.schema()).collect()
}
// return empty
LogicalPlan::Statement(_) | LogicalPlan::DescribeTable(_) => vec![],
}
}
/// Returns the (fixed) output schema for explain plans
pub fn explain_schema() -> SchemaRef {
SchemaRef::new(Schema::new(vec![
Field::new("plan_type", DataType::Utf8, false),
Field::new("plan", DataType::Utf8, false),
]))
}
/// Returns the (fixed) output schema for `DESCRIBE` plans
pub fn describe_schema() -> Schema {
Schema::new(vec![
Field::new("column_name", DataType::Utf8, false),
Field::new("data_type", DataType::Utf8, false),
Field::new("is_nullable", DataType::Utf8, false),
])
}
/// returns all expressions (non-recursively) in the current
/// logical plan node. This does not include expressions in any
/// children
pub fn expressions(self: &LogicalPlan) -> Vec<Expr> {
let mut exprs = vec![];
self.inspect_expressions(|e| {
exprs.push(e.clone());
Ok(()) as Result<()>
})
// closure always returns OK
.unwrap();
exprs
}
/// Returns all the out reference(correlated) expressions (recursively) in the current
/// logical plan nodes and all its descendant nodes.
pub fn all_out_ref_exprs(self: &LogicalPlan) -> Vec<Expr> {
let mut exprs = vec![];
self.inspect_expressions(|e| {
find_out_reference_exprs(e).into_iter().for_each(|e| {
if !exprs.contains(&e) {
exprs.push(e)
}
});
Ok(()) as Result<(), DataFusionError>
})
// closure always returns OK
.unwrap();
self.inputs()
.into_iter()
.flat_map(|child| child.all_out_ref_exprs())
.for_each(|e| {
if !exprs.contains(&e) {
exprs.push(e)
}
});
exprs
}
/// Calls `f` on all expressions (non-recursively) in the current
/// logical plan node. This does not include expressions in any
/// children.
pub fn inspect_expressions<F, E>(self: &LogicalPlan, mut f: F) -> Result<(), E>
where
F: FnMut(&Expr) -> Result<(), E>,
{
match self {
LogicalPlan::Projection(Projection { expr, .. }) => {
expr.iter().try_for_each(f)
}
LogicalPlan::Values(Values { values, .. }) => {
values.iter().flatten().try_for_each(f)
}
LogicalPlan::Filter(Filter { predicate, .. }) => f(predicate),
LogicalPlan::Repartition(Repartition {
partitioning_scheme,
..
}) => match partitioning_scheme {
Partitioning::Hash(expr, _) => expr.iter().try_for_each(f),
Partitioning::DistributeBy(expr) => expr.iter().try_for_each(f),
Partitioning::RoundRobinBatch(_) => Ok(()),
},
LogicalPlan::Window(Window { window_expr, .. }) => {
window_expr.iter().try_for_each(f)
}
LogicalPlan::Aggregate(Aggregate {
group_expr,
aggr_expr,
..
}) => group_expr.iter().chain(aggr_expr.iter()).try_for_each(f),
// There are two part of expression for join, equijoin(on) and non-equijoin(filter).
// 1. the first part is `on.len()` equijoin expressions, and the struct of each expr is `left-on = right-on`.
// 2. the second part is non-equijoin(filter).
LogicalPlan::Join(Join { on, filter, .. }) => {
on.iter()
// it not ideal to create an expr here to analyze them, but could cache it on the Join itself
.map(|(l, r)| Expr::eq(l.clone(), r.clone()))
.try_for_each(|e| f(&e))?;
if let Some(filter) = filter.as_ref() {
f(filter)
} else {
Ok(())
}
}
LogicalPlan::Sort(Sort { expr, .. }) => expr.iter().try_for_each(f),
LogicalPlan::Extension(extension) => {
// would be nice to avoid this copy -- maybe can
// update extension to just observer Exprs
extension.node.expressions().iter().try_for_each(f)
}
LogicalPlan::TableScan(TableScan { filters, .. }) => {
filters.iter().try_for_each(f)
}
LogicalPlan::Unnest(Unnest { column, .. }) => {
f(&Expr::Column(column.clone()))
}
LogicalPlan::Distinct(Distinct::On(DistinctOn {
on_expr,
select_expr,
sort_expr,
..
})) => on_expr
.iter()
.chain(select_expr.iter())
.chain(sort_expr.clone().unwrap_or(vec![]).iter())
.try_for_each(f),
// plans without expressions
LogicalPlan::EmptyRelation(_)
| LogicalPlan::Subquery(_)
| LogicalPlan::SubqueryAlias(_)
| LogicalPlan::Limit(_)
| LogicalPlan::Statement(_)
| LogicalPlan::CrossJoin(_)
| LogicalPlan::Analyze(_)
| LogicalPlan::Explain(_)
| LogicalPlan::Union(_)
| LogicalPlan::Distinct(Distinct::All(_))
| LogicalPlan::Dml(_)
| LogicalPlan::Ddl(_)
| LogicalPlan::Copy(_)
| LogicalPlan::DescribeTable(_)
| LogicalPlan::Prepare(_) => Ok(()),
}
}
/// returns all inputs of this `LogicalPlan` node. Does not
/// include inputs to inputs, or subqueries.
pub fn inputs(&self) -> Vec<&LogicalPlan> {
match self {
LogicalPlan::Projection(Projection { input, .. }) => vec![input],
LogicalPlan::Filter(Filter { input, .. }) => vec![input],
LogicalPlan::Repartition(Repartition { input, .. }) => vec![input],
LogicalPlan::Window(Window { input, .. }) => vec![input],
LogicalPlan::Aggregate(Aggregate { input, .. }) => vec![input],
LogicalPlan::Sort(Sort { input, .. }) => vec![input],
LogicalPlan::Join(Join { left, right, .. }) => vec![left, right],
LogicalPlan::CrossJoin(CrossJoin { left, right, .. }) => vec![left, right],
LogicalPlan::Limit(Limit { input, .. }) => vec![input],
LogicalPlan::Subquery(Subquery { subquery, .. }) => vec![subquery],
LogicalPlan::SubqueryAlias(SubqueryAlias { input, .. }) => vec![input],
LogicalPlan::Extension(extension) => extension.node.inputs(),
LogicalPlan::Union(Union { inputs, .. }) => {
inputs.iter().map(|arc| arc.as_ref()).collect()
}
LogicalPlan::Distinct(
Distinct::All(input) | Distinct::On(DistinctOn { input, .. }),
) => vec![input],
LogicalPlan::Explain(explain) => vec![&explain.plan],
LogicalPlan::Analyze(analyze) => vec![&analyze.input],
LogicalPlan::Dml(write) => vec![&write.input],
LogicalPlan::Copy(copy) => vec![©.input],
LogicalPlan::Ddl(ddl) => ddl.inputs(),
LogicalPlan::Unnest(Unnest { input, .. }) => vec![input],
LogicalPlan::Prepare(Prepare { input, .. }) => vec![input],
// plans without inputs
LogicalPlan::TableScan { .. }
| LogicalPlan::Statement { .. }
| LogicalPlan::EmptyRelation { .. }
| LogicalPlan::Values { .. }
| LogicalPlan::DescribeTable(_) => vec![],
}
}
/// returns all `Using` join columns in a logical plan
pub fn using_columns(&self) -> Result<Vec<HashSet<Column>>, DataFusionError> {
let mut using_columns: Vec<HashSet<Column>> = vec![];
self.apply(&mut |plan| {
if let LogicalPlan::Join(Join {
join_constraint: JoinConstraint::Using,
on,
..
}) = plan
{
// The join keys in using-join must be columns.
let columns =
on.iter().try_fold(HashSet::new(), |mut accumu, (l, r)| {
accumu.insert(l.try_into_col()?);
accumu.insert(r.try_into_col()?);
Result::<_, DataFusionError>::Ok(accumu)
})?;
using_columns.push(columns);
}
Ok(VisitRecursion::Continue)
})?;
Ok(using_columns)
}
/// returns the first output expression of this `LogicalPlan` node.
pub fn head_output_expr(&self) -> Result<Option<Expr>> {
match self {
LogicalPlan::Projection(projection) => {
Ok(Some(projection.expr.as_slice()[0].clone()))
}
LogicalPlan::Aggregate(agg) => {
if agg.group_expr.is_empty() {
Ok(Some(agg.aggr_expr.as_slice()[0].clone()))
} else {
Ok(Some(agg.group_expr.as_slice()[0].clone()))
}
}
LogicalPlan::Distinct(Distinct::On(DistinctOn { select_expr, .. })) => {
Ok(Some(select_expr[0].clone()))
}
LogicalPlan::Filter(Filter { input, .. })
| LogicalPlan::Distinct(Distinct::All(input))
| LogicalPlan::Sort(Sort { input, .. })
| LogicalPlan::Limit(Limit { input, .. })
| LogicalPlan::Repartition(Repartition { input, .. })
| LogicalPlan::Window(Window { input, .. }) => input.head_output_expr(),
LogicalPlan::Join(Join {
left,
right,
join_type,
..
}) => match join_type {
JoinType::Inner | JoinType::Left | JoinType::Right | JoinType::Full => {
if left.schema().fields().is_empty() {
right.head_output_expr()
} else {
left.head_output_expr()
}
}
JoinType::LeftSemi | JoinType::LeftAnti => left.head_output_expr(),
JoinType::RightSemi | JoinType::RightAnti => right.head_output_expr(),
},
LogicalPlan::CrossJoin(cross) => {
if cross.left.schema().fields().is_empty() {
cross.right.head_output_expr()
} else {
cross.left.head_output_expr()
}
}
LogicalPlan::Union(union) => Ok(Some(Expr::Column(
union.schema.fields()[0].qualified_column(),
))),
LogicalPlan::TableScan(table) => Ok(Some(Expr::Column(
table.projected_schema.fields()[0].qualified_column(),
))),
LogicalPlan::SubqueryAlias(subquery_alias) => {
let expr_opt = subquery_alias.input.head_output_expr()?;
expr_opt
.map(|expr| {
Ok(Expr::Column(create_col_from_scalar_expr(
&expr,
subquery_alias.alias.to_string(),
)?))
})
.map_or(Ok(None), |v| v.map(Some))
}
LogicalPlan::Subquery(_) => Ok(None),
LogicalPlan::EmptyRelation(_)
| LogicalPlan::Prepare(_)
| LogicalPlan::Statement(_)
| LogicalPlan::Values(_)
| LogicalPlan::Explain(_)
| LogicalPlan::Analyze(_)
| LogicalPlan::Extension(_)
| LogicalPlan::Dml(_)
| LogicalPlan::Copy(_)
| LogicalPlan::Ddl(_)
| LogicalPlan::DescribeTable(_)
| LogicalPlan::Unnest(_) => Ok(None),
}
}
/// Returns a copy of this `LogicalPlan` with the new inputs
pub fn with_new_inputs(&self, inputs: &[LogicalPlan]) -> Result<LogicalPlan> {
// with_new_inputs use original expression,
// so we don't need to recompute Schema.
match &self {
LogicalPlan::Projection(projection) => {
// Schema of the projection may change
// when its input changes. Hence we should use
// `try_new` method instead of `try_new_with_schema`.
Projection::try_new(projection.expr.to_vec(), Arc::new(inputs[0].clone()))
.map(LogicalPlan::Projection)
}
LogicalPlan::Window(Window { window_expr, .. }) => Ok(LogicalPlan::Window(
Window::try_new(window_expr.to_vec(), Arc::new(inputs[0].clone()))?,
)),
LogicalPlan::Aggregate(Aggregate {
group_expr,
aggr_expr,
..
}) => Aggregate::try_new(
// Schema of the aggregate may change
// when its input changes. Hence we should use
// `try_new` method instead of `try_new_with_schema`.
Arc::new(inputs[0].clone()),
group_expr.to_vec(),
aggr_expr.to_vec(),
)
.map(LogicalPlan::Aggregate),
_ => self.with_new_exprs(self.expressions(), inputs),
}
}
/// Returns a new `LogicalPlan` based on `self` with inputs and
/// expressions replaced.
///
/// The exprs correspond to the same order of expressions returned
/// by [`Self::expressions`]. This function is used by optimizers
/// to rewrite plans using the following pattern:
///
/// ```text
/// let new_inputs = optimize_children(..., plan, props);
///
/// // get the plans expressions to optimize
/// let exprs = plan.expressions();
///
/// // potentially rewrite plan expressions
/// let rewritten_exprs = rewrite_exprs(exprs);
///
/// // create new plan using rewritten_exprs in same position
/// let new_plan = plan.new_with_exprs(rewritten_exprs, new_inputs);
/// ```
///
/// Note: sometimes [`Self::with_new_exprs`] will use schema of
/// original plan, it will not change the scheam. Such as
/// `Projection/Aggregate/Window`
pub fn with_new_exprs(
&self,
mut expr: Vec<Expr>,
inputs: &[LogicalPlan],
) -> Result<LogicalPlan> {
match self {
// Since expr may be different than the previous expr, schema of the projection
// may change. We need to use try_new method instead of try_new_with_schema method.
LogicalPlan::Projection(Projection { .. }) => {
Projection::try_new(expr, Arc::new(inputs[0].clone()))
.map(LogicalPlan::Projection)
}
LogicalPlan::Dml(DmlStatement {
table_name,
table_schema,
op,
..
}) => Ok(LogicalPlan::Dml(DmlStatement {
table_name: table_name.clone(),
table_schema: table_schema.clone(),
op: op.clone(),
input: Arc::new(inputs[0].clone()),
})),
LogicalPlan::Copy(CopyTo {
input: _,
output_url,
file_format,
copy_options,
single_file_output,
}) => Ok(LogicalPlan::Copy(CopyTo {
input: Arc::new(inputs[0].clone()),
output_url: output_url.clone(),
file_format: file_format.clone(),
single_file_output: *single_file_output,
copy_options: copy_options.clone(),
})),
LogicalPlan::Values(Values { schema, .. }) => {
Ok(LogicalPlan::Values(Values {
schema: schema.clone(),
values: expr
.chunks_exact(schema.fields().len())
.map(|s| s.to_vec())
.collect::<Vec<_>>(),
}))
}
LogicalPlan::Filter { .. } => {
assert_eq!(1, expr.len());
let predicate = expr.pop().unwrap();
// filter predicates should not contain aliased expressions so we remove any aliases
// before this logic was added we would have aliases within filters such as for
// benchmark q6:
//
// lineitem.l_shipdate >= Date32(\"8766\")
// AND lineitem.l_shipdate < Date32(\"9131\")
// AND CAST(lineitem.l_discount AS Decimal128(30, 15)) AS lineitem.l_discount >=
// Decimal128(Some(49999999999999),30,15)
// AND CAST(lineitem.l_discount AS Decimal128(30, 15)) AS lineitem.l_discount <=
// Decimal128(Some(69999999999999),30,15)
// AND lineitem.l_quantity < Decimal128(Some(2400),15,2)
struct RemoveAliases {}
impl TreeNodeRewriter for RemoveAliases {
type N = Expr;
fn pre_visit(&mut self, expr: &Expr) -> Result<RewriteRecursion> {
match expr {
Expr::Exists { .. }
| Expr::ScalarSubquery(_)
| Expr::InSubquery(_) => {
// subqueries could contain aliases so we don't recurse into those
Ok(RewriteRecursion::Stop)
}
Expr::Alias(_) => Ok(RewriteRecursion::Mutate),
_ => Ok(RewriteRecursion::Continue),
}
}
fn mutate(&mut self, expr: Expr) -> Result<Expr> {
Ok(expr.unalias())
}
}
let mut remove_aliases = RemoveAliases {};
let predicate = predicate.rewrite(&mut remove_aliases)?;
Filter::try_new(predicate, Arc::new(inputs[0].clone()))
.map(LogicalPlan::Filter)
}
LogicalPlan::Repartition(Repartition {
partitioning_scheme,
..
}) => match partitioning_scheme {
Partitioning::RoundRobinBatch(n) => {
Ok(LogicalPlan::Repartition(Repartition {
partitioning_scheme: Partitioning::RoundRobinBatch(*n),
input: Arc::new(inputs[0].clone()),
}))
}
Partitioning::Hash(_, n) => Ok(LogicalPlan::Repartition(Repartition {
partitioning_scheme: Partitioning::Hash(expr, *n),
input: Arc::new(inputs[0].clone()),
})),
Partitioning::DistributeBy(_) => {
Ok(LogicalPlan::Repartition(Repartition {
partitioning_scheme: Partitioning::DistributeBy(expr),
input: Arc::new(inputs[0].clone()),
}))
}
},
LogicalPlan::Window(Window {
window_expr,
schema,
..
}) => {
assert_eq!(window_expr.len(), expr.len());
Ok(LogicalPlan::Window(Window {
input: Arc::new(inputs[0].clone()),
window_expr: expr,
schema: schema.clone(),
}))
}
LogicalPlan::Aggregate(Aggregate { group_expr, .. }) => {
// group exprs are the first expressions
let agg_expr = expr.split_off(group_expr.len());
Aggregate::try_new(Arc::new(inputs[0].clone()), expr, agg_expr)
.map(LogicalPlan::Aggregate)
}
LogicalPlan::Sort(Sort { fetch, .. }) => Ok(LogicalPlan::Sort(Sort {
expr,
input: Arc::new(inputs[0].clone()),
fetch: *fetch,
})),
LogicalPlan::Join(Join {
join_type,
join_constraint,
on,
null_equals_null,
..
}) => {
let schema =
build_join_schema(inputs[0].schema(), inputs[1].schema(), join_type)?;
let equi_expr_count = on.len();
assert!(expr.len() >= equi_expr_count);
// Assume that the last expr, if any,
// is the filter_expr (non equality predicate from ON clause)
let filter_expr = if expr.len() > equi_expr_count {
expr.pop()
} else {
None
};
// The first part of expr is equi-exprs,
// and the struct of each equi-expr is like `left-expr = right-expr`.
assert_eq!(expr.len(), equi_expr_count);
let new_on:Vec<(Expr,Expr)> = expr.into_iter().map(|equi_expr| {
// SimplifyExpression rule may add alias to the equi_expr.
let unalias_expr = equi_expr.clone().unalias();
if let Expr::BinaryExpr(BinaryExpr { left, op: Operator::Eq, right }) = unalias_expr {
Ok((*left, *right))
} else {
internal_err!(
"The front part expressions should be an binary equality expression, actual:{equi_expr}"
)
}
}).collect::<Result<Vec<(Expr, Expr)>>>()?;
Ok(LogicalPlan::Join(Join {
left: Arc::new(inputs[0].clone()),
right: Arc::new(inputs[1].clone()),
join_type: *join_type,
join_constraint: *join_constraint,
on: new_on,
filter: filter_expr,
schema: DFSchemaRef::new(schema),
null_equals_null: *null_equals_null,
}))
}
LogicalPlan::CrossJoin(_) => {
let left = inputs[0].clone();
let right = inputs[1].clone();
LogicalPlanBuilder::from(left).cross_join(right)?.build()
}
LogicalPlan::Subquery(Subquery {
outer_ref_columns, ..
}) => {
let subquery = LogicalPlanBuilder::from(inputs[0].clone()).build()?;
Ok(LogicalPlan::Subquery(Subquery {
subquery: Arc::new(subquery),
outer_ref_columns: outer_ref_columns.clone(),
}))
}
LogicalPlan::SubqueryAlias(SubqueryAlias { alias, .. }) => {
SubqueryAlias::try_new(inputs[0].clone(), alias.clone())
.map(LogicalPlan::SubqueryAlias)
}
LogicalPlan::Limit(Limit { skip, fetch, .. }) => {
Ok(LogicalPlan::Limit(Limit {
skip: *skip,
fetch: *fetch,
input: Arc::new(inputs[0].clone()),
}))
}
LogicalPlan::Ddl(DdlStatement::CreateMemoryTable(CreateMemoryTable {
name,
if_not_exists,
or_replace,
column_defaults,
..
})) => Ok(LogicalPlan::Ddl(DdlStatement::CreateMemoryTable(
CreateMemoryTable {
input: Arc::new(inputs[0].clone()),
constraints: Constraints::empty(),
name: name.clone(),
if_not_exists: *if_not_exists,
or_replace: *or_replace,
column_defaults: column_defaults.clone(),
},
))),
LogicalPlan::Ddl(DdlStatement::CreateView(CreateView {
name,
or_replace,
definition,
..
})) => Ok(LogicalPlan::Ddl(DdlStatement::CreateView(CreateView {
input: Arc::new(inputs[0].clone()),
name: name.clone(),
or_replace: *or_replace,
definition: definition.clone(),
}))),
LogicalPlan::Extension(e) => Ok(LogicalPlan::Extension(Extension {
node: e.node.from_template(&expr, inputs),
})),
LogicalPlan::Union(Union { schema, .. }) => {
let input_schema = inputs[0].schema();
// If inputs are not pruned do not change schema.
let schema = if schema.fields().len() == input_schema.fields().len() {
schema
} else {
input_schema
};
Ok(LogicalPlan::Union(Union {
inputs: inputs.iter().cloned().map(Arc::new).collect(),
schema: schema.clone(),
}))
}
LogicalPlan::Distinct(distinct) => {
let distinct = match distinct {
Distinct::All(_) => Distinct::All(Arc::new(inputs[0].clone())),
Distinct::On(DistinctOn {
on_expr,
select_expr,
..
}) => {
let sort_expr = expr.split_off(on_expr.len() + select_expr.len());
let select_expr = expr.split_off(on_expr.len());
Distinct::On(DistinctOn::try_new(
expr,
select_expr,
if !sort_expr.is_empty() {
Some(sort_expr)
} else {
None
},
Arc::new(inputs[0].clone()),
)?)
}
};
Ok(LogicalPlan::Distinct(distinct))
}
LogicalPlan::Analyze(a) => {
assert!(expr.is_empty());
assert_eq!(inputs.len(), 1);
Ok(LogicalPlan::Analyze(Analyze {
verbose: a.verbose,
schema: a.schema.clone(),
input: Arc::new(inputs[0].clone()),
}))
}
LogicalPlan::Explain(e) => {
assert!(
expr.is_empty(),
"Invalid EXPLAIN command. Expression should empty"
);
assert_eq!(inputs.len(), 1, "Invalid EXPLAIN command. Inputs are empty");
Ok(LogicalPlan::Explain(Explain {
verbose: e.verbose,
plan: Arc::new(inputs[0].clone()),
stringified_plans: e.stringified_plans.clone(),
schema: e.schema.clone(),
logical_optimization_succeeded: e.logical_optimization_succeeded,
}))
}
LogicalPlan::Prepare(Prepare {
name, data_types, ..
}) => Ok(LogicalPlan::Prepare(Prepare {
name: name.clone(),
data_types: data_types.clone(),
input: Arc::new(inputs[0].clone()),
})),
LogicalPlan::TableScan(ts) => {
assert!(inputs.is_empty(), "{self:?} should have no inputs");
Ok(LogicalPlan::TableScan(TableScan {
filters: expr,
..ts.clone()
}))
}
LogicalPlan::EmptyRelation(_)
| LogicalPlan::Ddl(_)
| LogicalPlan::Statement(_) => {
// All of these plan types have no inputs / exprs so should not be called
assert!(expr.is_empty(), "{self:?} should have no exprs");
assert!(inputs.is_empty(), "{self:?} should have no inputs");
Ok(self.clone())
}
LogicalPlan::DescribeTable(_) => Ok(self.clone()),
LogicalPlan::Unnest(Unnest {
column,
schema,
options,
..
}) => {
// Update schema with unnested column type.
let input = Arc::new(inputs[0].clone());
let nested_field = input.schema().field_from_column(column)?;
let unnested_field = schema.field_from_column(column)?;
let fields = input
.schema()
.fields()
.iter()
.map(|f| {
if f == nested_field {
unnested_field.clone()
} else {
f.clone()
}
})
.collect::<Vec<_>>();
let schema = Arc::new(
DFSchema::new_with_metadata(
fields,
input.schema().metadata().clone(),
)?
// We can use the existing functional dependencies as is:
.with_functional_dependencies(
input.schema().functional_dependencies().clone(),
)?,
);
Ok(LogicalPlan::Unnest(Unnest {
input,
column: column.clone(),
schema,
options: options.clone(),
}))
}
}
}
/// Replaces placeholder param values (like `$1`, `$2`) in [`LogicalPlan`]
/// with the specified `param_values`.
///
/// [`LogicalPlan::Prepare`] are
/// converted to their inner logical plan for execution.
///
/// # Example
/// ```
/// # use arrow::datatypes::{Field, Schema, DataType};
/// use datafusion_common::ScalarValue;
/// # use datafusion_expr::{lit, col, LogicalPlanBuilder, logical_plan::table_scan, placeholder};
/// # let schema = Schema::new(vec![
/// # Field::new("id", DataType::Int32, false),
/// # ]);
/// // Build SELECT * FROM t1 WHRERE id = $1
/// let plan = table_scan(Some("t1"), &schema, None).unwrap()
/// .filter(col("id").eq(placeholder("$1"))).unwrap()
/// .build().unwrap();
///
/// assert_eq!(
/// "Filter: t1.id = $1\
/// \n TableScan: t1",
/// plan.display_indent().to_string()
/// );
///
/// // Fill in the parameter $1 with a literal 3
/// let plan = plan.with_param_values(vec![
/// ScalarValue::from(3i32) // value at index 0 --> $1
/// ]).unwrap();
///
/// assert_eq!(
/// "Filter: t1.id = Int32(3)\
/// \n TableScan: t1",
/// plan.display_indent().to_string()
/// );
///
/// // Note you can also used named parameters
/// // Build SELECT * FROM t1 WHRERE id = $my_param
/// let plan = table_scan(Some("t1"), &schema, None).unwrap()
/// .filter(col("id").eq(placeholder("$my_param"))).unwrap()