forked from apache/datafusion
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathplanner.rs
More file actions
5596 lines (5124 loc) · 227 KB
/
planner.rs
File metadata and controls
5596 lines (5124 loc) · 227 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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::iter;
use std::ops::RangeFrom;
use std::str::FromStr;
use std::sync::{Arc, Mutex, RwLock};
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::EmptyRelation;
use crate::logical_plan::Expr::Alias;
use crate::logical_plan::{
and, builder::expand_qualified_wildcard, builder::expand_wildcard, col, lit,
normalize_col, rewrite_udtfs_to_columns, Column, CreateMemoryTable, DFSchema,
DFSchemaRef, DropTable, Expr, ExprSchemable, Like, LogicalPlan, LogicalPlanBuilder,
Operator, PlanType, SubqueryType, ToDFSchema, ToStringifiedPlan,
};
use crate::optimizer::utils::exprlist_to_columns;
use crate::prelude::JoinType;
use crate::scalar::ScalarValue;
use crate::sql::utils::{
find_udtf_exprs, make_decimal_type, normalize_ident, realias_duplicate_expr_aliases,
};
use crate::{
error::{DataFusionError, Result},
physical_plan::aggregates,
physical_plan::udaf::AggregateUDF,
physical_plan::udf::ScalarUDF,
physical_plan::udtf::TableUDF,
sql::parser::{CreateExternalTable, FileType, Statement as DFStatement},
};
use arrow::datatypes::*;
use datafusion_expr::{window_function::WindowFunction, BuiltinScalarFunction};
use hashbrown::HashMap;
use log::warn;
use datafusion_expr::expr::GroupingSet;
use sqlparser::ast::{
ArrayAgg, BinaryOperator, DataType as SQLDataType, DateTimeField, Expr as SQLExpr,
Fetch, FunctionArg, FunctionArgExpr, Ident, Join, JoinConstraint, JoinOperator,
ObjectName, Offset as SQLOffset, Query, Select, SelectItem, SetExpr, SetOperator,
SetOperatorOption, ShowStatementFilter, TableFactor, TableWithJoins, TrimWhereField,
UnaryOperator, Value, Values as SQLValues, WithinGroup,
};
use sqlparser::ast::{ColumnDef as SQLColumnDef, ColumnOption};
use sqlparser::ast::{ObjectType, 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, table_udfs};
use crate::logical_plan::plan::{
Analyze, CreateCatalogSchema, CreateExternalTable as PlanCreateExternalTable, Explain,
};
/// 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 UDTF description
fn get_table_function_meta(&self, name: &str) -> Option<Arc<TableUDF>>;
/// Getter for a UDAF description
fn get_aggregate_meta(&self, name: &str) -> Option<Arc<AggregateUDF>>;
/// Getter for system/user-defined variable type
fn get_variable_type(&self, variable_names: &[String]) -> Option<DataType>;
}
/// SQL query planner
pub struct SqlToRel<'a, S: ContextProvider> {
schema_provider: &'a S,
table_columns_precedence_over_projection: bool,
context: SqlToRelContext,
subquery_alias_iter: Arc<Mutex<RangeFrom<u32>>>,
}
/// Planning context
#[derive(Default)]
pub struct SqlToRelContext {
outer_query_context_schema: Vec<DFSchemaRef>,
subqueries_plans: Option<RwLock<Vec<(LogicalPlan, SubqueryType)>>>,
ctes: HashMap<String, LogicalPlan>,
}
impl SqlToRelContext {
/// Used to copy new version context based on the current one
pub fn fork(&self) -> Self {
Self {
outer_query_context_schema: self.outer_query_context_schema.clone(),
subqueries_plans: None,
ctes: self.ctes.clone(),
}
}
fn add_subquery_plan(
&self,
plan: LogicalPlan,
subquery_type: SubqueryType,
) -> Result<()> {
self.subqueries_plans.as_ref().ok_or_else(|| DataFusionError::Plan(format!("Sub query {:?} planned outside of sub query context. This type of sub query isn't supported", plan)))?.write().unwrap().push((plan, subquery_type));
Ok(())
}
fn subqueries_plans(&self) -> Result<Option<Vec<(LogicalPlan, SubqueryType)>>> {
Ok(if let Some(subqueries) = self.subqueries_plans.as_ref() {
Some(
subqueries
.read()
.map_err(|e| DataFusionError::Plan(e.to_string()))?
.iter()
.cloned()
.collect(),
)
} else {
None
})
}
}
fn plan_indexed(expr: Expr, mut keys: Vec<Expr>) -> Result<Expr> {
let key = keys.pop().ok_or_else(|| {
DataFusionError::SQL(ParserError(
"Internal error: Missing index key expression".to_string(),
))
})?;
let expr = if !keys.is_empty() {
plan_indexed(expr, keys)?
} else {
expr
};
Ok(Expr::GetIndexedField {
expr: Box::new(expr),
key: Box::new(key),
})
}
impl<'a, S: ContextProvider> SqlToRel<'a, S> {
/// Create a new query planner
pub fn new(schema_provider: &'a S) -> Self {
Self::new_with_options(schema_provider, false)
}
/// Create a new query planner
pub fn new_with_options(
schema_provider: &'a S,
table_columns_precedence_over_projection: bool,
) -> Self {
SqlToRel {
schema_provider,
table_columns_precedence_over_projection,
context: SqlToRelContext::default(),
subquery_alias_iter: Arc::new(Mutex::new(0..)),
}
}
/// Creates new version of SqlToRel with forked planning context
pub fn with_context(&self, f: impl FnOnce(&mut SqlToRelContext)) -> Self {
let mut context = self.context.fork();
f(&mut context);
SqlToRel {
schema_provider: self.schema_provider,
table_columns_precedence_over_projection: self
.table_columns_precedence_over_projection,
context,
subquery_alias_iter: Arc::clone(&self.subquery_alias_iter),
}
}
/// 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::CreateTable {
query: Some(query),
name,
columns,
constraints,
table_properties,
with_options,
..
} if columns.is_empty()
&& constraints.is_empty()
&& table_properties.is_empty()
&& with_options.is_empty() =>
{
let plan = self.query_to_plan(*query)?;
Ok(LogicalPlan::CreateMemoryTable(CreateMemoryTable {
name: name.to_string(),
input: Arc::new(plan),
}))
}
Statement::CreateTable { .. } => Err(DataFusionError::NotImplemented(
"Only `CREATE TABLE table_name AS SELECT ...` statement is supported"
.to_string(),
)),
Statement::CreateSchema {
schema_name,
if_not_exists,
} => Ok(LogicalPlan::CreateCatalogSchema(CreateCatalogSchema {
schema_name: schema_name.to_string(),
if_not_exists,
schema: Arc::new(DFSchema::empty()),
})),
Statement::Drop {
object_type: ObjectType::Table,
if_exists,
names,
cascade: _,
purge: _,
} =>
// We don't support cascade and purge for now.
{
Ok(LogicalPlan::DropTable(DropTable {
name: names.get(0).unwrap().to_string(),
if_exists,
schema: DFSchemaRef::new(DFSchema::empty()),
}))
}
Statement::ShowTables {
extended,
full,
db_name,
filter,
} => self.show_tables_to_plan(extended, full, db_name, filter),
Statement::ShowColumns {
extended,
full,
table_name,
filter,
} => self.show_columns_to_plan(extended, full, &table_name, filter.as_ref()),
_ => Err(DataFusionError::NotImplemented(format!(
"Unsupported SQL statement: {:?}",
sql
))),
}
}
/// Generate a logical plan from a "SHOW TABLES" query
fn show_tables_to_plan(
&self,
extended: bool,
full: bool,
db_name: Option<Ident>,
filter: Option<ShowStatementFilter>,
) -> Result<LogicalPlan> {
if self.has_table("information_schema", "tables") {
// we only support the basic "SHOW TABLES"
// https://github.com/apache/arrow-datafusion/issues/3188
if db_name.is_some() || filter.is_some() || full || extended {
Err(DataFusionError::Plan(
"Unsupported parameters to SHOW TABLES".to_string(),
))
} else {
let query = "SELECT * FROM information_schema.tables;";
let mut rewrite = DFParser::parse_sql(query)?;
assert_eq!(rewrite.len(), 1);
self.statement_to_plan(rewrite.pop_front().unwrap())
}
} else {
Err(DataFusionError::Plan(
"SHOW TABLES is not supported unless information_schema is enabled"
.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)
}
/// Generate a logic plan from an SQL query with optional alias
pub fn query_to_plan_with_alias(
&self,
query: Query,
alias: Option<String>,
) -> Result<LogicalPlan> {
let set_expr = query.body;
let mut ctes = self.context.ctes.clone();
if let Some(with) = query.with {
// Process CTEs from top to bottom
// do not allow self-references
for cte in with.cte_tables {
// A `WITH` block can't use the same name for many times
let cte_name: &str = cte.alias.name.value.as_ref();
if ctes.contains_key(cte_name) {
return Err(DataFusionError::SQL(ParserError(format!(
"WITH query name {:?} specified more than once",
cte_name
))));
}
let with_cte_context = self.with_context(|c| c.ctes = ctes.clone());
// create logical plan & pass backreferencing CTEs
let logical_plan = with_cte_context.query_to_plan_with_alias(
*cte.query,
Some(cte.alias.name.value.clone()),
)?;
ctes.insert(cte.alias.name.value, logical_plan);
}
}
let with_cte_context = self.with_context(|c| c.ctes = ctes);
let plan = with_cte_context.set_expr_to_plan(set_expr, alias)?;
let plan = with_cte_context.order_by(plan, query.order_by)?;
with_cte_context.limit(plan, query.offset, query.limit, query.fetch)
}
fn set_expr_to_plan(
&self,
set_expr: SetExpr,
alias: Option<String>,
) -> Result<LogicalPlan> {
match set_expr {
SetExpr::Select(s) => self.select_to_plan(*s, alias),
SetExpr::Values(v) => self.sql_values_to_plan(v),
SetExpr::SetOperation {
op,
left,
right,
option,
} => {
let left_plan = self.set_expr_to_plan(*left, None)?;
let right_plan = self.set_expr_to_plan(*right, None)?;
match (op, option) {
(SetOperator::Union, Some(SetOperatorOption::All)) => {
LogicalPlanBuilder::from(left_plan)
.union(right_plan)?
.build()
}
(SetOperator::Union, None)
| (SetOperator::Union, Some(SetOperatorOption::Distinct)) => {
LogicalPlanBuilder::from(left_plan)
.union_distinct(right_plan)?
.build()
}
(SetOperator::Intersect, Some(SetOperatorOption::All)) => {
LogicalPlanBuilder::intersect(left_plan, right_plan, true)
}
(SetOperator::Intersect, None)
| (SetOperator::Intersect, Some(SetOperatorOption::Distinct)) => {
LogicalPlanBuilder::intersect(left_plan, right_plan, false)
}
(SetOperator::Except, Some(SetOperatorOption::All)) => {
LogicalPlanBuilder::except(left_plan, right_plan, true)
}
(SetOperator::Except, None)
| (SetOperator::Except, Some(SetOperatorOption::Distinct)) => {
LogicalPlanBuilder::except(left_plan, right_plan, false)
}
}
}
SetExpr::Query(q) => self.query_to_plan_with_alias(*q, None),
_ => 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,
table_partition_cols,
} = 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(PlanCreateExternalTable {
schema: schema.to_dfschema_ref()?,
name,
location,
file_type,
has_header,
table_partition_cols,
}))
}
/// 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(Analyze {
verbose,
input: plan,
schema,
}))
} else {
let stringified_plans =
vec![plan.to_stringified(PlanType::InitialLogicalPlan)];
Ok(LogicalPlan::Explain(Explain {
verbose,
plan,
stringified_plans,
schema,
}))
}
}
fn build_schema(&self, columns: Vec<SQLColumnDef>) -> Result<Schema> {
let mut fields = Vec::with_capacity(columns.len());
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(_) => Ok(DataType::Int64),
SQLDataType::Int(_) => Ok(DataType::Int32),
SQLDataType::SmallInt(_) => Ok(DataType::Int16),
SQLDataType::Char(_) | SQLDataType::Varchar(_) | SQLDataType::Text => {
Ok(DataType::Utf8)
}
SQLDataType::Decimal(precision, scale) => {
make_decimal_type(*precision, *scale)
}
SQLDataType::Float(_) => Ok(DataType::Float32),
SQLDataType::Real => Ok(DataType::Float32),
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: Vec<TableWithJoins>) -> Result<Vec<LogicalPlan>> {
match from.len() {
0 => Ok(vec![LogicalPlanBuilder::empty(true).build()?]),
_ => from
.into_iter()
.map(|t| self.plan_table_with_joins(t))
.collect::<Result<Vec<_>>>(),
}
}
fn plan_table_with_joins(&self, t: TableWithJoins) -> Result<LogicalPlan> {
let left = self.create_relation(t.relation)?;
match t.joins.len() {
0 => Ok(left),
_ => {
let mut joins = t.joins.into_iter();
let mut left = self.parse_relation_join(left, joins.next().unwrap())?;
for join in joins {
left = self.parse_relation_join(left, join)?;
}
Ok(left)
}
}
}
fn parse_relation_join(&self, left: LogicalPlan, join: Join) -> Result<LogicalPlan> {
let right = self.create_relation(join.relation)?;
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 left_keys.is_empty() {
// When we don't have join keys, use cross join
let join = LogicalPlanBuilder::from(left).cross_join(&right)?;
join.filter(filter.into_iter().reduce(Expr::and).unwrap())?
.build()
} else 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.into_iter().reduce(Expr::and).unwrap())?
.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()
},
)
{
let join_filter_init = filter.remove(0);
LogicalPlanBuilder::from(left)
.join(
&LogicalPlanBuilder::from(right)
.filter(
filter
.into_iter()
.fold(join_filter_init, |acc, e| acc.and(e)),
)?
.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()
},
)
{
let join_filter_init = filter.remove(0);
LogicalPlanBuilder::from(left)
.filter(
filter
.into_iter()
.fold(join_filter_init, |acc, e| acc.and(e)),
)?
.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
.into_iter()
.map(|x| Column::from_name(x.value))
.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) -> Result<LogicalPlan> {
let (plan, alias) = match relation {
TableFactor::Table {
ref name,
alias,
args,
..
} => {
let table_name = normalize_sql_object_name(name);
let table_ref: TableReference = table_name.as_str().into();
let table_alias = alias.as_ref().map(|i| i.name.value.to_string());
let default_table_alias =
name.0.iter().last().map(|i| i.value.to_string()).unwrap();
let cte = self.context.ctes.get(&table_name);
let plan = match (cte, self.schema_provider.get_table_provider(table_ref))
{
(Some(cte_plan), _) => match table_alias {
Some(cte_alias) => project_with_alias(
cte_plan.clone(),
vec![Expr::Wildcard],
Some(cte_alias),
),
_ => Ok(cte_plan.clone()),
},
(_, Some(provider)) => LogicalPlanBuilder::scan(
// take alias into account to support `JOIN table1 as table2`
table_alias.unwrap_or(default_table_alias),
provider,
None,
)?
.build(),
(None, None) => {
let table_udf =
self.schema_provider.get_table_function_meta(&table_name);
if table_udf.is_some() {
let udtf = Expr::TableUDF {
fun: table_udf.unwrap(),
args: self
.function_args_to_expr(args, &DFSchema::empty())
.unwrap(),
};
let udtf_plan = table_udfs(
LogicalPlan::EmptyRelation(EmptyRelation {
produce_one_row: true,
schema: Arc::new(DFSchema::empty()),
}),
vec![udtf.clone()],
)
.unwrap();
if alias.is_none() {
return Ok(udtf_plan);
}
let mut select_exprs = rewrite_udtfs_to_columns(
vec![udtf],
udtf_plan.schema().clone().as_ref().to_owned(),
);
let alias = alias.unwrap();
if !alias.columns.is_empty() {
select_exprs = select_exprs
.iter()
.enumerate()
.map(|(i, e)| {
if alias.columns.len() > i {
Expr::Alias(
Box::new(e.clone()),
alias.columns[i].to_string(),
)
} else {
e.clone()
}
})
.collect();
}
return project_with_alias(
udtf_plan,
select_exprs,
Some(alias.name.value),
);
}
Err(DataFusionError::Plan(format!(
"Table or CTE with name '{}' not found",
name
)))
}
}?;
(plan, 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()),
)?;
(
project_with_alias(
logical_plan.clone(),
logical_plan.schema().fields().iter().map(|field| {
Expr::Column(Column {
relation: None,
name: field.name().clone(),
})
}),
alias.as_ref().map(|a| a.name.value.to_string()),
)?,
alias,
)
}
TableFactor::NestedJoin(table_with_joins) => {
(self.plan_table_with_joins(*table_with_joins)?, 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() {
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.name.value),
)?
.build()?)
}
} else {
Ok(plan)
}
}
/// Generate a logic plan from selection clause, the function contain optimization for cross join to inner join
/// Related PR: <https://github.com/apache/arrow-datafusion/pull/1566>
fn plan_selection(
&self,
selection: Option<SQLExpr>,
plans: Vec<LogicalPlan>,
) -> Result<LogicalPlan> {
// TODO: enable subqueries for joins
let plan = match selection {
Some(predicate_expr) => {
// build join schema
let mut fields = vec![];
let mut metadata = std::collections::HashMap::new();
for plan in &plans {
fields.extend_from_slice(plan.schema().fields());
metadata.extend(plan.schema().metadata().clone());
}
let join_schema = DFSchema::new_with_metadata(fields, metadata)?;
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 plans = plans.into_iter();
let mut left = plans.next().unwrap(); // have at least one plan
// List of the plans that have not yet been joined
let mut remaining_plans: Vec<Option<LogicalPlan>> =
plans.into_iter().map(Some).collect();
// Take from the list of remaining plans,
loop {
let mut join_keys = vec![];
// Search all remaining plans for the next to
// join. Prefer the first one that has a join
// predicate in the predicate lists
let plan_with_idx =
remaining_plans.iter().enumerate().find(|(_idx, plan)| {
// skip plans that have been joined already
let plan = if let Some(plan) = plan {
plan
} else {
return false;
};
// can we find a match?
let left_schema = left.schema();
let right_schema = plan.schema();
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()));
}
}
// stop if we found join keys
!join_keys.is_empty()
});
// If we did not find join keys, either there are
// no more plans, or we can't find any plans that
// can be joined with predicates
if join_keys.is_empty() {
assert!(plan_with_idx.is_none());
// pick the first non null plan to join
let plan_with_idx = remaining_plans
.iter()
.enumerate()
.find(|(_idx, plan)| plan.is_some());
if let Some((idx, _)) = plan_with_idx {
let plan = std::mem::take(&mut remaining_plans[idx]).unwrap();
left = LogicalPlanBuilder::from(left)
.cross_join(&plan)?
.build()?;
} else {
// no more plans to join
break;
}
} else {
// have a plan
let (idx, _) = plan_with_idx.expect("found plan node");
let plan = std::mem::take(&mut remaining_plans[idx]).unwrap();
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(&plan, 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) => {
let left = self.wrap_with_subquery_plan_if_necessary(left)?;
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)
}
}