forked from apache/datafusion
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
380 lines (354 loc) · 14.6 KB
/
mod.rs
File metadata and controls
380 lines (354 loc) · 14.6 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
// 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.
use std::sync::Arc;
use crate::planner::{ContextProvider, PlannerContext, SqlToRel};
use datafusion_common::tree_node::{Transformed, TreeNode};
use datafusion_common::{
DFSchema, Diagnostic, Result, Span, Spans, TableReference, not_impl_err, plan_err,
};
use datafusion_expr::builder::subquery_alias;
use datafusion_expr::planner::{
PlannedRelation, RelationPlannerContext, RelationPlanning,
};
use datafusion_expr::{Expr, LogicalPlan, LogicalPlanBuilder, expr::Unnest};
use datafusion_expr::{Subquery, SubqueryAlias};
use sqlparser::ast::{FunctionArg, FunctionArgExpr, Spanned, TableFactor};
mod join;
struct SqlToRelRelationContext<'a, 'b, S: ContextProvider> {
planner: &'a SqlToRel<'b, S>,
planner_context: &'a mut PlannerContext,
}
// Implement RelationPlannerContext
impl<'a, 'b, S: ContextProvider> RelationPlannerContext
for SqlToRelRelationContext<'a, 'b, S>
{
fn context_provider(&self) -> &dyn ContextProvider {
self.planner.context_provider
}
fn plan(&mut self, relation: TableFactor) -> Result<LogicalPlan> {
self.planner.create_relation(relation, self.planner_context)
}
fn sql_to_expr(
&mut self,
expr: sqlparser::ast::Expr,
schema: &DFSchema,
) -> Result<Expr> {
self.planner.sql_to_expr(expr, schema, self.planner_context)
}
fn sql_expr_to_logical_expr(
&mut self,
expr: sqlparser::ast::Expr,
schema: &DFSchema,
) -> Result<Expr> {
self.planner
.sql_expr_to_logical_expr(expr, schema, self.planner_context)
}
fn normalize_ident(&self, ident: sqlparser::ast::Ident) -> String {
self.planner.ident_normalizer.normalize(ident)
}
fn object_name_to_table_reference(
&self,
name: sqlparser::ast::ObjectName,
) -> Result<TableReference> {
self.planner.object_name_to_table_reference(name)
}
}
impl<S: ContextProvider> SqlToRel<'_, S> {
/// Create a `LogicalPlan` that scans the named relation.
///
/// First tries any registered extension planners. If no extension handles
/// the relation, falls back to the default planner.
fn create_relation(
&self,
relation: TableFactor,
planner_context: &mut PlannerContext,
) -> Result<LogicalPlan> {
let planned_relation =
match self.create_extension_relation(relation, planner_context)? {
RelationPlanning::Planned(planned) => planned,
RelationPlanning::Original(original) => {
Box::new(self.create_default_relation(*original, planner_context)?)
}
};
let optimized_plan = optimize_subquery_sort(planned_relation.plan)?.data;
if let Some(alias) = planned_relation.alias {
self.apply_table_alias(optimized_plan, alias)
} else {
Ok(optimized_plan)
}
}
fn create_extension_relation(
&self,
relation: TableFactor,
planner_context: &mut PlannerContext,
) -> Result<RelationPlanning> {
let planners = self.context_provider.get_relation_planners();
if planners.is_empty() {
return Ok(RelationPlanning::Original(Box::new(relation)));
}
let mut current_relation = relation;
for planner in planners.iter() {
let mut context = SqlToRelRelationContext {
planner: self,
planner_context,
};
match planner.plan_relation(current_relation, &mut context)? {
RelationPlanning::Planned(planned) => {
return Ok(RelationPlanning::Planned(planned));
}
RelationPlanning::Original(original) => {
current_relation = *original;
}
}
}
Ok(RelationPlanning::Original(Box::new(current_relation)))
}
fn create_default_relation(
&self,
relation: TableFactor,
planner_context: &mut PlannerContext,
) -> Result<PlannedRelation> {
let relation_span = relation.span();
let (plan, alias) = match relation {
TableFactor::Table {
name, alias, args, ..
} => {
if let Some(func_args) = args {
let tbl_func_name =
name.0.first().unwrap().as_ident().unwrap().to_string();
let args = func_args
.args
.into_iter()
.flat_map(|arg| {
if let FunctionArg::Unnamed(FunctionArgExpr::Expr(expr)) = arg
{
self.sql_expr_to_logical_expr(
expr,
&DFSchema::empty(),
planner_context,
)
} else {
plan_err!("Unsupported function argument type: {}", arg)
}
})
.collect::<Vec<_>>();
let provider = self
.context_provider
.get_table_function_source(&tbl_func_name, args)?;
let plan = LogicalPlanBuilder::scan(
TableReference::Bare {
table: format!("{tbl_func_name}()").into(),
},
provider,
None,
)?
.build()?;
(plan, alias)
} else {
// Normalize name and alias
let table_ref = self.object_name_to_table_reference(name)?;
let table_name = table_ref.to_string();
let cte = planner_context.get_cte(&table_name);
(
match (
cte,
self.context_provider.get_table_source(table_ref.clone()),
) {
(Some(cte_plan), _) => Ok(cte_plan.clone()),
(_, Ok(provider)) => LogicalPlanBuilder::scan(
table_ref.clone(),
provider,
None,
)?
.build(),
(None, Err(e)) => {
let e = e.with_diagnostic(Diagnostic::new_error(
format!("table '{table_ref}' not found"),
Span::try_from_sqlparser_span(relation_span),
));
Err(e)
}
}?,
alias,
)
}
}
TableFactor::Derived {
subquery, alias, ..
} => {
let logical_plan = self.query_to_plan(*subquery, planner_context)?;
(logical_plan, alias)
}
TableFactor::NestedJoin {
table_with_joins,
alias,
} => (
self.plan_table_with_joins(*table_with_joins, planner_context)?,
alias,
),
TableFactor::UNNEST {
alias,
array_exprs,
with_offset: false,
with_offset_alias: None,
with_ordinality,
} => {
if with_ordinality {
return not_impl_err!("UNNEST with ordinality is not supported yet");
}
// Unnest table factor has empty input
let schema = DFSchema::empty();
let input = LogicalPlanBuilder::empty(true).build()?;
// Unnest table factor can have multiple arguments.
// We treat each argument as a separate unnest expression.
let unnest_exprs = array_exprs
.into_iter()
.map(|sql_expr| {
let expr = self.sql_expr_to_logical_expr(
sql_expr,
&schema,
planner_context,
)?;
Self::check_unnest_arg(&expr, &schema)?;
Ok(Expr::Unnest(Unnest::new(expr)))
})
.collect::<Result<Vec<_>>>()?;
if unnest_exprs.is_empty() {
return plan_err!("UNNEST must have at least one argument");
}
let logical_plan = self.try_process_unnest(input, unnest_exprs)?;
(logical_plan, alias)
}
TableFactor::UNNEST { .. } => {
return not_impl_err!(
"UNNEST table factor with offset is not supported yet"
);
}
TableFactor::Function {
name, args, alias, ..
} => {
let tbl_func_ref = self.object_name_to_table_reference(name)?;
let schema = planner_context
.outer_query_schema()
.cloned()
.unwrap_or_else(DFSchema::empty);
let func_args = args
.into_iter()
.map(|arg| match arg {
FunctionArg::Unnamed(FunctionArgExpr::Expr(expr))
| FunctionArg::Named {
arg: FunctionArgExpr::Expr(expr),
..
} => {
self.sql_expr_to_logical_expr(expr, &schema, planner_context)
}
_ => plan_err!("Unsupported function argument: {arg:?}"),
})
.collect::<Result<Vec<Expr>>>()?;
let provider = self
.context_provider
.get_table_function_source(tbl_func_ref.table(), func_args)?;
let plan =
LogicalPlanBuilder::scan(tbl_func_ref.table(), provider, None)?
.build()?;
(plan, alias)
}
// @todo Support TableFactory::TableFunction?
_ => {
return not_impl_err!(
"Unsupported ast node {relation:?} in create_relation"
);
}
};
Ok(PlannedRelation::new(plan, alias))
}
pub(crate) fn create_relation_subquery(
&self,
subquery: TableFactor,
planner_context: &mut PlannerContext,
) -> Result<LogicalPlan> {
// At this point for a syntactically valid query the outer_from_schema is
// guaranteed to be set, so the `.unwrap()` call will never panic. This
// is the case because we only call this method for lateral table
// factors, and those can never be the first factor in a FROM list. This
// means we arrived here through the `for` loop in `plan_from_tables` or
// the `for` loop in `plan_table_with_joins`.
let old_from_schema = planner_context
.set_outer_from_schema(None)
.unwrap_or_else(|| Arc::new(DFSchema::empty()));
let new_query_schema = match planner_context.outer_query_schema() {
Some(old_query_schema) => {
let mut new_query_schema = old_from_schema.as_ref().clone();
new_query_schema.merge(old_query_schema);
Some(Arc::new(new_query_schema))
}
None => Some(Arc::clone(&old_from_schema)),
};
let old_query_schema = planner_context.set_outer_query_schema(new_query_schema);
let plan = self.create_relation(subquery, planner_context)?;
let outer_ref_columns = plan.all_out_ref_exprs();
planner_context.set_outer_query_schema(old_query_schema);
planner_context.set_outer_from_schema(Some(old_from_schema));
// We can omit the subquery wrapper if there are no columns
// referencing the outer scope.
if outer_ref_columns.is_empty() {
return Ok(plan);
}
match plan {
LogicalPlan::SubqueryAlias(SubqueryAlias { input, alias, .. }) => {
subquery_alias(
LogicalPlan::Subquery(Subquery {
subquery: input,
outer_ref_columns,
spans: Spans::new(),
}),
alias,
)
}
plan => Ok(LogicalPlan::Subquery(Subquery {
subquery: Arc::new(plan),
outer_ref_columns,
spans: Spans::new(),
})),
}
}
}
fn optimize_subquery_sort(plan: LogicalPlan) -> Result<Transformed<LogicalPlan>> {
// When initializing subqueries, we examine sort options since they might be unnecessary.
// They are only important if the subquery result is affected by the ORDER BY statement,
// which can happen when we have:
// 1. DISTINCT ON / ARRAY_AGG ... => Handled by an `Aggregate` and its requirements.
// 2. RANK / ROW_NUMBER ... => Handled by a `WindowAggr` and its requirements.
// 3. LIMIT => Handled by a `Sort`, so we need to search for it.
let mut has_limit = false;
plan.transform_down(|c| {
if let LogicalPlan::Limit(_) = c {
has_limit = true;
return Ok(Transformed::no(c));
}
match c {
LogicalPlan::Sort(s) => {
if !has_limit {
has_limit = false;
return Ok(Transformed::yes(s.input.as_ref().clone()));
}
Ok(Transformed::no(LogicalPlan::Sort(s)))
}
_ => Ok(Transformed::no(c)),
}
})
}