Repository navigation
Expand file tree
/
Copy pathphysical_planner.rs
More file actions
6500 lines (5946 loc) · 244 KB
/
Copy pathphysical_planner.rs
File metadata and controls
6500 lines (5946 loc) · 244 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
//! Planner for [`LogicalPlan`] to [`ExecutionPlan`]
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use crate::datasource::file_format::file_type_to_format;
use crate::datasource::listing::ListingTableUrl;
use crate::datasource::physical_plan::{FileOutputMode, FileSinkConfig};
use crate::datasource::{DefaultTableSource, source_as_provider};
use crate::error::{DataFusionError, Result};
use crate::execution::context::ExecutionProps;
use crate::execution::session_state::SessionState;
use crate::logical_expr::utils::generate_sort_key;
use crate::logical_expr::{
Aggregate, EmptyRelation, Join, Projection, Sort, TableScan, Unnest, Values, Window,
};
use crate::logical_expr::{Expr, LogicalPlan, PlanType, Repartition};
use crate::physical_expr::{
create_physical_expr, create_physical_exprs, create_physical_partitioning,
};
use crate::physical_plan::aggregates::{AggregateExec, AggregateMode, PhysicalGroupBy};
use crate::physical_plan::analyze::AnalyzeExec;
use crate::physical_plan::explain::ExplainExec;
use crate::physical_plan::filter::FilterExecBuilder;
use crate::physical_plan::joins::utils as join_utils;
use crate::physical_plan::joins::{
AsOfJoinExec, AsOfMatchExpr, CrossJoinExec, HashJoinExecBuilder, NestedLoopJoinExec,
PartitionMode, SortMergeJoinExec,
};
use crate::physical_plan::limit::{GlobalLimitExec, LocalLimitExec};
use crate::physical_plan::materialized_cte::{
MaterializedCteBuffer, MaterializedCteExec, MaterializedCteScanExec,
};
use crate::physical_plan::projection::{ProjectionExec, ProjectionExpr};
use crate::physical_plan::repartition::RepartitionExec;
use crate::physical_plan::sorts::sort::SortExec;
use crate::physical_plan::union::UnionExec;
use crate::physical_plan::unnest::UnnestExec;
use crate::physical_plan::windows::{BoundedWindowAggExec, WindowAggExec};
use crate::physical_plan::{
ExecutionPlan, ExecutionPlanProperties, InputOrderMode, PhysicalExpr, WindowExpr,
displayable, windows,
};
use crate::schema_equivalence::schema_satisfied_by;
use arrow::array::{ArrayRef, RecordBatch, UInt64Array};
use arrow::compute::SortOptions;
use arrow::datatypes::{DataType, Schema};
use arrow_schema::Field;
use datafusion_catalog::ScanArgs;
use datafusion_catalog::information_schema::InformationSchemaProvider;
use datafusion_common::Column;
use datafusion_common::HashMap as DFHashMap;
use datafusion_common::config::ConfigOptions;
use datafusion_common::display::ToStringifiedPlan;
use datafusion_common::format::ExplainAnalyzeCategories;
use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeRecursion};
use datafusion_common::{
DFSchema, DFSchemaRef, ScalarValue, Statistics, exec_err, internal_datafusion_err,
internal_err, not_impl_err, plan_err,
};
use datafusion_common::{
NullEquality, TableReference, assert_eq_or_internal_err, assert_or_internal_err,
};
use datafusion_datasource::file_groups::FileGroup;
use datafusion_datasource::memory::MemorySourceConfig;
use datafusion_expr::dml::{CopyTo, InsertOp};
use datafusion_expr::expr::{
Alias, GroupingSet, NullTreatment, WindowFunction, WindowFunctionParams,
physical_name,
};
use datafusion_expr::expr_rewriter::unnormalize_cols;
use datafusion_expr::logical_plan::Subquery;
use datafusion_expr::logical_plan::builder::wrap_projection_for_join_if_necessary;
use datafusion_expr::physical_planning_context::{
PhysicalPlanningContext, ScalarSubqueryResults, SubqueryIndex,
};
use datafusion_expr::utils::{expr_to_columns, split_conjunction};
use datafusion_expr::{
Analyze, BinaryExpr, DmlStatement, Explain, ExplainFormat, Extension, FetchType,
Filter, JoinType, MaterializedCte, MaterializedCteId, MaterializedCtePlan,
MaterializedCteScan, Operator, RecursiveQuery, Show, ShowKind, SkipType,
StringifiedPlan, WindowFrame, WindowFrameBound, WriteOp,
};
use datafusion_physical_expr::aggregate::{
AggregateFunctionExpr, LoweredAggregate, LoweredAggregateBuilder,
};
use datafusion_physical_expr::expressions::Literal;
use datafusion_physical_expr::{
LexOrdering, PhysicalSortExpr, create_physical_sort_exprs,
};
use datafusion_physical_optimizer::ensure_requirements::EnsureRequirements;
use datafusion_physical_optimizer::sanity_checker::{
check_plan_tree_sanity, input_requirements_hold,
};
use datafusion_physical_plan::empty::EmptyExec;
use datafusion_physical_plan::execution_plan::InvariantLevel;
use datafusion_physical_plan::joins::PiecewiseMergeJoinExec;
use datafusion_physical_plan::operator_statistics::StatisticsRegistry;
use datafusion_physical_plan::placeholder_row::PlaceholderRowExec;
use datafusion_physical_plan::recursive_query::RecursiveQueryExec;
use datafusion_physical_plan::scalar_subquery::{ScalarSubqueryExec, ScalarSubqueryLink};
use datafusion_physical_plan::statistics::{StatisticsArgs, StatisticsContext};
use datafusion_physical_plan::unnest::ListUnnest;
use datafusion_session::{PhysicalOptimizerContext, PhysicalOptimizerRule, Session};
use async_trait::async_trait;
use datafusion_physical_plan::async_func::{AsyncFuncExec, AsyncMapper};
use futures::future::BoxFuture;
use futures::{StreamExt, TryStreamExt};
use indexmap::IndexSet;
use itertools::{Itertools, multiunzip};
use log::debug;
use tokio::sync::Mutex;
// Re-export from this module for backwards compatibility.
pub use datafusion_session::{ExtensionPlanner, PhysicalPlanner};
struct SessionOptimizerContext<'a> {
session: &'a dyn Session,
statistics_context: StatisticsContext,
}
impl<'a> SessionOptimizerContext<'a> {
fn new(session: &'a dyn Session) -> Self {
let statistics_context = match session.statistics_registry() {
Some(registry) => StatisticsContext::new_with_registry(registry.clone()),
None => StatisticsContext::new(),
};
Self {
session,
statistics_context,
}
}
}
impl PhysicalOptimizerContext for SessionOptimizerContext<'_> {
fn config_options(&self) -> &ConfigOptions {
self.session.config_options()
}
fn statistics_registry(&self) -> Option<&StatisticsRegistry> {
self.session.statistics_registry()
}
fn statistics_context(&self) -> Option<&StatisticsContext> {
Some(&self.statistics_context)
}
}
/// Default single node physical query planner that converts a
/// `LogicalPlan` to an `ExecutionPlan` suitable for execution.
///
/// This planner first flattens the `LogicalPlan` tree with a depth-first
/// traversal. It then builds the physical plan from the leaves to the root.
/// Up to [`planning_concurrency`] tasks execute concurrently.
///
/// [`planning_concurrency`]: crate::config::ExecutionOptions::planning_concurrency
#[derive(Default)]
pub struct DefaultPhysicalPlanner {
extension_planners: Vec<Arc<dyn ExtensionPlanner + Send + Sync>>,
}
#[async_trait]
impl PhysicalPlanner for DefaultPhysicalPlanner {
/// Create a physical plan from a logical plan
// Hand-written `#[async_trait]` expansion to reduce compile time. See
// <https://github.com/apache/datafusion/issues/13814#issuecomment-5292709677>
fn create_physical_plan<'life0, 'life1, 'life2, 'async_trait>(
&'life0 self,
logical_plan: &'life1 LogicalPlan,
session_state: &'life2 dyn Session,
) -> BoxFuture<'async_trait, Result<Arc<dyn ExecutionPlan>>>
where
'life0: 'async_trait,
'life1: 'async_trait,
'life2: 'async_trait,
Self: 'async_trait,
{
self.create_physical_plan_boxed(logical_plan, session_state)
}
/// Create a physical expression from a logical expression
/// suitable for evaluation
///
/// `e`: the expression to convert
///
/// `input_dfschema`: the logical plan schema for evaluating `e`
fn create_physical_expr(
&self,
expr: &Expr,
input_dfschema: &DFSchema,
session_state: &dyn Session,
planning_ctx: &PhysicalPlanningContext,
) -> Result<Arc<dyn PhysicalExpr>> {
create_physical_expr(
expr,
input_dfschema,
session_state.execution_props(),
planning_ctx,
)
}
}
impl DefaultPhysicalPlanner {
fn create_physical_plan_boxed<'a>(
&'a self,
logical_plan: &'a LogicalPlan,
session_state: &'a dyn Session,
) -> BoxFuture<'a, Result<Arc<dyn ExecutionPlan>>> {
Box::pin(self.create_physical_plan_inner(logical_plan, session_state))
}
async fn create_physical_plan_inner(
&self,
logical_plan: &LogicalPlan,
session_state: &dyn Session,
) -> Result<Arc<dyn ExecutionPlan>> {
if let Some(plan) = self
.handle_explain_or_analyze(logical_plan, session_state)
.await?
{
return Ok(plan);
}
let renumbered = renumber_materialized_ctes(logical_plan)?;
let logical_plan = renumbered.as_ref().unwrap_or(logical_plan);
let plan = self
.create_initial_plan(logical_plan, session_state)
.await?;
self.optimize_physical_plan(plan, session_state, |_, _| {})
}
}
/// Give each occurrence of a [`MaterializedCte`] in `plan` a new id, and
/// update the scans in its continuation, including the scans in subqueries.
///
/// The id is copied when a logical plan is cloned, so one CTE can occur more
/// than once, for example when a view that declares it is referenced two
/// times, or when a DataFrame is joined to itself. Each occurrence is a
/// separate CTE, as in PostgreSQL.
///
/// The ids must also be new for each planning run, not only unique within
/// `plan`. A table provider can plan a saved logical plan in its `scan`, as a
/// [`ViewTable`] that is not inlined does. Each such scan is a separate
/// planning run of the same saved plan, and its CTEs end up in the same
/// physical plan as the CTEs of the outer run.
///
/// Returns `None` when `plan` has no materialized CTE.
///
/// [`ViewTable`]: crate::datasource::ViewTable
fn renumber_materialized_ctes(plan: &LogicalPlan) -> Result<Option<LogicalPlan>> {
let mut has_cte = false;
plan.apply_with_subqueries(|node| {
if matches!(
node,
LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(_))
) {
has_cte = true;
return Ok(TreeNodeRecursion::Stop);
}
Ok(TreeNodeRecursion::Continue)
})?;
if !has_cte {
return Ok(None);
}
plan.clone()
.transform_down_with_subqueries(|node| {
let LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) = node else {
return Ok(Transformed::no(node));
};
let old_id = cte.id;
let new_id = MaterializedCteId::next();
let continuation = Arc::unwrap_or_clone(cte.continuation)
.transform_down_with_subqueries(|node| match node {
// A nested occurrence of the same CTE owns the scans below
// it, and is renumbered on its own.
LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(
ref nested,
)) if nested.id == old_id => {
Ok(Transformed::new(node, false, TreeNodeRecursion::Jump))
}
LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(scan))
if scan.id == old_id =>
{
Ok(Transformed::yes(LogicalPlan::MaterializedCte(
MaterializedCtePlan::Scan(MaterializedCteScan {
id: new_id,
..scan
}),
)))
}
_ => Ok(Transformed::no(node)),
})?
.data;
Ok(Transformed::yes(LogicalPlan::MaterializedCte(
MaterializedCtePlan::Cte(MaterializedCte {
id: new_id,
continuation: Arc::new(continuation),
..cte
}),
)))
})
.map(|t| Some(t.data))
}
/// Points every [`MaterializedCteScanExec`] at the buffer of the
/// [`MaterializedCteExec`] with the same id, and gives it the statistics of
/// the CTE body.
///
/// [`renumber_materialized_ctes`] makes the ids unique before the physical
/// plan is created.
///
/// A scan that is already bound was planned and bound by a separate planning
/// run, such as the `scan` of a [`ViewTable`], and is not bound again. Binding
/// it again would count its partitions twice in the buffer.
///
/// Scans are planned before the node that owns their CTE, and a scan inside a
/// scalar subquery is planned in a separate subtree, so the binding is done
/// on the whole initial plan.
///
/// [`ViewTable`]: crate::datasource::ViewTable
struct MaterializedCteBinder {
ctes: HashMap<u64, Arc<dyn ExecutionPlan>>,
/// The statistics of the CTE bodies. `None` while they are computed.
statistics: HashMap<u64, Option<Arc<Statistics>>>,
context: StatisticsContext,
}
impl MaterializedCteBinder {
fn new(plan: &Arc<dyn ExecutionPlan>, session_state: &dyn Session) -> Result<Self> {
let mut ctes = HashMap::new();
plan.apply(|node| {
if let Some(cte) = node.downcast_ref::<MaterializedCteExec>()
&& ctes.insert(cte.buffer().id(), Arc::clone(node)).is_some()
{
return internal_err!(
"Two MaterializedCteExec nodes have the id {}",
cte.buffer().id()
);
}
Ok(TreeNodeRecursion::Continue)
})?;
let context = match session_state.statistics_registry() {
Some(registry) => StatisticsContext::new_with_registry(registry.clone()),
None => StatisticsContext::new(),
};
Ok(Self {
ctes,
statistics: HashMap::new(),
context,
})
}
fn cte(&self, id: u64) -> Option<&MaterializedCteExec> {
self.ctes
.get(&id)
.and_then(|cte| cte.downcast_ref::<MaterializedCteExec>())
}
/// Give every scan in `plan` whose CTE is in `self.ctes` the statistics
/// of the CTE body. If `bind` is true, also bind the scans that are not
/// bound.
fn bind(
&mut self,
plan: Arc<dyn ExecutionPlan>,
bind: bool,
) -> Result<Arc<dyn ExecutionPlan>> {
plan.transform_up(|node| {
let Some(scan) = node.downcast_ref::<MaterializedCteScanExec>() else {
return Ok(Transformed::no(node));
};
let Some(cte) = self.cte(scan.id()) else {
if scan.is_bound() {
return Ok(Transformed::no(node));
}
return internal_err!("MaterializedCteScanExec {} has no CTE", scan.id());
};
let bound =
(bind && !scan.is_bound()).then(|| scan.bind(Arc::clone(cte.buffer())));
let scan = bound.as_ref().unwrap_or(scan);
let scan = match self.body_statistics(scan.id())? {
Some(statistics) => scan.with_body_statistics(statistics),
None => match bound {
Some(bound) => bound,
None => return Ok(Transformed::no(node)),
},
};
Ok(Transformed::yes(Arc::new(scan) as Arc<dyn ExecutionPlan>))
})
.map(|t| t.data)
}
/// The statistics of the body of the CTE `id`, or `None` while they are
/// computed.
///
/// The body can read other CTEs. Its scans get their statistics first,
/// in a copy of the body that is used only here.
fn body_statistics(&mut self, id: u64) -> Result<Option<Arc<Statistics>>> {
if let Some(statistics) = self.statistics.get(&id) {
return Ok(statistics.clone());
}
let Some(cte) = self.cte(id) else {
return Ok(None);
};
let body = Arc::clone(cte.body());
self.statistics.insert(id, None);
let body = self.bind(body, false)?;
let statistics = self
.context
.compute(body.as_ref(), &StatisticsArgs::new())?;
self.statistics.insert(id, Some(Arc::clone(&statistics)));
Ok(Some(statistics))
}
}
/// See [`MaterializedCteBinder`].
fn bind_materialized_cte_scans(
plan: Arc<dyn ExecutionPlan>,
session_state: &dyn Session,
) -> Result<Arc<dyn ExecutionPlan>> {
let mut binder = MaterializedCteBinder::new(&plan, session_state)?;
if binder.ctes.is_empty() {
return Ok(plan);
}
binder.bind(plan, true)
}
#[derive(Debug)]
struct ExecutionPlanChild {
/// Index needed to order children of parent to ensure consistency with original
/// `LogicalPlan`
index: usize,
plan: Arc<dyn ExecutionPlan>,
}
#[derive(Debug)]
enum NodeState {
ZeroOrOneChild,
/// Nodes with multiple children will have multiple tasks accessing it,
/// and each task will append their contribution until the last task takes
/// all the children to build the parent node.
TwoOrMoreChildren(Mutex<Vec<ExecutionPlanChild>>),
}
/// To avoid needing to pass single child wrapped in a Vec for nodes
/// with only one child.
enum ChildrenContainer {
None,
One(Arc<dyn ExecutionPlan>),
Multiple(Vec<Arc<dyn ExecutionPlan>>),
}
impl ChildrenContainer {
fn one(self) -> Result<Arc<dyn ExecutionPlan>> {
match self {
Self::One(p) => Ok(p),
_ => internal_err!("More than one child in ChildrenContainer"),
}
}
fn two(self) -> Result<[Arc<dyn ExecutionPlan>; 2]> {
match self {
Self::Multiple(v) if v.len() == 2 => Ok(v.try_into().unwrap()),
_ => internal_err!("ChildrenContainer doesn't contain exactly 2 children"),
}
}
fn vec(self) -> Vec<Arc<dyn ExecutionPlan>> {
match self {
Self::None => vec![],
Self::One(p) => vec![p],
Self::Multiple(v) => v,
}
}
}
#[derive(Debug)]
struct LogicalNode<'a> {
node: &'a LogicalPlan,
// None if root
parent_index: Option<usize>,
state: NodeState,
}
impl DefaultPhysicalPlanner {
/// Create a physical planner that uses `extension_planners` to
/// plan user-defined logical nodes [`LogicalPlan::Extension`]
/// or user-defined table sources in [`LogicalPlan::TableScan`].
/// The planner uses the first [`ExtensionPlanner`] to return a non-`None`
/// plan.
pub fn with_extension_planners(
extension_planners: Vec<Arc<dyn ExtensionPlanner + Send + Sync>>,
) -> Self {
Self { extension_planners }
}
fn ensure_schema_matches(
&self,
logical_schema: &DFSchemaRef,
physical_plan: &Arc<dyn ExecutionPlan>,
context_factory: impl FnOnce() -> String,
) -> Result<()> {
if !logical_schema.matches_arrow_schema(&physical_plan.schema()) {
return plan_err!(
"{} created an ExecutionPlan with mismatched schema. \
LogicalPlan schema: {:?}, ExecutionPlan schema: {:?}",
context_factory(),
logical_schema,
physical_plan.schema()
);
}
Ok(())
}
/// Collect uncorrelated scalar subqueries. We don't descend into nested
/// subqueries here: each call to `create_initial_plan` handles subqueries
/// at its level and then recurses in order to handle nested subqueries.
#[allow(clippy::allow_attributes, clippy::mutable_key_type)] // Subquery contains Arc with interior mutability but is intentionally used as hash key
fn collect_scalar_subqueries(plan: &LogicalPlan) -> Vec<Subquery> {
let mut subqueries = IndexSet::new();
plan.apply(|node| {
for expr in node.expressions() {
expr.apply(|e| {
if let Expr::ScalarSubquery(sq) = e
&& sq.outer_ref_columns.is_empty()
{
subqueries.insert(sq.clone());
}
Ok(TreeNodeRecursion::Continue)
})
.expect("infallible");
}
Ok(TreeNodeRecursion::Continue)
})
.expect("infallible");
subqueries.into_iter().collect()
}
/// Create a physical plan from a logical plan.
///
/// Uncorrelated scalar subqueries in the plan's own expressions are
/// collected, planned as separate physical plans, and each assigned an
/// index in a shared [`ScalarSubqueryResults`] container that will hold its
/// result at execution time. The index map and shared results container are
/// stored in a [`PhysicalPlanningContext`] and passed explicitly to
/// [`create_physical_expr`] so it can convert `Expr::ScalarSubquery` into
/// [`ScalarSubqueryExpr`] nodes that read from that container.
///
/// The resulting physical plan is wrapped in a [`ScalarSubqueryExec`] node
/// that executes those subquery plans before any data flows through the
/// main plan. If a subquery itself contains nested uncorrelated subqueries,
/// the recursive call produces its own [`ScalarSubqueryExec`] inside the
/// subquery plan — each level manages only its own subqueries.
///
/// Returns a [`BoxFuture`] rather than using `async fn` because of
/// this recursion.
///
/// [`ScalarSubqueryExpr`]: datafusion_physical_expr::scalar_subquery::ScalarSubqueryExpr
/// [`BoxFuture`]: futures::future::BoxFuture
fn create_initial_plan<'a>(
&'a self,
logical_plan: &'a LogicalPlan,
session_state: &'a dyn Session,
) -> BoxFuture<'a, Result<Arc<dyn ExecutionPlan>>> {
Box::pin(async move {
// When `enable_physical_uncorrelated_scalar_subquery` is disabled, the
// `ScalarSubqueryToJoin` optimizer rule rewrites all uncorrelated
// scalar subqueries to joins, so none should reach this point.
// Skip collection in that case to avoid creating a no-op
// `ScalarSubqueryExec` wrapper.
let all_subqueries = if session_state
.config_options()
.optimizer
.enable_physical_uncorrelated_scalar_subquery
{
Self::collect_scalar_subqueries(logical_plan)
} else {
Vec::new()
};
let (links, index_map) = self
.plan_scalar_subqueries(all_subqueries, session_state)
.await?;
if links.is_empty() {
return self
.create_initial_plan_inner(
logical_plan,
session_state,
&PhysicalPlanningContext::default(),
)
.await;
}
// Build a `PhysicalPlanningContext` that carries the index map and
// shared results container into calls that create physical expressions.
// The context is threaded explicitly through physical planning rather
// than being stashed in `ExecutionProps`, so the planner does not need
// a mutable `SessionState` and each recursively planned subtree receives
// the correct context.
let results = ScalarSubqueryResults::new(links.len());
let planning_ctx = PhysicalPlanningContext::new(index_map, results.clone());
let plan = self
.create_initial_plan_inner(logical_plan, session_state, &planning_ctx)
.await?;
Ok(Arc::new(ScalarSubqueryExec::new(plan, links, results)))
})
}
/// Inner physical planning that converts a logical plan tree into an
/// execution plan tree without collecting scalar subqueries.
async fn create_initial_plan_inner(
&self,
logical_plan: &LogicalPlan,
session_state: &dyn Session,
planning_ctx: &PhysicalPlanningContext,
) -> Result<Arc<dyn ExecutionPlan>> {
// DFS the tree to flatten it into a Vec.
// This will allow us to build the Physical Plan from the leaves up
// to avoid recursion, and also to make it easier to build a valid
// Physical Plan from the start and not rely on some intermediate
// representation (since parents need to know their children at
// construction time).
let mut flat_tree = vec![];
let mut dfs_visit_stack = vec![(None, logical_plan)];
// Use this to be able to find the leaves to start construction bottom
// up concurrently.
let mut flat_tree_leaf_indices = vec![];
while let Some((parent_index, node)) = dfs_visit_stack.pop() {
let current_index = flat_tree.len();
// Because of how we extend the visit stack here, we visit the children
// in reverse order of how they appear, so later we need to reverse
// the order of children when building the nodes.
dfs_visit_stack
.extend(node.inputs().iter().map(|&n| (Some(current_index), n)));
let state = match node.inputs().len() {
0 => {
flat_tree_leaf_indices.push(current_index);
NodeState::ZeroOrOneChild
}
1 => NodeState::ZeroOrOneChild,
_ => {
let ready_children = Vec::with_capacity(node.inputs().len());
let ready_children = Mutex::new(ready_children);
NodeState::TwoOrMoreChildren(ready_children)
}
};
let node = LogicalNode {
node,
parent_index,
state,
};
flat_tree.push(node);
}
let flat_tree = Arc::new(flat_tree);
let planning_concurrency = session_state
.config_options()
.execution
.planning_concurrency;
// Can never spawn more tasks than leaves in the tree, as these tasks must
// all converge down to the root node, which can only be processed by a
// single task.
let max_concurrency = planning_concurrency.min(flat_tree_leaf_indices.len());
// Spawning tasks which will traverse leaf up to the root.
let tasks = flat_tree_leaf_indices.into_iter().map(|index| {
self.task_helper(index, Arc::clone(&flat_tree), session_state, planning_ctx)
});
let mut outputs = futures::stream::iter(tasks)
.buffer_unordered(max_concurrency)
.try_collect::<Vec<_>>()
.await?
.into_iter()
.flatten()
.collect::<Vec<_>>();
// Ideally this never happens if we have a valid LogicalPlan tree
assert_eq_or_internal_err!(
outputs.len(),
1,
"Failed to convert LogicalPlan to ExecutionPlan: More than one root detected"
);
let plan = outputs.pop().unwrap();
Ok(plan)
}
/// These tasks start at a leaf and traverse up the tree towards the root, building
/// an ExecutionPlan as they go. When they reach a node with two or more children,
/// they append their current result (a child of the parent node) to the children
/// vector, and if this is sufficient to create the parent then continues traversing
/// the tree to create nodes. Otherwise, the task terminates.
async fn task_helper<'a>(
&'a self,
leaf_starter_index: usize,
flat_tree: Arc<Vec<LogicalNode<'a>>>,
session_state: &'a dyn Session,
planning_ctx: &'a PhysicalPlanningContext,
) -> Result<Option<Arc<dyn ExecutionPlan>>> {
// We always start with a leaf, so can ignore status and pass empty children
let mut node = flat_tree.get(leaf_starter_index).ok_or_else(|| {
internal_datafusion_err!(
"Invalid index whilst creating initial physical plan"
)
})?;
let mut plan = self
.map_logical_node_to_physical(
node.node,
session_state,
planning_ctx,
ChildrenContainer::None,
)
.await?;
let mut current_index = leaf_starter_index;
// parent_index is None only for root
while let Some(parent_index) = node.parent_index {
node = flat_tree.get(parent_index).ok_or_else(|| {
internal_datafusion_err!(
"Invalid index whilst creating initial physical plan"
)
})?;
match &node.state {
NodeState::ZeroOrOneChild => {
plan = self
.map_logical_node_to_physical(
node.node,
session_state,
planning_ctx,
ChildrenContainer::One(plan),
)
.await?;
}
// See if we have all children to build the node.
NodeState::TwoOrMoreChildren(children) => {
let mut children: Vec<ExecutionPlanChild> = {
let mut guard = children.lock().await;
// Add our contribution to this parent node.
// Vec is pre-allocated so no allocation should occur here.
guard.push(ExecutionPlanChild {
index: current_index,
plan,
});
if guard.len() < node.node.inputs().len() {
// This node is not ready yet, still pending more children.
// This task is finished forever.
return Ok(None);
}
// With this task's contribution we have enough children.
// This task is the only one building this node now, and thus
// no other task will need the Mutex for this node, so take
// all children.
std::mem::take(guard.as_mut())
};
// Indices refer to position in flat tree Vec, which means they are
// guaranteed to be unique, hence unstable sort used.
//
// We reverse sort because of how we visited the node in the initial
// DFS traversal (see above).
children.sort_unstable_by_key(|epc| std::cmp::Reverse(epc.index));
let children = children.into_iter().map(|epc| epc.plan).collect();
let children = ChildrenContainer::Multiple(children);
plan = self
.map_logical_node_to_physical(
node.node,
session_state,
planning_ctx,
children,
)
.await?;
}
}
current_index = parent_index;
}
// Only one task should ever reach this point for a valid LogicalPlan tree.
Ok(Some(plan))
}
/// Given a single LogicalPlan node, map it to its physical ExecutionPlan counterpart.
async fn map_logical_node_to_physical(
&self,
node: &LogicalPlan,
session: &dyn Session,
planning_ctx: &PhysicalPlanningContext,
children: ChildrenContainer,
) -> Result<Arc<dyn ExecutionPlan>> {
let execution_props = session.execution_props();
let exec_node: Arc<dyn ExecutionPlan> = match node {
// Leaves (no children)
LogicalPlan::TableScan(scan) => {
let TableScan {
source,
projection,
filters,
fetch,
skip: offset,
projected_schema,
statistics_requests,
..
} = scan;
if let Ok(source) = source_as_provider(source) {
// Remove all qualifiers from the scan as the provider
// doesn't know (nor should care) how the relation was
// referred to in the query
let filters = unnormalize_cols(filters.iter().cloned());
let filters_vec = filters.into_iter().collect::<Vec<_>>();
let stats_requests =
statistics_requests.iter().cloned().collect::<Vec<_>>();
let opts = ScanArgs::default()
.with_projection(projection.as_deref())
.with_filters(Some(&filters_vec))
.with_limit(*fetch)
.with_skip(*offset)
.with_statistics_requests(&stats_requests);
let res = source.scan_with_args(session, opts).await?;
Arc::clone(res.plan())
} else {
let mut maybe_plan = None;
for planner in &self.extension_planners {
if maybe_plan.is_some() {
break;
}
maybe_plan = planner
.plan_table_scan(self, scan, session, planning_ctx)
.await?;
}
let Some(plan) = maybe_plan else {
return plan_err!(
"No installed planner was able to plan TableScan for custom TableSource: {:?}",
scan.table_name
);
};
self.ensure_schema_matches(projected_schema, &plan, || {
format!("Extension planner for table scan {}", scan.table_name)
})?;
plan
}
}
LogicalPlan::Values(Values { values, schema }) => {
let exprs = values
.iter()
.map(|row| {
row.iter()
.map(|expr| {
create_physical_expr(
expr,
schema,
execution_props,
planning_ctx,
)
})
.collect::<Result<Vec<Arc<dyn PhysicalExpr>>>>()
})
.collect::<Result<Vec<_>>>()?;
MemorySourceConfig::try_new_as_values(Arc::clone(schema.inner()), exprs)?
as _
}
LogicalPlan::EmptyRelation(EmptyRelation {
produce_one_row: false,
schema,
}) => Arc::new(EmptyExec::new(Arc::clone(schema.inner()))),
LogicalPlan::EmptyRelation(EmptyRelation {
produce_one_row: true,
schema,
}) => Arc::new(PlaceholderRowExec::new(Arc::clone(schema.inner()))),
LogicalPlan::Show(Show {
kind: ShowKind::Tables,
..
}) => create_information_schema_provider(session).show_tables()?,
LogicalPlan::Show(Show {
kind: ShowKind::Describe { schema },
..
}) => create_information_schema_provider(session).describe_schema(schema)?,
LogicalPlan::Show(Show {
kind: ShowKind::Columns { table_ref, detail },
..
}) => {
let catalog_options = &session.config_options().catalog;
let resolved = table_ref.clone().resolve(
&catalog_options.default_catalog,
&catalog_options.default_schema,
);
create_information_schema_provider(session)
.show_columns(&resolved, *detail)
.await?
}
LogicalPlan::Show(Show {
kind: ShowKind::CreateTable { table_ref },
..
}) => {
let catalog_options = &session.config_options().catalog;
let resolved = table_ref.clone().resolve(
&catalog_options.default_catalog,
&catalog_options.default_schema,
);
create_information_schema_provider(session)
.show_create_table(&resolved)
.await?
}
LogicalPlan::Show(Show {
kind: ShowKind::Variables { name, verbose },
..
}) => create_information_schema_provider(session).show_variables(
session.config_options(),
session.runtime_env(),
name.as_deref(),
*verbose,
)?,
LogicalPlan::Show(Show {
kind: ShowKind::Functions { filter },
..
}) => {
// Table functions (UDTFs) are only reachable through the
// concrete `SessionState` (the `Session` trait has no
// accessor for them); a custom `Session` implementor will
// simply see no `TABLE`-typed routines in `SHOW FUNCTIONS`.
let table_functions = session
.as_any()
.downcast_ref::<SessionState>()
.map(|state| state.table_functions().clone())
.unwrap_or_default();
create_information_schema_provider(session)
.with_table_functions(table_functions)
.show_functions(
session.scalar_functions(),
session.aggregate_functions(),
session.window_functions(),
filter.as_deref(),
)?
}
LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(scan)) => {
// Unbound until `bind_materialized_cte_scans` runs on the whole plan.
Arc::new(MaterializedCteScanExec::new(
scan.id.as_u64(),
&scan.name,
Arc::clone(scan.schema.inner()),
session.config().target_partitions(),
))
}
// 1 Child
LogicalPlan::Copy(CopyTo {
input,
output_url,
file_type,
partition_by,
options: source_option_tuples,
output_schema: _,
}) => {
let original_url = output_url.clone();
let input_exec = children.one()?;
let parsed_url = ListingTableUrl::parse(output_url)?;
let object_store_url = parsed_url.object_store();
let schema = Arc::clone(input.schema().inner());
// Note: the DataType passed here is ignored for the purposes of writing and inferred instead
// from the schema of the RecordBatch being written. This allows COPY statements to specify only
// the column name rather than column name + explicit data type.
let table_partition_cols = partition_by
.iter()
.map(|s| (s.to_string(), DataType::Null))
.collect::<Vec<_>>();
let keep_partition_by_columns = match source_option_tuples
.get("execution.keep_partition_by_columns")
.map(|v| v.trim())
{
None => {
session
.config()
.options()
.execution
.keep_partition_by_columns
}
Some("true") => true,
Some("false") => false,
Some(value) => {
return Err(DataFusionError::Configuration(format!(
"provided value for 'execution.keep_partition_by_columns' was not recognized: \"{value}\""
)));
}
};
// Parse single_file_output option if explicitly set
let file_output_mode = match source_option_tuples
.get("single_file_output")