-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
planner.rs
3674 lines (3363 loc) · 148 KB
/
planner.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.
//! SQL Query Planner (produces logical plan from SQL AST)
use std::collections::HashSet;
use std::str::FromStr;
use std::sync::Arc;
use std::{convert::TryInto, vec};
use crate::catalog::TableReference;
use crate::datasource::TableProvider;
use crate::logical_plan::window_frames::{WindowFrame, WindowFrameUnits};
use crate::logical_plan::Expr::Alias;
use crate::logical_plan::{
and, builder::expand_wildcard, col, lit, normalize_col, union_with_alias, Column,
DFSchema, Expr, LogicalPlan, LogicalPlanBuilder, Operator, PlanType, ToDFSchema,
ToStringifiedPlan,
};
use crate::optimizer::utils::exprlist_to_columns;
use crate::prelude::JoinType;
use crate::scalar::ScalarValue;
use crate::{
error::{DataFusionError, Result},
physical_plan::udaf::AggregateUDF,
};
use crate::{
physical_plan::udf::ScalarUDF,
physical_plan::{aggregates, functions, window_functions},
sql::parser::{CreateExternalTable, FileType, Statement as DFStatement},
};
use arrow::datatypes::*;
use hashbrown::HashMap;
use sqlparser::ast::{
BinaryOperator, DataType as SQLDataType, DateTimeField, Expr as SQLExpr, FunctionArg,
Ident, Join, JoinConstraint, JoinOperator, ObjectName, Query, Select, SelectItem,
SetExpr, SetOperator, ShowStatementFilter, TableFactor, TableWithJoins,
TrimWhereField, UnaryOperator, Value, Values as SQLValues,
};
use sqlparser::ast::{ColumnDef as SQLColumnDef, ColumnOption};
use sqlparser::ast::{OrderByExpr, Statement};
use sqlparser::parser::ParserError::ParserError;
use super::{
parser::DFParser,
utils::{
can_columns_satisfy_exprs, expr_as_column_expr, extract_aliases,
find_aggregate_exprs, find_column_exprs, find_window_exprs, rebase_expr,
resolve_aliases_to_exprs, resolve_positions_to_exprs,
},
};
use crate::logical_plan::builder::project_with_alias;
/// The ContextProvider trait allows the query planner to obtain meta-data about tables and
/// functions referenced in SQL statements
pub trait ContextProvider {
/// Getter for a datasource
fn get_table_provider(&self, name: TableReference) -> Option<Arc<dyn TableProvider>>;
/// Getter for a UDF description
fn get_function_meta(&self, name: &str) -> Option<Arc<ScalarUDF>>;
/// Getter for a UDAF description
fn get_aggregate_meta(&self, name: &str) -> Option<Arc<AggregateUDF>>;
}
/// SQL query planner
pub struct SqlToRel<'a, S: ContextProvider> {
schema_provider: &'a S,
}
fn plan_key(key: Value) -> ScalarValue {
match key {
Value::Number(s, _) => ScalarValue::Int64(Some(s.parse().unwrap())),
Value::SingleQuotedString(s) => ScalarValue::Utf8(Some(s)),
_ => unreachable!(),
}
}
#[allow(clippy::branches_sharing_code)]
fn plan_indexed(expr: Expr, mut keys: Vec<Value>) -> Expr {
if keys.len() == 1 {
let key = keys.pop().unwrap();
Expr::GetIndexedField {
expr: Box::new(expr),
key: plan_key(key),
}
} else {
let key = keys.pop().unwrap();
let expr = Box::new(plan_indexed(expr, keys));
Expr::GetIndexedField {
expr,
key: plan_key(key),
}
}
}
impl<'a, S: ContextProvider> SqlToRel<'a, S> {
/// Create a new query planner
pub fn new(schema_provider: &'a S) -> Self {
SqlToRel { schema_provider }
}
/// Generate a logical plan from an DataFusion SQL statement
pub fn statement_to_plan(&self, statement: &DFStatement) -> Result<LogicalPlan> {
match statement {
DFStatement::CreateExternalTable(s) => self.external_table_to_plan(s),
DFStatement::Statement(s) => self.sql_statement_to_plan(s),
}
}
/// Generate a logical plan from an SQL statement
pub fn sql_statement_to_plan(&self, sql: &Statement) -> Result<LogicalPlan> {
match sql {
Statement::Explain {
verbose,
statement,
analyze,
describe_alias: _,
} => self.explain_statement_to_plan(*verbose, *analyze, statement),
Statement::Query(query) => self.query_to_plan(query),
Statement::ShowVariable { variable } => self.show_variable_to_plan(variable),
Statement::ShowColumns {
extended,
full,
table_name,
filter,
} => self.show_columns_to_plan(*extended, *full, table_name, filter.as_ref()),
_ => Err(DataFusionError::NotImplemented(
"Only SELECT statements are implemented".to_string(),
)),
}
}
/// Generate a logic plan from an SQL query
pub fn query_to_plan(&self, query: &Query) -> Result<LogicalPlan> {
self.query_to_plan_with_alias(query, None, &mut HashMap::new())
}
/// Generate a logic plan from an SQL query with optional alias
pub fn query_to_plan_with_alias(
&self,
query: &Query,
alias: Option<String>,
ctes: &mut HashMap<String, LogicalPlan>,
) -> Result<LogicalPlan> {
let set_expr = &query.body;
if let Some(with) = &query.with {
// Process CTEs from top to bottom
// do not allow self-references
for cte in &with.cte_tables {
// create logical plan & pass backreferencing CTEs
let logical_plan = self.query_to_plan_with_alias(
&cte.query,
Some(cte.alias.name.value.clone()),
&mut ctes.clone(),
)?;
ctes.insert(cte.alias.name.value.clone(), logical_plan);
}
}
let plan = self.set_expr_to_plan(set_expr, alias, ctes)?;
let plan = self.order_by(plan, &query.order_by)?;
self.limit(plan, &query.limit)
}
fn set_expr_to_plan(
&self,
set_expr: &SetExpr,
alias: Option<String>,
ctes: &mut HashMap<String, LogicalPlan>,
) -> Result<LogicalPlan> {
match set_expr {
SetExpr::Select(s) => self.select_to_plan(s.as_ref(), ctes, alias),
SetExpr::Values(v) => self.sql_values_to_plan(v),
SetExpr::SetOperation {
op,
left,
right,
all,
} => match (op, all) {
(SetOperator::Union, true) => {
let left_plan = self.set_expr_to_plan(left.as_ref(), None, ctes)?;
let right_plan = self.set_expr_to_plan(right.as_ref(), None, ctes)?;
union_with_alias(left_plan, right_plan, alias)
}
(SetOperator::Union, false) => {
let left_plan = self.set_expr_to_plan(left.as_ref(), None, ctes)?;
let right_plan = self.set_expr_to_plan(right.as_ref(), None, ctes)?;
let union_plan = union_with_alias(left_plan, right_plan, alias)?;
LogicalPlanBuilder::from(union_plan).distinct()?.build()
}
_ => Err(DataFusionError::NotImplemented(format!(
"Only UNION ALL and UNION [DISTINCT] are supported, found {}",
op
))),
},
_ => Err(DataFusionError::NotImplemented(format!(
"Query {} not implemented yet",
set_expr
))),
}
}
/// Generate a logical plan from a CREATE EXTERNAL TABLE statement
pub fn external_table_to_plan(
&self,
statement: &CreateExternalTable,
) -> Result<LogicalPlan> {
let CreateExternalTable {
name,
columns,
file_type,
has_header,
location,
} = statement;
// semantic checks
match *file_type {
FileType::CSV => {}
FileType::Parquet => {
if !columns.is_empty() {
return Err(DataFusionError::Plan(
"Column definitions can not be specified for PARQUET files."
.into(),
));
}
}
FileType::NdJson => {}
FileType::Avro => {}
};
let schema = self.build_schema(columns)?;
Ok(LogicalPlan::CreateExternalTable {
schema: schema.to_dfschema_ref()?,
name: name.clone(),
location: location.clone(),
file_type: *file_type,
has_header: *has_header,
})
}
/// Generate a plan for EXPLAIN ... that will print out a plan
///
pub fn explain_statement_to_plan(
&self,
verbose: bool,
analyze: bool,
statement: &Statement,
) -> Result<LogicalPlan> {
let plan = self.sql_statement_to_plan(statement)?;
let plan = Arc::new(plan);
let schema = LogicalPlan::explain_schema();
let schema = schema.to_dfschema_ref()?;
if analyze {
Ok(LogicalPlan::Analyze {
verbose,
input: plan,
schema,
})
} else {
let stringified_plans =
vec![plan.to_stringified(PlanType::InitialLogicalPlan)];
Ok(LogicalPlan::Explain {
verbose,
plan,
stringified_plans,
schema,
})
}
}
fn build_schema(&self, columns: &[SQLColumnDef]) -> Result<Schema> {
let mut fields = Vec::new();
for column in columns {
let data_type = self.make_data_type(&column.data_type)?;
let allow_null = column
.options
.iter()
.any(|x| x.option == ColumnOption::Null);
fields.push(Field::new(&column.name.value, data_type, allow_null));
}
Ok(Schema::new(fields))
}
/// Maps the SQL type to the corresponding Arrow `DataType`
fn make_data_type(&self, sql_type: &SQLDataType) -> Result<DataType> {
match sql_type {
SQLDataType::BigInt(_display) => Ok(DataType::Int64),
SQLDataType::Int(_display) => Ok(DataType::Int32),
SQLDataType::SmallInt(_display) => Ok(DataType::Int16),
SQLDataType::Char(_) | SQLDataType::Varchar(_) | SQLDataType::Text => {
Ok(DataType::Utf8)
}
SQLDataType::Decimal(_, _) => Ok(DataType::Float64),
SQLDataType::Float(_) => Ok(DataType::Float32),
SQLDataType::Real | SQLDataType::Double => Ok(DataType::Float64),
SQLDataType::Boolean => Ok(DataType::Boolean),
SQLDataType::Date => Ok(DataType::Date32),
SQLDataType::Time => Ok(DataType::Time64(TimeUnit::Millisecond)),
SQLDataType::Timestamp => Ok(DataType::Timestamp(TimeUnit::Nanosecond, None)),
_ => Err(DataFusionError::NotImplemented(format!(
"The SQL data type {:?} is not implemented",
sql_type
))),
}
}
fn plan_from_tables(
&self,
from: &[TableWithJoins],
ctes: &mut HashMap<String, LogicalPlan>,
) -> Result<Vec<LogicalPlan>> {
match from.len() {
0 => Ok(vec![LogicalPlanBuilder::empty(true).build()?]),
_ => from
.iter()
.map(|t| self.plan_table_with_joins(t, ctes))
.collect::<Result<Vec<_>>>(),
}
}
fn plan_table_with_joins(
&self,
t: &TableWithJoins,
ctes: &mut HashMap<String, LogicalPlan>,
) -> Result<LogicalPlan> {
let left = self.create_relation(&t.relation, ctes)?;
match t.joins.len() {
0 => Ok(left),
n => {
let mut left = self.parse_relation_join(left, &t.joins[0], ctes)?;
for i in 1..n {
left = self.parse_relation_join(left, &t.joins[i], ctes)?;
}
Ok(left)
}
}
}
fn parse_relation_join(
&self,
left: LogicalPlan,
join: &Join,
ctes: &mut HashMap<String, LogicalPlan>,
) -> Result<LogicalPlan> {
let right = self.create_relation(&join.relation, ctes)?;
match &join.join_operator {
JoinOperator::LeftOuter(constraint) => {
self.parse_join(left, right, constraint, JoinType::Left)
}
JoinOperator::RightOuter(constraint) => {
self.parse_join(left, right, constraint, JoinType::Right)
}
JoinOperator::Inner(constraint) => {
self.parse_join(left, right, constraint, JoinType::Inner)
}
JoinOperator::FullOuter(constraint) => {
self.parse_join(left, right, constraint, JoinType::Full)
}
JoinOperator::CrossJoin => self.parse_cross_join(left, &right),
other => Err(DataFusionError::NotImplemented(format!(
"Unsupported JOIN operator {:?}",
other
))),
}
}
fn parse_cross_join(
&self,
left: LogicalPlan,
right: &LogicalPlan,
) -> Result<LogicalPlan> {
LogicalPlanBuilder::from(left).cross_join(right)?.build()
}
fn parse_join(
&self,
left: LogicalPlan,
right: LogicalPlan,
constraint: &JoinConstraint,
join_type: JoinType,
) -> Result<LogicalPlan> {
match constraint {
JoinConstraint::On(sql_expr) => {
let mut keys: Vec<(Column, Column)> = vec![];
let join_schema = left.schema().join(right.schema())?;
// parse ON expression
let expr = self.sql_to_rex(sql_expr, &join_schema)?;
// expression that didn't match equi-join pattern
let mut filter = vec![];
// extract join keys
extract_join_keys(&expr, &mut keys, &mut filter);
let mut cols = HashSet::new();
exprlist_to_columns(&filter, &mut cols)?;
let (left_keys, right_keys): (Vec<Column>, Vec<Column>) =
keys.into_iter().unzip();
// return the logical plan representing the join
if filter.is_empty() {
let join = LogicalPlanBuilder::from(left).join(
&right,
join_type,
(left_keys, right_keys),
)?;
join.build()
} else if join_type == JoinType::Inner {
let join = LogicalPlanBuilder::from(left).join(
&right,
join_type,
(left_keys, right_keys),
)?;
join.filter(
filter
.iter()
.skip(1)
.fold(filter[0].clone(), |acc, e| acc.and(e.clone())),
)?
.build()
}
// Left join with all non-equijoin expressions from the right
// l left join r
// on l1=r1 and r2 > [..]
else if join_type == JoinType::Left
&& cols.iter().all(
|Column {
relation: qualifier,
name,
}| {
right
.schema()
.field_with_name(qualifier.as_deref(), name)
.is_ok()
},
)
{
LogicalPlanBuilder::from(left)
.join(
&LogicalPlanBuilder::from(right)
.filter(
filter
.iter()
.skip(1)
.fold(filter[0].clone(), |acc, e| {
acc.and(e.clone())
}),
)?
.build()?,
join_type,
(left_keys, right_keys),
)?
.build()
}
// Right join with all non-equijoin expressions from the left
// l right join r
// on l1=r1 and l2 > [..]
else if join_type == JoinType::Right
&& cols.iter().all(
|Column {
relation: qualifier,
name,
}| {
left.schema()
.field_with_name(qualifier.as_deref(), name)
.is_ok()
},
)
{
LogicalPlanBuilder::from(left)
.filter(
filter
.iter()
.skip(1)
.fold(filter[0].clone(), |acc, e| acc.and(e.clone())),
)?
.join(&right, join_type, (left_keys, right_keys))?
.build()
} else {
Err(DataFusionError::NotImplemented(format!(
"Unsupported expressions in {:?} JOIN: {:?}",
join_type, filter
)))
}
}
JoinConstraint::Using(idents) => {
let keys: Vec<Column> = idents
.iter()
.map(|x| Column::from_name(x.value.clone()))
.collect();
LogicalPlanBuilder::from(left)
.join_using(&right, join_type, keys)?
.build()
}
JoinConstraint::Natural => {
// https://issues.apache.org/jira/browse/ARROW-10727
Err(DataFusionError::NotImplemented(
"NATURAL JOIN is not supported (https://issues.apache.org/jira/browse/ARROW-10727)".to_string(),
))
}
JoinConstraint::None => Err(DataFusionError::NotImplemented(
"NONE constraint is not supported".to_string(),
)),
}
}
fn create_relation(
&self,
relation: &TableFactor,
ctes: &mut HashMap<String, LogicalPlan>,
) -> Result<LogicalPlan> {
let (plan, alias) = match relation {
TableFactor::Table { name, alias, .. } => {
let table_name = name.to_string();
let cte = ctes.get(&table_name);
(
match (
cte,
self.schema_provider.get_table_provider(name.try_into()?),
) {
(Some(cte_plan), _) => Ok(cte_plan.clone()),
(_, Some(provider)) => LogicalPlanBuilder::scan(
// take alias into account to support `JOIN table1 as table2`
alias
.as_ref()
.map(|a| a.name.value.as_str())
.unwrap_or(&table_name),
provider,
None,
)?
.build(),
(None, None) => Err(DataFusionError::Plan(format!(
"Table or CTE with name '{}' not found",
name
))),
}?,
alias,
)
}
TableFactor::Derived {
subquery, alias, ..
} => {
// if alias is None, return Err
if alias.is_none() {
return Err(DataFusionError::Plan(
"subquery in FROM must have an alias".to_string(),
));
}
let logical_plan = self.query_to_plan_with_alias(
subquery,
alias.as_ref().map(|a| a.name.value.to_string()),
ctes,
)?;
(
project_with_alias(
logical_plan.clone(),
logical_plan
.schema()
.fields()
.iter()
.map(|field| col(field.name())),
alias.as_ref().map(|a| a.name.value.to_string()),
)?,
alias,
)
}
TableFactor::NestedJoin(table_with_joins) => {
(self.plan_table_with_joins(table_with_joins, ctes)?, &None)
}
// @todo Support TableFactory::TableFunction?
_ => {
return Err(DataFusionError::NotImplemented(format!(
"Unsupported ast node {:?} in create_relation",
relation
)))
}
};
if let Some(alias) = alias {
let columns_alias = alias.clone().columns;
if columns_alias.is_empty() {
// sqlparser-rs encodes AS t as an empty list of column alias
Ok(plan)
} else if columns_alias.len() != plan.schema().fields().len() {
return Err(DataFusionError::Plan(format!(
"Source table contains {} columns but only {} names given as column alias",
plan.schema().fields().len(),
columns_alias.len(),
)));
} else {
Ok(LogicalPlanBuilder::from(plan.clone())
.project_with_alias(
plan.schema()
.fields()
.iter()
.zip(columns_alias.iter())
.map(|(field, ident)| col(field.name()).alias(&ident.value)),
Some(alias.clone().name.value),
)?
.build()?)
}
} else {
Ok(plan)
}
}
/// Generate a logic plan from an SQL select
fn select_to_plan(
&self,
select: &Select,
ctes: &mut HashMap<String, LogicalPlan>,
alias: Option<String>,
) -> Result<LogicalPlan> {
let plans = self.plan_from_tables(&select.from, ctes)?;
let plan = match &select.selection {
Some(predicate_expr) => {
// build join schema
let mut fields = vec![];
for plan in &plans {
fields.extend_from_slice(plan.schema().fields());
}
let join_schema = DFSchema::new(fields)?;
let filter_expr = self.sql_to_rex(predicate_expr, &join_schema)?;
// look for expressions of the form `<column> = <column>`
let mut possible_join_keys = vec![];
extract_possible_join_keys(&filter_expr, &mut possible_join_keys)?;
let mut all_join_keys = HashSet::new();
let mut left = plans[0].clone();
for right in plans.iter().skip(1) {
let left_schema = left.schema();
let right_schema = right.schema();
let mut join_keys = vec![];
for (l, r) in &possible_join_keys {
if left_schema.field_from_column(l).is_ok()
&& right_schema.field_from_column(r).is_ok()
{
join_keys.push((l.clone(), r.clone()));
} else if left_schema.field_from_column(r).is_ok()
&& right_schema.field_from_column(l).is_ok()
{
join_keys.push((r.clone(), l.clone()));
}
}
if join_keys.is_empty() {
left =
LogicalPlanBuilder::from(left).cross_join(right)?.build()?;
} else {
let left_keys: Vec<Column> =
join_keys.iter().map(|(l, _)| l.clone()).collect();
let right_keys: Vec<Column> =
join_keys.iter().map(|(_, r)| r.clone()).collect();
let builder = LogicalPlanBuilder::from(left);
left = builder
.join(right, JoinType::Inner, (left_keys, right_keys))?
.build()?;
}
all_join_keys.extend(join_keys);
}
// remove join expressions from filter
match remove_join_expressions(&filter_expr, &all_join_keys)? {
Some(filter_expr) => {
LogicalPlanBuilder::from(left).filter(filter_expr)?.build()
}
_ => Ok(left),
}
}
None => {
if plans.len() == 1 {
Ok(plans[0].clone())
} else {
let mut left = plans[0].clone();
for right in plans.iter().skip(1) {
left =
LogicalPlanBuilder::from(left).cross_join(right)?.build()?;
}
Ok(left)
}
}
};
let plan = plan?;
// The SELECT expressions, with wildcards expanded.
let select_exprs = self.prepare_select_exprs(&plan, &select.projection)?;
// having and group by clause may reference aliases defined in select projection
let projected_plan = self.project(plan.clone(), select_exprs.clone())?;
let mut combined_schema = (**projected_plan.schema()).clone();
combined_schema.merge(plan.schema());
// this alias map is resolved and looked up in both having exprs and group by exprs
let alias_map = extract_aliases(&select_exprs);
// Optionally the HAVING expression.
let having_expr_opt = select
.having
.as_ref()
.map::<Result<Expr>, _>(|having_expr| {
let having_expr =
self.sql_expr_to_logical_expr(having_expr, &combined_schema)?;
// This step "dereferences" any aliases in the HAVING clause.
//
// This is how we support queries with HAVING expressions that
// refer to aliased columns.
//
// For example:
//
// SELECT c1 AS m FROM t HAVING m > 10;
// SELECT c1, MAX(c2) AS m FROM t GROUP BY c1 HAVING m > 10;
//
// are rewritten as, respectively:
//
// SELECT c1 AS m FROM t HAVING c1 > 10;
// SELECT c1, MAX(c2) AS m FROM t GROUP BY c1 HAVING MAX(c2) > 10;
//
let having_expr = resolve_aliases_to_exprs(&having_expr, &alias_map)?;
normalize_col(having_expr, &projected_plan)
})
.transpose()?;
// The outer expressions we will search through for
// aggregates. Aggregates may be sourced from the SELECT...
let mut aggr_expr_haystack = select_exprs.clone();
// ... or from the HAVING.
if let Some(having_expr) = &having_expr_opt {
aggr_expr_haystack.push(having_expr.clone());
}
// All of the aggregate expressions (deduplicated).
let aggr_exprs = find_aggregate_exprs(&aggr_expr_haystack);
let group_by_exprs = select
.group_by
.iter()
.map(|e| {
let group_by_expr = self.sql_expr_to_logical_expr(e, &combined_schema)?;
let group_by_expr = resolve_aliases_to_exprs(&group_by_expr, &alias_map)?;
let group_by_expr =
resolve_positions_to_exprs(&group_by_expr, &select_exprs)
.unwrap_or(group_by_expr);
let group_by_expr = normalize_col(group_by_expr, &projected_plan)?;
self.validate_schema_satisfies_exprs(
plan.schema(),
&[group_by_expr.clone()],
)?;
Ok(group_by_expr)
})
.collect::<Result<Vec<Expr>>>()?;
let (plan, select_exprs_post_aggr, having_expr_post_aggr_opt) = if !group_by_exprs
.is_empty()
|| !aggr_exprs.is_empty()
{
self.aggregate(
plan,
&select_exprs,
&having_expr_opt,
group_by_exprs,
aggr_exprs,
)?
} else {
if let Some(having_expr) = &having_expr_opt {
let available_columns = select_exprs
.iter()
.map(|expr| expr_as_column_expr(expr, &plan))
.collect::<Result<Vec<Expr>>>()?;
// Ensure the HAVING expression is using only columns
// provided by the SELECT.
if !can_columns_satisfy_exprs(&available_columns, &[having_expr.clone()])?
{
return Err(DataFusionError::Plan(
"Having references column(s) not provided by the select"
.to_owned(),
));
}
}
(plan, select_exprs, having_expr_opt)
};
let plan = if let Some(having_expr_post_aggr) = having_expr_post_aggr_opt {
LogicalPlanBuilder::from(plan)
.filter(having_expr_post_aggr)?
.build()?
} else {
plan
};
// window function
let window_func_exprs = find_window_exprs(&select_exprs_post_aggr);
let plan = if window_func_exprs.is_empty() {
plan
} else {
LogicalPlanBuilder::window_plan(plan, window_func_exprs)?
};
let plan = if select.distinct {
return LogicalPlanBuilder::from(plan)
.aggregate(select_exprs_post_aggr, vec![])?
.build();
} else {
plan
};
project_with_alias(plan, select_exprs_post_aggr, alias)
}
/// Returns the `Expr`'s corresponding to a SQL query's SELECT expressions.
///
/// Wildcards are expanded into the concrete list of columns.
fn prepare_select_exprs(
&self,
plan: &LogicalPlan,
projection: &[SelectItem],
) -> Result<Vec<Expr>> {
let input_schema = plan.schema();
projection
.iter()
.map(|expr| self.sql_select_to_rex(expr, input_schema))
.collect::<Result<Vec<Expr>>>()?
.into_iter()
.map(|expr| {
Ok(match expr {
Expr::Wildcard => expand_wildcard(input_schema, plan)?,
_ => vec![normalize_col(expr, plan)?],
})
})
.flat_map(|res| match res {
Ok(v) => v.into_iter().map(Ok).collect(),
Err(e) => vec![Err(e)],
})
.collect::<Result<Vec<Expr>>>()
}
/// Wrap a plan in a projection
fn project(&self, input: LogicalPlan, expr: Vec<Expr>) -> Result<LogicalPlan> {
self.validate_schema_satisfies_exprs(input.schema(), &expr)?;
LogicalPlanBuilder::from(input).project(expr)?.build()
}
/// Wrap a plan in an aggregate
fn aggregate(
&self,
input: LogicalPlan,
select_exprs: &[Expr],
having_expr_opt: &Option<Expr>,
group_by_exprs: Vec<Expr>,
aggr_exprs: Vec<Expr>,
) -> Result<(LogicalPlan, Vec<Expr>, Option<Expr>)> {
let aggr_projection_exprs = group_by_exprs
.iter()
.chain(aggr_exprs.iter())
.cloned()
.collect::<Vec<Expr>>();
let plan = LogicalPlanBuilder::from(input.clone())
.aggregate(group_by_exprs, aggr_exprs)?
.build()?;
// After aggregation, these are all of the columns that will be
// available to next phases of planning.
let column_exprs_post_aggr = aggr_projection_exprs
.iter()
.map(|expr| expr_as_column_expr(expr, &input))
.collect::<Result<Vec<Expr>>>()?;
// Rewrite the SELECT expression to use the columns produced by the
// aggregation.
let select_exprs_post_aggr = select_exprs
.iter()
.map(|expr| rebase_expr(expr, &aggr_projection_exprs, &input))
.collect::<Result<Vec<Expr>>>()?;
if !can_columns_satisfy_exprs(&column_exprs_post_aggr, &select_exprs_post_aggr)? {
return Err(DataFusionError::Plan(
"Projection references non-aggregate values".to_owned(),
));
}
// Rewrite the HAVING expression to use the columns produced by the
// aggregation.
let having_expr_post_aggr_opt = if let Some(having_expr) = having_expr_opt {
let having_expr_post_aggr =
rebase_expr(having_expr, &aggr_projection_exprs, &input)?;
if !can_columns_satisfy_exprs(
&column_exprs_post_aggr,
&[having_expr_post_aggr.clone()],
)? {
return Err(DataFusionError::Plan(
"Having references non-aggregate values".to_owned(),
));
}
Some(having_expr_post_aggr)
} else {
None
};
Ok((plan, select_exprs_post_aggr, having_expr_post_aggr_opt))
}
/// Wrap a plan in a limit
fn limit(&self, input: LogicalPlan, limit: &Option<SQLExpr>) -> Result<LogicalPlan> {
match *limit {
Some(ref limit_expr) => {
let n = match self.sql_to_rex(limit_expr, input.schema())? {
Expr::Literal(ScalarValue::Int64(Some(n))) => Ok(n as usize),
_ => Err(DataFusionError::Plan(
"Unexpected expression for LIMIT clause".to_string(),
)),
}?;
LogicalPlanBuilder::from(input).limit(n)?.build()
}
_ => Ok(input),
}
}
/// Wrap the logical in a sort
fn order_by(
&self,
plan: LogicalPlan,
order_by: &[OrderByExpr],
) -> Result<LogicalPlan> {
if order_by.is_empty() {
return Ok(plan);
}
let order_by_rex = order_by
.iter()
.map(|e| self.order_by_to_sort_expr(e, plan.schema()))
.collect::<Result<Vec<_>>>()?;
LogicalPlanBuilder::from(plan).sort(order_by_rex)?.build()
}
/// convert sql OrderByExpr to Expr::Sort
fn order_by_to_sort_expr(&self, e: &OrderByExpr, schema: &DFSchema) -> Result<Expr> {
Ok(Expr::Sort {
expr: Box::new(self.sql_expr_to_logical_expr(&e.expr, schema)?),
// by default asc
asc: e.asc.unwrap_or(true),
// by default nulls first to be consistent with spark
nulls_first: e.nulls_first.unwrap_or(true),
})
}
/// Validate the schema provides all of the columns referenced in the expressions.
fn validate_schema_satisfies_exprs(
&self,
schema: &DFSchema,
exprs: &[Expr],
) -> Result<()> {
find_column_exprs(exprs)
.iter()
.try_for_each(|col| match col {
Expr::Column(col) => match &col.relation {
Some(r) => {
schema.field_with_qualified_name(r, &col.name)?;
Ok(())
}
None => {
if !schema.fields_with_unqualified_name(&col.name).is_empty() {
Ok(())
} else {
Err(DataFusionError::Plan(format!(
"No field with unqualified name '{}'",
&col.name
)))
}
}
}
.map_err(|_: DataFusionError| {