1use super::{
6 Unparser,
7 ast::{
8 BuilderError, DerivedRelationBuilder, QueryBuilder, RelationBuilder,
9 SelectBuilder, TableRelationBuilder, TableWithJoinsBuilder,
10 },
11 rewrite::{
12 TableAliasRewriter, inject_column_aliases_into_subquery, normalize_union_schema,
13 rewrite_plan_for_sort_on_non_projected_fields,
14 subquery_alias_inner_query_and_columns,
15 },
16 utils::{
17 find_agg_node_within_select, find_unnest_node_within_select,
18 find_window_nodes_within_select, try_transform_to_simple_table_scan_with_filters,
19 unproject_sort_expr, unproject_unnest_expr,
20 unproject_unnest_expr_as_flatten_value, unproject_window_exprs,
21 },
22};
23use crate::unparser::utils::{find_unnest_node_until_relation, unproject_agg_exprs};
24use crate::unparser::{
25 ast::FlattenRelationBuilder, ast::UnnestRelationBuilder, rewrite::rewrite_qualify,
26};
27use crate::unparser::{
28 extension_unparser::{UnparseToStatementResult, UnparseWithinStatementResult},
29 utils::filter_depends_on_input_alias,
30};
31use crate::utils::UNNEST_PLACEHOLDER;
32use datafusion_common::{
33 Column, DFSchema, DataFusionError, Result, ScalarValue, TableReference,
34 assert_or_internal_err, internal_datafusion_err, internal_err, not_impl_err,
35 tree_node::{Transformed, TransformedResult, TreeNode, TreeNodeRecursion},
36 utils::combine_limit,
37};
38use datafusion_expr::expr::{OUTER_REFERENCE_COLUMN_PREFIX, UNNEST_COLUMN_PREFIX};
39use datafusion_expr::{
40 Aggregate, AsOfJoin, BinaryExpr, Distinct, Expr, FetchType, JoinConstraint, JoinType,
41 LogicalPlan, LogicalPlanBuilder, Operator, Projection, SkipType, Sort, SortExpr,
42 TableScan, Unnest, UserDefinedLogicalNode, Window, expr::Alias,
43};
44use sqlparser::ast::{self, Ident, OrderByKind, SetExpr, TableAliasColumnDef};
45use std::{collections::HashSet, sync::Arc, vec};
46
47pub fn plan_to_sql(plan: &LogicalPlan) -> Result<ast::Statement> {
88 let unparser = Unparser::default();
89 unparser.plan_to_sql(plan)
90}
91
92struct UnparserAggScope<'a> {
105 agg: &'a Aggregate,
106 input_is_derived_projection: bool,
109}
110
111impl<'a> UnparserAggScope<'a> {
112 fn new(agg: &'a Aggregate) -> Self {
113 Self {
114 agg,
115 input_is_derived_projection: Unparser::contains_projection_before_relation(
116 agg.input.as_ref(),
117 ),
118 }
119 }
120
121 fn prepare(&self, expr: Expr, windows: Option<&[&Window]>) -> Result<Expr> {
125 self.normalize(unproject_agg_exprs(expr, self.agg, windows)?)
126 }
127
128 fn normalize(&self, expr: Expr) -> Result<Expr> {
132 if self.input_is_derived_projection {
133 Unparser::strip_column_qualifiers_for_schema(
134 expr,
135 self.agg.input.schema().as_ref(),
136 )
137 } else {
138 Ok(expr)
139 }
140 }
141
142 fn prepare_sort_expr(
145 &self,
146 sort_expr: SortExpr,
147 input: &LogicalPlan,
148 ) -> Result<SortExpr> {
149 let mut sort_expr = unproject_sort_expr(sort_expr, Some(self.agg), input)?;
150 sort_expr.expr = self.normalize(sort_expr.expr)?;
151 Ok(sort_expr)
152 }
153}
154
155#[derive(Clone, Copy)]
156struct DerivedInputScope<'a> {
157 alias: &'static str,
158 schema: &'a DFSchema,
159}
160
161impl Unparser<'_> {
162 pub fn plan_to_sql(&self, plan: &LogicalPlan) -> Result<ast::Statement> {
163 let mut plan = normalize_union_schema(plan)?;
164 if !self.dialect.supports_qualify() {
165 plan = rewrite_qualify(plan)?;
166 }
167
168 match plan {
169 LogicalPlan::Projection(_)
170 | LogicalPlan::Filter(_)
171 | LogicalPlan::Window(_)
172 | LogicalPlan::Aggregate(_)
173 | LogicalPlan::Sort(_)
174 | LogicalPlan::Join(_)
175 | LogicalPlan::AsOfJoin(_)
176 | LogicalPlan::Repartition(_)
177 | LogicalPlan::Union(_)
178 | LogicalPlan::TableScan(_)
179 | LogicalPlan::EmptyRelation(_)
180 | LogicalPlan::Subquery(_)
181 | LogicalPlan::SubqueryAlias(_)
182 | LogicalPlan::Limit(_)
183 | LogicalPlan::Statement(_)
184 | LogicalPlan::Values(_)
185 | LogicalPlan::Distinct(_) => self.select_to_sql_statement(&plan),
186 LogicalPlan::Dml(_) => self.dml_to_sql(&plan),
187 LogicalPlan::Extension(extension) => {
188 self.extension_to_statement(extension.node.as_ref())
189 }
190 LogicalPlan::Explain(_)
191 | LogicalPlan::Analyze(_)
192 | LogicalPlan::Ddl(_)
193 | LogicalPlan::Copy(_)
194 | LogicalPlan::Show(_)
195 | LogicalPlan::RecursiveQuery(_)
196 | LogicalPlan::Unnest(_) => not_impl_err!("Unsupported plan: {plan:?}"),
197 LogicalPlan::MaterializedCte(_) => {
198 not_impl_err!("Unparsing a MATERIALIZED CTE is not supported: {plan:?}")
199 }
200 }
201 }
202
203 fn extension_to_statement(
207 &self,
208 node: &dyn UserDefinedLogicalNode,
209 ) -> Result<ast::Statement> {
210 let mut statement = None;
211 for unparser in &self.extension_unparsers {
212 match unparser.unparse_to_statement(node, self)? {
213 UnparseToStatementResult::Modified(stmt) => {
214 statement = Some(stmt);
215 break;
216 }
217 UnparseToStatementResult::Unmodified => {}
218 }
219 }
220 if let Some(statement) = statement {
221 Ok(statement)
222 } else {
223 not_impl_err!("Unsupported extension node: {node:?}")
224 }
225 }
226
227 fn extension_to_sql(
231 &self,
232 node: &dyn UserDefinedLogicalNode,
233 query: &mut Option<&mut QueryBuilder>,
234 select: &mut Option<&mut SelectBuilder>,
235 relation: &mut Option<&mut RelationBuilder>,
236 ) -> Result<()> {
237 for unparser in &self.extension_unparsers {
238 match unparser.unparse(node, self, query, select, relation)? {
239 UnparseWithinStatementResult::Modified => return Ok(()),
240 UnparseWithinStatementResult::Unmodified => {}
241 }
242 }
243 not_impl_err!("Unsupported extension node: {node:?}")
244 }
245
246 fn select_to_sql_statement(&self, plan: &LogicalPlan) -> Result<ast::Statement> {
247 let mut query_builder = Some(QueryBuilder::default());
248
249 let body = self.select_to_sql_expr(plan, &mut query_builder)?;
250
251 let query = query_builder.unwrap().body(Box::new(body)).build()?;
252
253 Ok(ast::Statement::Query(Box::new(query)))
254 }
255
256 fn select_to_sql_expr(
257 &self,
258 plan: &LogicalPlan,
259 query: &mut Option<QueryBuilder>,
260 ) -> Result<SetExpr> {
261 let mut select_builder = SelectBuilder::default();
262 select_builder.push_from(TableWithJoinsBuilder::default());
263 let mut relation_builder = RelationBuilder::default();
264 self.select_to_sql_recursively(
265 plan,
266 query,
267 &mut select_builder,
268 &mut relation_builder,
269 )?;
270
271 if let Some(body) = query.as_mut().and_then(|q| q.take_body()) {
273 return Ok(*body);
274 }
275
276 if !select_builder.already_projected() {
279 select_builder.projection(vec![ast::SelectItem::Wildcard(
280 ast::WildcardAdditionalOptions::default(),
281 )]);
282 }
283
284 let mut twj = select_builder.pop_from().unwrap();
285 twj.relation(relation_builder);
286 select_builder.push_from(twj);
287
288 Ok(SetExpr::Select(Box::new(select_builder.build()?)))
289 }
290
291 fn reconstruct_select_statement(
308 &self,
309 plan: &LogicalPlan,
310 p: &Projection,
311 select: &mut SelectBuilder,
312 fully_absorbed: bool,
313 ) -> Result<bool> {
314 let mut exprs = p.expr.clone();
315
316 let flatten_alias = select.current_flatten_alias();
318 if let Some(unnest) = find_unnest_node_within_select(plan) {
319 if let Some(ref alias) = flatten_alias {
320 exprs = exprs
321 .into_iter()
322 .map(|e| unproject_unnest_expr_as_flatten_value(e, unnest, alias))
323 .collect::<Result<Vec<_>>>()?;
324 } else {
325 exprs = exprs
326 .into_iter()
327 .map(|e| unproject_unnest_expr(e, unnest))
328 .collect::<Result<Vec<_>>>()?;
329 }
330 }
331
332 if !select.flatten_table_aliases_empty() {
336 exprs = exprs
337 .into_iter()
338 .map(|e| {
339 e.transform(|expr| {
340 if let Expr::Column(ref col) = expr
341 && let Some(ref relation) = col.relation
342 && select.is_flatten_table_alias(relation.table())
343 {
344 return Ok(Transformed::yes(Expr::Column(Column::new(
345 Some(relation.clone()),
346 "VALUE",
347 ))));
348 }
349 Ok(Transformed::no(expr))
350 })
351 .map(|t| t.data)
352 })
353 .collect::<Result<Vec<_>>>()?;
354 }
355
356 let agg = if fully_absorbed {
364 find_agg_node_within_select(plan, true)
365 } else {
366 None
367 };
368 let window = if fully_absorbed {
369 find_window_nodes_within_select(plan, None, true)
370 } else {
371 None
372 };
373 match (agg, window) {
374 (Some(agg), window) => {
375 let window_option = window.as_deref();
376 let unparser_agg_scope = UnparserAggScope::new(agg);
377 let items = exprs
378 .into_iter()
379 .map(|proj_expr| {
380 let unproj =
381 unparser_agg_scope.prepare(proj_expr, window_option)?;
382 self.select_item_to_sql(&unproj)
383 })
384 .collect::<Result<Vec<_>>>()?;
385
386 select.projection(items);
387 select.group_by(ast::GroupByExpr::Expressions(
388 agg.group_expr
389 .iter()
390 .cloned()
391 .map(|expr| {
392 self.expr_to_sql(&unparser_agg_scope.normalize(expr)?)
393 })
394 .collect::<Result<Vec<_>>>()?,
395 vec![],
396 ));
397 Ok(true)
398 }
399 (None, Some(window)) => {
400 let items = exprs
401 .into_iter()
402 .map(|proj_expr| {
403 let unproj = unproject_window_exprs(proj_expr, &window)?;
404 self.select_item_to_sql(&unproj)
405 })
406 .collect::<Result<Vec<_>>>()?;
407
408 select.projection(items);
409 Ok(false)
410 }
411 _ => {
412 let items = exprs
413 .iter()
414 .map(|e| {
415 if let Some(ref alias) = flatten_alias
420 && Self::has_internal_unnest_alias(e)
421 {
422 return Ok(self.build_flatten_value_select_item(alias, None));
423 }
424 self.select_item_to_sql(e)
425 })
426 .collect::<Result<Vec<_>>>()?;
427 select.projection(items);
428 Ok(false)
429 }
430 }
431 }
432
433 fn contains_projection_before_relation(plan: &LogicalPlan) -> bool {
434 match plan {
435 LogicalPlan::Projection(_) => true,
436 LogicalPlan::TableScan(_)
437 | LogicalPlan::Subquery(_)
438 | LogicalPlan::SubqueryAlias(_)
439 | LogicalPlan::Join(_)
440 | LogicalPlan::EmptyRelation(_)
441 | LogicalPlan::Values(_) => false,
442 _ => {
443 let inputs = plan.inputs();
444 matches!(
445 inputs.as_slice(),
446 [input] if Self::contains_projection_before_relation(input)
447 )
448 }
449 }
450 }
451
452 fn derived_input_alias(plan: &LogicalPlan) -> Option<&'static str> {
455 match plan {
456 LogicalPlan::Projection(_) => Some("derived_projection"),
457 LogicalPlan::Limit(_) => Some("derived_limit"),
458 LogicalPlan::Sort(_) => Some("derived_sort"),
459 LogicalPlan::Distinct(_) => Some("derived_distinct"),
460 LogicalPlan::Filter(filter) => {
461 Self::derived_input_alias(filter.input.as_ref())
462 }
463 LogicalPlan::Repartition(repartition) => {
464 Self::derived_input_alias(repartition.input.as_ref())
465 }
466 _ => None,
467 }
468 }
469
470 fn derived_input_scope<'a>(
471 plan: &'a LogicalPlan,
472 select: &SelectBuilder,
473 ) -> Option<DerivedInputScope<'a>> {
474 if select.inside_subquery_alias() {
475 return None;
476 }
477
478 if select.already_projected()
479 && find_unnest_node_within_select(plan).is_none()
480 && let Some(alias) = Self::derived_input_alias(plan)
481 {
482 return Some(DerivedInputScope {
483 alias,
484 schema: plan.schema().as_ref(),
485 });
486 }
487
488 match plan {
489 LogicalPlan::Projection(projection) => {
490 let alias = Self::derived_input_alias(projection.input.as_ref())?;
491 let qualified_projection = projection.expr.iter().any(|expr| {
492 expr.column_refs()
493 .iter()
494 .any(|column| column.relation.is_some())
495 });
496 let mut input_names =
497 HashSet::with_capacity(projection.input.schema().fields().len());
498 let unique_input_names = projection
499 .input
500 .schema()
501 .fields()
502 .iter()
503 .all(|field| input_names.insert(field.name()));
504
505 (qualified_projection
506 && unique_input_names
507 && find_unnest_node_within_select(plan).is_none())
508 .then_some(DerivedInputScope {
509 alias,
510 schema: projection.input.schema().as_ref(),
511 })
512 }
513 LogicalPlan::Filter(filter) if filter_depends_on_input_alias(filter) => {
516 Some(DerivedInputScope {
517 alias: "derived_projection",
518 schema: filter.input.schema().as_ref(),
519 })
520 }
521 LogicalPlan::Filter(filter) => {
522 Self::derived_input_scope(filter.input.as_ref(), select)
523 }
524 LogicalPlan::Limit(limit) => {
525 Self::derived_input_scope(limit.input.as_ref(), select)
526 }
527 LogicalPlan::Sort(sort) => {
528 Self::derived_input_scope(sort.input.as_ref(), select)
529 }
530 LogicalPlan::Repartition(repartition) => {
531 Self::derived_input_scope(repartition.input.as_ref(), select)
532 }
533 _ => None,
534 }
535 }
536
537 fn rebase_derived_input_expr(
538 &self,
539 expr: Expr,
540 scope: Option<DerivedInputScope<'_>>,
541 ) -> Result<Expr> {
542 let Some(scope) = scope else {
543 return Ok(expr);
544 };
545 if self.dialect.requires_derived_table_alias() {
546 let mut alias_rewriter = TableAliasRewriter {
547 table_schema: scope.schema,
548 alias_name: TableReference::bare(scope.alias),
549 rewrite_unqualified: false,
550 };
551 expr.rewrite(&mut alias_rewriter).data()
552 } else {
553 Self::strip_column_qualifiers_for_schema(expr, scope.schema)
554 }
555 }
556
557 fn contains_aggregate_before_relation(plan: &LogicalPlan) -> bool {
558 match plan {
559 LogicalPlan::Aggregate(_) => true,
560 LogicalPlan::TableScan(_)
561 | LogicalPlan::Subquery(_)
562 | LogicalPlan::SubqueryAlias(_)
563 | LogicalPlan::Join(_)
564 | LogicalPlan::EmptyRelation(_)
565 | LogicalPlan::Values(_) => false,
566 _ => {
567 let inputs = plan.inputs();
568 matches!(
569 inputs.as_slice(),
570 [input] if Self::contains_aggregate_before_relation(input)
571 )
572 }
573 }
574 }
575
576 fn unproject_sort_expr_in_scope(
579 sort_expr: SortExpr,
580 agg: Option<&Aggregate>,
581 input: &LogicalPlan,
582 ) -> Result<SortExpr> {
583 match agg {
584 Some(agg) => UnparserAggScope::new(agg).prepare_sort_expr(sort_expr, input),
585 None => unproject_sort_expr(sort_expr, None, input),
586 }
587 }
588
589 fn derive(
590 &self,
591 plan: &LogicalPlan,
592 relation: &mut RelationBuilder,
593 alias: Option<ast::TableAlias>,
594 lateral: bool,
595 ) -> Result<()> {
596 let preserve_names = matches!(plan, LogicalPlan::Projection(_))
597 && alias.as_ref().is_none_or(|alias| alias.columns.is_empty());
598 let mut derived_builder = DerivedRelationBuilder::default();
599 if preserve_names {
600 derived_builder.projection_names(
601 plan.schema()
602 .fields()
603 .iter()
604 .map(|field| self.column_alias_to_sql(field.name()))
605 .collect::<Result<Vec<_>>>()?,
606 );
607 }
608 derived_builder.lateral(lateral).alias(alias).subquery({
609 let inner_statement = self.plan_to_sql(plan)?;
610 if let ast::Statement::Query(inner_query) = inner_statement {
611 inner_query
612 } else {
613 return internal_err!(
614 "Subquery must be a Query, but found {inner_statement:?}"
615 );
616 }
617 });
618 relation.derived(derived_builder);
619
620 Ok(())
621 }
622
623 fn derive_with_dialect_alias(
624 &self,
625 alias: &str,
626 plan: &LogicalPlan,
627 relation: &mut RelationBuilder,
628 lateral: bool,
629 columns: Vec<Ident>,
630 ) -> Result<()> {
631 if self.dialect.requires_derived_table_alias() || !columns.is_empty() {
632 self.derive(
633 plan,
634 relation,
635 Some(self.new_table_alias(alias.to_string(), columns)),
636 lateral,
637 )
638 } else {
639 self.derive(plan, relation, None, lateral)
640 }
641 }
642
643 fn try_projection_unnest_as_lateral_flatten(
659 &self,
660 plan: &LogicalPlan,
661 p: &Projection,
662 query: &mut Option<QueryBuilder>,
663 select: &mut SelectBuilder,
664 relation: &mut RelationBuilder,
665 unnest_input_type: Option<&UnnestInputType>,
666 ) -> Result<bool> {
667 if self.dialect.unnest_as_lateral_flatten() && unnest_input_type.is_some() {
672 let flatten_alias_name = if !select.already_projected() {
673 select.next_flatten_alias()
674 } else {
675 select
676 .current_flatten_alias()
677 .unwrap_or_else(|| select.next_flatten_alias())
678 };
679
680 if let Some((unnest, unnest_plan)) = self.peel_to_unnest_with_modifiers(
681 p.input.as_ref(),
682 query,
683 Some(&flatten_alias_name),
684 )? && let Some(mut flatten) =
685 self.try_unnest_to_lateral_flatten_sql(unnest)?
686 {
687 let inner_projection = Self::peel_to_inner_projection(
688 unnest.input.as_ref(),
689 )
690 .ok_or_else(|| {
691 internal_datafusion_err!(
692 "Unnest input is not a Projection: {:?}",
693 unnest.input
694 )
695 })?;
696
697 flatten.alias(Some(ast::TableAlias {
698 name: Ident::with_quote('"', &flatten_alias_name),
699 columns: vec![],
700 explicit: true,
701 at: None,
702 }));
703
704 if !select.already_projected() {
705 self.reconstruct_select_statement(plan, p, select, true)?;
706 }
707
708 if matches!(
709 inner_projection.input.as_ref(),
710 LogicalPlan::EmptyRelation(_)
711 ) {
712 relation.flatten(flatten);
713 self.select_to_sql_recursively(unnest_plan, query, select, relation)?;
714 return Ok(true);
715 }
716
717 self.select_to_sql_recursively(unnest_plan, query, select, relation)?;
718
719 let flatten_factor = flatten.build().map_err(|e| {
720 internal_datafusion_err!("Failed to build FLATTEN: {e}")
721 })?;
722 let cross_join = ast::Join {
723 relation: flatten_factor,
724 global: false,
725 join_operator: ast::JoinOperator::CrossJoin(
726 ast::JoinConstraint::None,
727 ),
728 };
729 if let Some(mut from) = select.pop_from() {
730 from.push_join(cross_join);
731 select.push_from(from);
732 } else {
733 let mut twj = TableWithJoinsBuilder::default();
734 twj.push_join(cross_join);
735 select.push_from(twj);
736 }
737
738 return Ok(true);
739 }
740 }
741
742 Ok(false)
743 }
744
745 fn project_window_output(
746 &self,
747 window_expr: &[Expr],
748 select: &mut SelectBuilder,
749 agg: Option<&Aggregate>,
750 ) -> Result<()> {
751 let mut items = if select.already_projected() {
752 select.pop_projections()
753 } else {
754 vec![ast::SelectItem::Wildcard(
755 ast::WildcardAdditionalOptions::default(),
756 )]
757 };
758
759 items.extend(
760 window_expr
761 .iter()
762 .map(|expr| {
763 let expr = if let Some(agg) = agg {
767 unproject_agg_exprs(expr.clone(), agg, None)?
768 } else {
769 expr.clone()
770 };
771 self.select_item_to_sql(&expr)
772 })
773 .collect::<Result<Vec<_>>>()?,
774 );
775 select.projection(items);
776
777 Ok(())
778 }
779
780 fn window_input_requires_derived_subquery(plan: &LogicalPlan) -> bool {
781 matches!(
785 plan,
786 LogicalPlan::Projection(_)
787 | LogicalPlan::Distinct(_)
788 | LogicalPlan::Limit(_)
789 | LogicalPlan::Sort(_)
790 | LogicalPlan::Union(_)
791 )
792 }
793
794 fn window_to_sql_with_derived_input(
795 &self,
796 window: &Window,
797 select: &mut SelectBuilder,
798 relation: &mut RelationBuilder,
799 ) -> Result<()> {
800 let input_alias = "derived_window_input";
801 self.derive(
802 window.input.as_ref(),
803 relation,
804 Some(self.new_table_alias(input_alias.to_string(), vec![])),
805 false,
806 )?;
807
808 let input_schema = window.input.schema();
809 let mut alias_rewriter = TableAliasRewriter {
810 table_schema: input_schema.as_ref(),
811 alias_name: TableReference::bare(input_alias),
812 rewrite_unqualified: true,
813 };
814 let window_expr = window
815 .window_expr
816 .iter()
817 .map(|expr| expr.clone().rewrite(&mut alias_rewriter).data())
818 .collect::<Result<Vec<_>>>()?;
819
820 self.project_window_output(&window_expr, select, None)
821 }
822
823 fn extract_join_input_table_scan_filters(
824 plan: &Arc<LogicalPlan>,
825 table_scan_filters: &mut Vec<Expr>,
826 ) -> Result<Arc<LogicalPlan>> {
827 match try_transform_to_simple_table_scan_with_filters(plan)? {
828 Some((plan, filters)) => {
829 table_scan_filters.extend(filters);
830 Ok(Arc::new(plan))
831 }
832 None => Ok(Arc::clone(plan)),
833 }
834 }
835
836 #[cfg_attr(feature = "recursive_protection", recursive::recursive)]
837 fn select_to_sql_recursively(
838 &self,
839 plan: &LogicalPlan,
840 query: &mut Option<QueryBuilder>,
841 select: &mut SelectBuilder,
842 relation: &mut RelationBuilder,
843 ) -> Result<()> {
844 match plan {
845 LogicalPlan::TableScan(scan) => {
846 if let Some(unparsed_table_scan) = self.unparse_table_scan_pushdown(
847 plan,
848 None,
849 select.already_projected(),
850 )? {
851 return self.select_to_sql_recursively(
852 &unparsed_table_scan,
853 query,
854 select,
855 relation,
856 );
857 }
858 let mut builder = TableRelationBuilder::default();
859 let mut table_parts = vec![];
860 if let Some(catalog_name) = scan.table_name.catalog() {
861 table_parts
862 .push(self.new_ident_quoted_if_needs(catalog_name.to_string()));
863 }
864 if let Some(schema_name) = scan.table_name.schema() {
865 table_parts
866 .push(self.new_ident_quoted_if_needs(schema_name.to_string()));
867 }
868 table_parts.push(
869 self.new_ident_quoted_if_needs(scan.table_name.table().to_string()),
870 );
871 builder.name(ast::ObjectName::from(table_parts));
872 relation.table(builder);
873
874 Ok(())
875 }
876 LogicalPlan::Projection(p) => {
877 if let Some(new_plan) = rewrite_plan_for_sort_on_non_projected_fields(p) {
878 return self
879 .select_to_sql_recursively(&new_plan, query, select, relation);
880 }
881
882 let unnest_input_type: Option<UnnestInputType> =
887 p.expr.iter().find_map(Self::find_unnest_placeholder);
888
889 if self.dialect.unnest_as_table_factor()
895 && p.expr.len() == 1
896 && Self::is_bare_unnest_placeholder(&p.expr[0])
897 && let Some((unnest, unnest_plan)) =
898 self.peel_to_unnest_with_modifiers(p.input.as_ref(), query, None)?
899 && let Some(unnest_relation) =
900 self.try_unnest_to_table_factor_sql(unnest)?
901 {
902 relation.unnest(unnest_relation);
903 return self.select_to_sql_recursively(
904 unnest_plan,
905 query,
906 select,
907 relation,
908 );
909 }
910
911 if self.try_projection_unnest_as_lateral_flatten(
912 plan,
913 p,
914 query,
915 select,
916 relation,
917 unnest_input_type.as_ref(),
918 )? {
919 return Ok(());
920 }
921
922 let columns = if unnest_input_type.is_some() {
925 p.expr
926 .iter()
927 .map(|e| {
928 self.new_ident_quoted_if_needs(e.schema_name().to_string())
929 })
930 .collect()
931 } else {
932 vec![]
933 };
934 if select.already_projected() {
936 return self.derive_with_dialect_alias(
937 "derived_projection",
938 plan,
939 relation,
940 unnest_input_type.is_some_and(|t| {
941 matches!(t, UnnestInputType::OuterReference)
942 }),
943 columns,
944 );
945 }
946
947 if let Some(scope) = Self::derived_input_scope(plan, select) {
948 let requires_alias = self.dialect.requires_derived_table_alias();
952 let alias = requires_alias
953 .then(|| self.new_table_alias(scope.alias.to_string(), vec![]));
954 self.derive(p.input.as_ref(), relation, alias, false)?;
955
956 let items = p
957 .expr
958 .iter()
959 .cloned()
960 .map(|expr| self.rebase_derived_input_expr(expr, Some(scope)))
961 .map(|expr| self.select_item_to_sql(&expr?))
962 .collect::<Result<Vec<_>>>()?;
963 select.projection(items);
964 return Ok(());
965 }
966 if self.dialect.unnest_as_lateral_flatten()
972 && p.expr.iter().any(Self::has_internal_unnest_alias)
973 {
974 select.next_flatten_alias();
975 }
976 if self.dialect.unnest_as_lateral_flatten() {
982 Self::collect_flatten_aliases(p.input.as_ref(), select);
983 }
984 let mut cur = p.input.as_ref();
1010 let mut absorbed_sort: Option<&Sort> = None;
1011 let mut combined_skip: usize = 0;
1012 let mut combined_fetch: Option<usize> = None;
1013 let mut have_combined_limit = false;
1014 let mut have_direct_limit = false;
1015 let mut have_order_by = false;
1016 loop {
1017 match cur {
1018 LogicalPlan::Limit(limit) => {
1019 if have_order_by {
1020 break;
1024 }
1025 let skip_lit = limit.get_skip_type()?;
1026 let fetch_lit = limit.get_fetch_type()?;
1027 match (skip_lit, fetch_lit) {
1028 (SkipType::Literal(s), FetchType::Literal(f)) => {
1029 if have_direct_limit {
1030 break;
1031 }
1032 if have_combined_limit {
1033 let (cs, cf) = combine_limit(
1037 combined_skip,
1038 combined_fetch,
1039 s,
1040 f,
1041 );
1042 combined_skip = cs;
1043 combined_fetch = cf;
1044 } else {
1045 combined_skip = s;
1046 combined_fetch = f;
1047 have_combined_limit = true;
1048 }
1049 }
1050 _ => {
1051 if have_combined_limit || have_direct_limit {
1052 break;
1056 }
1057 let Some(query_ref) = query.as_mut() else {
1058 return internal_err!(
1059 "Limit operator only valid in a statement context."
1060 );
1061 };
1062 if let Some(fetch) = &limit.fetch {
1063 query_ref.limit(Some(self.expr_to_sql(fetch)?));
1064 }
1065 if let Some(skip) = &limit.skip {
1066 query_ref.offset(Some(ast::Offset {
1067 rows: ast::OffsetRows::None,
1068 value: self.expr_to_sql(skip)?,
1069 }));
1070 }
1071 have_direct_limit = true;
1072 }
1073 }
1074 cur = limit.input.as_ref();
1075 }
1076 LogicalPlan::Sort(sort) if sort.fetch.is_some() => {
1077 let fetch = sort.fetch.expect("guarded above");
1083 if have_order_by {
1084 break;
1087 }
1088 if have_direct_limit {
1089 break;
1093 }
1094 if have_combined_limit {
1095 let (cs, cf) = combine_limit(
1096 combined_skip,
1097 combined_fetch,
1098 0,
1099 Some(fetch),
1100 );
1101 combined_skip = cs;
1102 combined_fetch = cf;
1103 } else {
1104 combined_skip = 0;
1105 combined_fetch = Some(fetch);
1106 have_combined_limit = true;
1107 }
1108 absorbed_sort = Some(sort);
1111 have_order_by = true;
1112 cur = sort.input.as_ref();
1113 }
1114 LogicalPlan::Sort(sort) => {
1115 if have_order_by {
1117 cur = sort.input.as_ref();
1122 continue;
1123 }
1124 absorbed_sort = Some(sort);
1125 have_order_by = true;
1126 cur = sort.input.as_ref();
1127 }
1128 _ => break,
1129 }
1130 }
1131
1132 let fully_absorbed =
1138 !matches!(cur, LogicalPlan::Limit(_) | LogicalPlan::Sort(_));
1139 let found_agg =
1140 self.reconstruct_select_statement(plan, p, select, fully_absorbed)?;
1141
1142 let agg_below =
1149 !fully_absorbed && find_agg_node_within_select(plan, true).is_some();
1150 if !(found_agg || agg_below) {
1151 return self.select_to_sql_recursively(
1152 p.input.as_ref(),
1153 query,
1154 select,
1155 relation,
1156 );
1157 }
1158
1159 if let Some(sort) = absorbed_sort {
1160 let Some(query_ref) = query.as_mut() else {
1161 return internal_err!(
1162 "Sort operator only valid in a statement context."
1163 );
1164 };
1165 let sort_exprs: Vec<SortExpr> = if fully_absorbed {
1166 let agg =
1167 find_agg_node_within_select(plan, select.already_projected());
1168 sort.expr
1169 .iter()
1170 .map(|sort_expr| {
1171 Self::unproject_sort_expr_in_scope(
1172 sort_expr.clone(),
1173 agg,
1174 sort.input.as_ref(),
1175 )
1176 })
1177 .collect::<Result<Vec<_>>>()?
1178 } else {
1179 sort.expr.clone()
1180 };
1181 query_ref.order_by(self.sorts_to_sql(&sort_exprs)?);
1182 }
1183 if have_combined_limit {
1184 let Some(query_ref) = query.as_mut() else {
1185 return internal_err!(
1186 "Limit operator only valid in a statement context."
1187 );
1188 };
1189 if let Some(fetch) = combined_fetch {
1190 query_ref.limit(Some(ast::Expr::value(ast::Value::Number(
1191 fetch.to_string(),
1192 false,
1193 ))));
1194 }
1195 if combined_skip > 0 {
1196 query_ref.offset(Some(ast::Offset {
1197 rows: ast::OffsetRows::None,
1198 value: ast::Expr::value(ast::Value::Number(
1199 combined_skip.to_string(),
1200 false,
1201 )),
1202 }));
1203 }
1204 }
1205
1206 self.select_to_sql_recursively(cur, query, select, relation)
1207 }
1208 LogicalPlan::Filter(filter) => {
1209 let derived_input_scope = Self::derived_input_scope(plan, select);
1210 let window = find_window_nodes_within_select(
1211 plan,
1212 None,
1213 select.already_projected(),
1214 );
1215 let agg = find_agg_node_within_select(plan, select.already_projected());
1216
1217 if let (Some(window), true) =
1218 (window.as_deref(), self.dialect.supports_qualify())
1219 {
1220 let mut unprojected =
1221 unproject_window_exprs(filter.predicate.clone(), window)?;
1222 if let Some(agg) = agg {
1223 unprojected =
1224 UnparserAggScope::new(agg).prepare(unprojected, None)?;
1225 }
1226 unprojected =
1227 self.rebase_derived_input_expr(unprojected, derived_input_scope)?;
1228 let filter_expr = self.expr_to_sql(&unprojected)?;
1229 select.qualify(Some(filter_expr));
1230 } else if let Some(agg) = agg {
1231 let mut unprojected = UnparserAggScope::new(agg)
1232 .prepare(filter.predicate.clone(), None)?;
1233 unprojected =
1234 self.rebase_derived_input_expr(unprojected, derived_input_scope)?;
1235 let filter_expr = self.expr_to_sql(&unprojected)?;
1236 select.having(Some(filter_expr));
1237 } else {
1238 let predicate = self.rebase_derived_input_expr(
1239 filter.predicate.clone(),
1240 derived_input_scope,
1241 )?;
1242 let filter_expr = self.expr_to_sql(&predicate)?;
1243 select.selection(Some(filter_expr));
1244 }
1245
1246 if filter_depends_on_input_alias(filter) {
1249 return self.derive_with_dialect_alias(
1250 "derived_projection",
1251 &filter.input,
1252 relation,
1253 false,
1254 vec![],
1255 );
1256 }
1257
1258 self.select_to_sql_recursively(
1259 filter.input.as_ref(),
1260 query,
1261 select,
1262 relation,
1263 )
1264 }
1265 LogicalPlan::Limit(limit) => {
1266 if select.already_projected() {
1268 return self.derive_with_dialect_alias(
1269 "derived_limit",
1270 plan,
1271 relation,
1272 false,
1273 vec![],
1274 );
1275 }
1276 if let Some(fetch) = &limit.fetch {
1277 let Some(query) = query.as_mut() else {
1278 return internal_err!(
1279 "Limit operator only valid in a statement context."
1280 );
1281 };
1282 query.limit(Some(self.expr_to_sql(fetch)?));
1283 }
1284
1285 if let Some(skip) = &limit.skip {
1286 let Some(query) = query.as_mut() else {
1287 return internal_err!(
1288 "Offset operator only valid in a statement context."
1289 );
1290 };
1291
1292 query.offset(Some(ast::Offset {
1293 rows: ast::OffsetRows::None,
1294 value: self.expr_to_sql(skip)?,
1295 }));
1296 }
1297
1298 self.select_to_sql_recursively(
1299 limit.input.as_ref(),
1300 query,
1301 select,
1302 relation,
1303 )
1304 }
1305 LogicalPlan::Sort(sort) => {
1306 if select.already_projected() {
1308 return self.derive_with_dialect_alias(
1309 "derived_sort",
1310 plan,
1311 relation,
1312 false,
1313 vec![],
1314 );
1315 }
1316
1317 let Some(query_ref) = query else {
1318 return internal_err!(
1319 "Sort operator only valid in a statement context."
1320 );
1321 };
1322
1323 if let Some(fetch) = sort.fetch {
1324 query_ref.limit(Some(ast::Expr::value(ast::Value::Number(
1325 fetch.to_string(),
1326 false,
1327 ))));
1328 }
1329
1330 let derived_input_scope = Self::derived_input_scope(plan, select);
1331 let agg = find_agg_node_within_select(plan, select.already_projected());
1332 let sort_exprs: Vec<SortExpr> = sort
1334 .expr
1335 .iter()
1336 .map(|sort_expr| {
1337 let sort_expr = Self::unproject_sort_expr_in_scope(
1338 sort_expr.clone(),
1339 agg,
1340 sort.input.as_ref(),
1341 )?;
1342 Ok(SortExpr {
1343 expr: self.rebase_derived_input_expr(
1344 sort_expr.expr,
1345 derived_input_scope,
1346 )?,
1347 ..sort_expr
1348 })
1349 })
1350 .collect::<Result<Vec<_>>>()?;
1351
1352 query_ref.order_by(self.sorts_to_sql(&sort_exprs)?);
1353
1354 self.select_to_sql_recursively(
1355 sort.input.as_ref(),
1356 query,
1357 select,
1358 relation,
1359 )
1360 }
1361 LogicalPlan::Aggregate(agg) => {
1362 if !select.already_projected() {
1364 let unparser_agg_scope = UnparserAggScope::new(agg);
1365 let exprs: Vec<_> = agg
1368 .aggr_expr
1369 .iter()
1370 .chain(agg.group_expr.iter())
1371 .cloned()
1372 .map(|expr| {
1373 self.select_item_to_sql(&unparser_agg_scope.normalize(expr)?)
1374 })
1375 .collect::<Result<Vec<_>>>()?;
1376 select.projection(exprs);
1377
1378 select.group_by(ast::GroupByExpr::Expressions(
1379 agg.group_expr
1380 .iter()
1381 .cloned()
1382 .map(|expr| {
1383 self.expr_to_sql(&unparser_agg_scope.normalize(expr)?)
1384 })
1385 .collect::<Result<Vec<_>>>()?,
1386 vec![],
1387 ));
1388 } else if Self::contains_aggregate_before_relation(agg.input.as_ref()) {
1389 return self.derive_with_dialect_alias(
1390 "derived_aggregate",
1391 agg.input.as_ref(),
1392 relation,
1393 false,
1394 vec![],
1395 );
1396 }
1397
1398 self.select_to_sql_recursively(
1399 agg.input.as_ref(),
1400 query,
1401 select,
1402 relation,
1403 )
1404 }
1405 LogicalPlan::Distinct(distinct) => {
1406 if select.already_projected() {
1408 return self.derive_with_dialect_alias(
1409 "derived_distinct",
1410 plan,
1411 relation,
1412 false,
1413 vec![],
1414 );
1415 }
1416
1417 if let Distinct::All(input) = distinct
1420 && matches!(input.as_ref(), LogicalPlan::Union(_))
1421 && let Some(query_mut) = query.as_mut()
1422 {
1423 query_mut.distinct_union();
1424 return self.select_to_sql_recursively(
1425 input.as_ref(),
1426 query,
1427 select,
1428 relation,
1429 );
1430 }
1431
1432 let (select_distinct, input) = match distinct {
1433 Distinct::All(input) => (ast::Distinct::Distinct, input.as_ref()),
1434 Distinct::On(on) => {
1435 let exprs = on
1436 .on_expr
1437 .iter()
1438 .map(|e| self.expr_to_sql(e))
1439 .collect::<Result<Vec<_>>>()?;
1440 let items = on
1441 .select_expr
1442 .iter()
1443 .map(|e| self.select_item_to_sql(e))
1444 .collect::<Result<Vec<_>>>()?;
1445 if let Some(sort_expr) = &on.sort_expr {
1446 if let Some(query_ref) = query {
1447 query_ref.order_by(self.sorts_to_sql(sort_expr)?);
1448 } else {
1449 return internal_err!(
1450 "Sort operator only valid in a statement context."
1451 );
1452 }
1453 }
1454 select.projection(items);
1455 (ast::Distinct::On(exprs), on.input.as_ref())
1456 }
1457 };
1458 select.distinct(Some(select_distinct));
1459 self.select_to_sql_recursively(input, query, select, relation)
1460 }
1461 LogicalPlan::Join(join) => {
1462 let mut table_scan_filters = vec![];
1463 let (left_plan, right_plan) = match join.join_type {
1464 JoinType::RightSemi | JoinType::RightAnti => {
1465 (&join.right, &join.left)
1466 }
1467 _ => (&join.left, &join.right),
1468 };
1469 let already_projected = select.already_projected();
1473
1474 let left_plan = Self::extract_join_input_table_scan_filters(
1475 left_plan,
1476 &mut table_scan_filters,
1477 )?;
1478 let left_plan = if already_projected {
1479 Self::unwrap_qualified_passthrough_join_projection(left_plan)
1480 } else {
1481 left_plan
1482 };
1483
1484 self.select_to_sql_recursively(
1485 left_plan.as_ref(),
1486 query,
1487 select,
1488 relation,
1489 )?;
1490
1491 let left_projection: Option<Vec<ast::SelectItem>> = if !already_projected
1492 {
1493 Some(select.pop_projections())
1494 } else {
1495 None
1496 };
1497
1498 let right_plan = Self::extract_join_input_table_scan_filters(
1499 right_plan,
1500 &mut table_scan_filters,
1501 )?;
1502
1503 let mut right_relation = RelationBuilder::default();
1504 if already_projected
1505 && let Some(nested_relation) =
1506 self.join_input_to_nested_relation(right_plan.as_ref(), query)?
1507 {
1508 right_relation = nested_relation;
1509 } else {
1510 self.select_to_sql_recursively(
1511 right_plan.as_ref(),
1512 query,
1513 select,
1514 &mut right_relation,
1515 )?;
1516 }
1517
1518 let (join_filters, where_filters) = Self::split_join_on_and_where_filters(
1519 join.join_type,
1520 join.filter.as_ref(),
1521 table_scan_filters,
1522 );
1523 for filter in where_filters {
1524 let filter_expr = self.expr_to_sql(&filter)?;
1525 select.selection(Some(filter_expr));
1526 }
1527
1528 let join_constraint = self.join_constraint_to_sql(
1529 join.join_constraint,
1530 &join.on,
1531 join_filters.as_ref(),
1532 )?;
1533
1534 let right_projection: Option<Vec<ast::SelectItem>> = if !already_projected
1535 {
1536 Some(select.pop_projections())
1537 } else {
1538 None
1539 };
1540
1541 match join.join_type {
1542 JoinType::LeftSemi
1543 | JoinType::LeftAnti
1544 | JoinType::LeftMark
1545 | JoinType::RightSemi
1546 | JoinType::RightAnti
1547 | JoinType::RightMark => {
1548 let mut query_builder = QueryBuilder::default();
1549 let mut from = TableWithJoinsBuilder::default();
1550 let mut exists_select: SelectBuilder = SelectBuilder::default();
1551 from.relation(right_relation);
1552 exists_select.push_from(from);
1553 if let Some(filter) = &join.filter {
1554 exists_select.selection(Some(self.expr_to_sql(filter)?));
1555 }
1556 for (left, right) in &join.on {
1557 exists_select.selection(Some(
1558 self.expr_to_sql(&left.clone().eq(right.clone()))?,
1559 ));
1560 }
1561 exists_select.projection(vec![ast::SelectItem::UnnamedExpr(
1562 ast::Expr::value(ast::Value::Number("1".to_string(), false)),
1563 )]);
1564 query_builder.body(Box::new(SetExpr::Select(Box::new(
1565 exists_select.build()?,
1566 ))));
1567
1568 let negated = match join.join_type {
1569 JoinType::LeftSemi
1570 | JoinType::RightSemi
1571 | JoinType::LeftMark
1572 | JoinType::RightMark => false,
1573 JoinType::LeftAnti | JoinType::RightAnti => true,
1574 _ => unreachable!(),
1575 };
1576 let exists_expr = ast::Expr::Exists {
1577 subquery: Box::new(query_builder.build()?),
1578 negated,
1579 };
1580
1581 match join.join_type {
1582 JoinType::LeftMark | JoinType::RightMark => {
1583 let source_schema =
1584 if join.join_type == JoinType::LeftMark {
1585 right_plan.schema()
1586 } else {
1587 left_plan.schema()
1588 };
1589 let (table_ref, _) = source_schema.qualified_field(0);
1590 let column = self.col_to_sql(&Column::new(
1591 table_ref.cloned(),
1592 "mark",
1593 ))?;
1594 select.replace_mark(&column, &exists_expr);
1595 }
1596 _ => {
1597 select.selection(Some(exists_expr));
1598 }
1599 }
1600 if let Some(projection) = left_projection {
1601 select.projection(projection);
1602 }
1603 }
1604 JoinType::Inner
1605 | JoinType::Left
1606 | JoinType::Right
1607 | JoinType::Full => {
1608 let Ok(Some(relation)) = right_relation.build() else {
1609 return internal_err!("Failed to build right relation");
1610 };
1611 let ast_join = ast::Join {
1612 relation,
1613 global: false,
1614 join_operator: self
1615 .join_operator_to_sql(join.join_type, join_constraint)?,
1616 };
1617 let mut from = select.pop_from().unwrap();
1618 from.push_join(ast_join);
1619 select.push_from(from);
1620 if !already_projected {
1621 let Some(left_projection) = left_projection else {
1622 return internal_err!("Left projection is missing");
1623 };
1624
1625 let Some(right_projection) = right_projection else {
1626 return internal_err!("Right projection is missing");
1627 };
1628
1629 let projection = left_projection
1630 .into_iter()
1631 .chain(right_projection)
1632 .collect();
1633 select.projection(projection);
1634 }
1635 }
1636 }
1637
1638 Ok(())
1639 }
1640 LogicalPlan::AsOfJoin(join) => {
1641 self.asof_join_to_sql(join, query, select, relation)
1642 }
1643 LogicalPlan::SubqueryAlias(plan_alias) => {
1644 let (plan, mut columns) =
1645 subquery_alias_inner_query_and_columns(plan_alias);
1646 let unparsed_table_scan = self.unparse_table_scan_pushdown(
1647 plan,
1648 Some(plan_alias.alias.clone()),
1649 select.already_projected(),
1650 )?;
1651
1652 if (unparsed_table_scan.is_none()
1661 && Self::requires_derived_subquery(plan))
1662 || matches!(plan, LogicalPlan::Filter(_))
1663 {
1664 if !columns.is_empty()
1669 && !self.dialect.supports_column_alias_in_table_alias()
1670 {
1671 let Ok(rewritten_plan) =
1672 inject_column_aliases_into_subquery(plan.clone(), columns)
1673 else {
1674 return internal_err!(
1675 "Failed to transform SubqueryAlias plan"
1676 );
1677 };
1678 return self.derive(
1679 &rewritten_plan,
1680 relation,
1681 Some(self.new_table_alias(
1682 plan_alias.alias.table().to_string(),
1683 vec![],
1684 )),
1685 false,
1686 );
1687 }
1688 return self.derive(
1689 plan,
1690 relation,
1691 Some(self.new_table_alias(
1692 plan_alias.alias.table().to_string(),
1693 columns,
1694 )),
1695 false,
1696 );
1697 }
1698
1699 if !select.already_projected() && unparsed_table_scan.is_none() {
1702 select.projection(vec![ast::SelectItem::Wildcard(
1703 ast::WildcardAdditionalOptions::default(),
1704 )]);
1705 }
1706 let plan = unparsed_table_scan.unwrap_or_else(|| plan.clone());
1707 select.enter_subquery_alias();
1708 let recursive_result = if !columns.is_empty()
1709 && !self.dialect.supports_column_alias_in_table_alias()
1710 {
1711 let rewritten_plan =
1713 match inject_column_aliases_into_subquery(plan, columns) {
1714 Ok(p) => p,
1715 Err(e) => {
1716 return internal_err!(
1717 "Failed to transform SubqueryAlias plan: {e}"
1718 );
1719 }
1720 };
1721
1722 columns = vec![];
1723
1724 self.select_to_sql_recursively(
1725 &rewritten_plan,
1726 query,
1727 select,
1728 relation,
1729 )
1730 } else {
1731 self.select_to_sql_recursively(&plan, query, select, relation)
1732 };
1733 select.exit_subquery_alias();
1734 recursive_result?;
1735
1736 relation.alias(Some(
1737 self.new_table_alias(plan_alias.alias.table().to_string(), columns),
1738 ));
1739
1740 if self.dialect.unnest_as_lateral_flatten()
1744 && find_unnest_node_until_relation(plan_alias.input.as_ref())
1745 .is_some()
1746 {
1747 select.add_flatten_table_alias(plan_alias.alias.table().to_string());
1748 }
1749
1750 Ok(())
1751 }
1752 LogicalPlan::Union(union) => {
1753 if select.already_projected() {
1755 return self.derive_with_dialect_alias(
1756 "derived_union",
1757 plan,
1758 relation,
1759 false,
1760 vec![],
1761 );
1762 }
1763
1764 let input_exprs: Vec<SetExpr> = union
1765 .inputs
1766 .iter()
1767 .map(|input| self.select_to_sql_expr(input, query))
1768 .collect::<Result<Vec<_>>>()?;
1769
1770 assert_or_internal_err!(
1771 input_exprs.len() >= 2,
1772 "UNION operator requires at least 2 inputs"
1773 );
1774
1775 let set_quantifier =
1776 if query.as_ref().is_some_and(|q| q.is_distinct_union()) {
1777 ast::SetQuantifier::None
1780 } else {
1781 ast::SetQuantifier::All
1782 };
1783
1784 let union_expr = input_exprs
1787 .into_iter()
1788 .rev()
1789 .reduce(|a, b| SetExpr::SetOperation {
1790 op: ast::SetOperator::Union,
1791 set_quantifier,
1792 left: Box::new(b),
1793 right: Box::new(a),
1794 })
1795 .unwrap();
1796
1797 let Some(query) = query.as_mut() else {
1798 return internal_err!(
1799 "UNION ALL operator only valid in a statement context"
1800 );
1801 };
1802 query.body(Box::new(union_expr));
1803
1804 Ok(())
1805 }
1806 LogicalPlan::Window(window) => {
1807 let project_window_output = !select.already_projected();
1813 if project_window_output
1814 && Self::window_input_requires_derived_subquery(window.input.as_ref())
1815 {
1816 return self
1817 .window_to_sql_with_derived_input(window, select, relation);
1818 }
1819
1820 let agg = if project_window_output {
1821 find_agg_node_within_select(plan, false)
1822 } else {
1823 None
1824 };
1825
1826 self.select_to_sql_recursively(
1827 window.input.as_ref(),
1828 query,
1829 select,
1830 relation,
1831 )?;
1832
1833 if project_window_output {
1834 self.project_window_output(&window.window_expr, select, agg)?;
1835 }
1836
1837 Ok(())
1838 }
1839 LogicalPlan::EmptyRelation(_) => {
1840 if !relation.has_relation() {
1843 relation.empty();
1844 }
1845 Ok(())
1846 }
1847 LogicalPlan::Extension(extension) => {
1848 let mut query = query.as_mut();
1849 self.extension_to_sql(
1850 extension.node.as_ref(),
1851 &mut query,
1852 &mut Some(select),
1853 &mut Some(relation),
1854 )
1855 }
1856 LogicalPlan::Unnest(unnest) => {
1857 if !unnest.struct_type_columns.is_empty() {
1858 if self.dialect.unnest_as_lateral_flatten() {
1859 return not_impl_err!(
1860 "Snowflake FLATTEN cannot unparse struct unnest: \
1861 DataFusion expands struct fields into columns (horizontal), \
1862 but Snowflake FLATTEN expands them into rows (vertical). \
1863 Columns: {:?}",
1864 unnest.struct_type_columns
1865 );
1866 }
1867 return internal_err!(
1868 "Struct type columns are not currently supported in UNNEST: {:?}",
1869 unnest.struct_type_columns
1870 );
1871 }
1872
1873 if self.dialect.unnest_as_lateral_flatten()
1877 && !relation.has_relation()
1878 && let Some(mut flatten_relation) =
1879 self.try_unnest_to_lateral_flatten_sql(unnest)?
1880 {
1881 if let Some(alias) = select.current_flatten_alias() {
1885 flatten_relation.alias(Some(ast::TableAlias {
1886 name: Ident::with_quote('"', &alias),
1887 columns: vec![],
1888 explicit: true,
1889 at: None,
1890 }));
1891 }
1892 relation.flatten(flatten_relation);
1893 }
1894
1895 if let Some(p) = Self::peel_to_inner_projection(unnest.input.as_ref()) {
1903 self.select_to_sql_recursively(&p.input, query, select, relation)
1906 } else {
1907 internal_err!("Unnest input is not a Projection: {unnest:?}")
1908 }
1909 }
1910 LogicalPlan::Subquery(subquery)
1911 if find_unnest_node_until_relation(subquery.subquery.as_ref())
1912 .is_some() =>
1913 {
1914 if self.dialect.unnest_as_table_factor()
1915 || self.dialect.unnest_as_lateral_flatten()
1916 {
1917 self.select_to_sql_recursively(
1918 subquery.subquery.as_ref(),
1919 query,
1920 select,
1921 relation,
1922 )
1923 } else {
1924 self.derive_with_dialect_alias(
1925 "derived_unnest",
1926 subquery.subquery.as_ref(),
1927 relation,
1928 true,
1929 vec![],
1930 )
1931 }
1932 }
1933 _ => {
1934 not_impl_err!("Unsupported operator: {plan:?}")
1935 }
1936 }
1937 }
1938
1939 #[inline(never)]
1941 fn asof_join_to_sql(
1942 &self,
1943 join: &AsOfJoin,
1944 query: &mut Option<QueryBuilder>,
1945 select: &mut SelectBuilder,
1946 relation: &mut RelationBuilder,
1947 ) -> Result<()> {
1948 let already_projected = select.already_projected();
1949 let left_plan =
1950 Self::unwrap_qualified_passthrough_join_projection(Arc::clone(&join.left));
1951 let inline_left_join = matches!(
1952 left_plan.as_ref(),
1953 LogicalPlan::Join(_) | LogicalPlan::AsOfJoin(_)
1954 );
1955 let left_projection = if already_projected {
1956 None
1957 } else if inline_left_join {
1958 self.select_to_sql_recursively(left_plan.as_ref(), query, select, relation)?;
1959 select.pop_projections();
1960 Some(self.derived_input_projection(join.left.as_ref(), None)?)
1961 } else if Self::asof_input_requires_derived(join.left.as_ref()) {
1962 let qualifier = self.derive_asof_input(join.left.as_ref(), relation)?;
1963 Some(self.derived_input_projection(join.left.as_ref(), qualifier.as_ref())?)
1964 } else {
1965 self.select_to_sql_recursively(join.left.as_ref(), query, select, relation)?;
1966 Some(select.pop_projections())
1967 };
1968 if already_projected {
1969 if inline_left_join {
1970 self.select_to_sql_recursively(
1971 left_plan.as_ref(),
1972 query,
1973 select,
1974 relation,
1975 )?;
1976 } else if Self::asof_input_requires_derived(join.left.as_ref()) {
1977 self.derive_asof_input(join.left.as_ref(), relation)?;
1978 } else {
1979 self.select_to_sql_recursively(
1980 join.left.as_ref(),
1981 query,
1982 select,
1983 relation,
1984 )?;
1985 }
1986 }
1987
1988 let mut right_relation = RelationBuilder::default();
1989 let nested_right =
1990 self.join_input_to_nested_relation(join.right.as_ref(), query)?;
1991 let right_projection = if already_projected {
1992 if let Some(nested_right) = nested_right {
1993 right_relation = nested_right;
1994 } else if Self::asof_input_requires_derived(join.right.as_ref()) {
1995 self.derive_asof_input(join.right.as_ref(), &mut right_relation)?;
1996 } else {
1997 self.select_to_sql_recursively(
1998 join.right.as_ref(),
1999 query,
2000 select,
2001 &mut right_relation,
2002 )?;
2003 }
2004 None
2005 } else if let Some(nested_right) = nested_right {
2006 right_relation = nested_right;
2007 Some(self.derived_input_projection(join.right.as_ref(), None)?)
2008 } else if Self::asof_input_requires_derived(join.right.as_ref()) {
2009 let qualifier =
2010 self.derive_asof_input(join.right.as_ref(), &mut right_relation)?;
2011 Some(self.derived_input_projection(join.right.as_ref(), qualifier.as_ref())?)
2012 } else {
2013 self.select_to_sql_recursively(
2014 join.right.as_ref(),
2015 query,
2016 select,
2017 &mut right_relation,
2018 )?;
2019 Some(select.pop_projections())
2020 };
2021 let Ok(Some(relation)) = right_relation.build() else {
2022 return internal_err!("Failed to build ASOF right relation");
2023 };
2024 let constraint =
2025 self.join_constraint_to_sql(join.join_constraint, &join.on, None)?;
2026 let match_condition = self.expr_to_sql(&Expr::BinaryExpr(BinaryExpr::new(
2027 Box::new(join.match_condition.left.clone()),
2028 join.match_condition.op,
2029 Box::new(join.match_condition.right.clone()),
2030 )))?;
2031 let ast_join = ast::Join {
2032 relation,
2033 global: false,
2034 join_operator: ast::JoinOperator::AsOf {
2035 match_condition,
2036 constraint,
2037 },
2038 };
2039 let mut from = select
2040 .pop_from()
2041 .ok_or_else(|| internal_datafusion_err!("ASOF left relation is missing"))?;
2042 from.push_join(ast_join);
2043 select.push_from(from);
2044
2045 if !already_projected {
2046 let left_projection = left_projection.ok_or_else(|| {
2047 internal_datafusion_err!("ASOF left projection is missing")
2048 })?;
2049 let right_projection = right_projection.ok_or_else(|| {
2050 internal_datafusion_err!("ASOF right projection is missing")
2051 })?;
2052 select.projection(
2053 left_projection
2054 .into_iter()
2055 .chain(right_projection)
2056 .collect(),
2057 );
2058 }
2059 Ok(())
2060 }
2061
2062 fn peel_to_inner_projection(plan: &LogicalPlan) -> Option<&Projection> {
2070 match plan {
2071 LogicalPlan::Projection(p) => Some(p),
2072 LogicalPlan::SubqueryAlias(alias) => {
2073 Self::peel_to_inner_projection(alias.input.as_ref())
2074 }
2075 _ => None,
2076 }
2077 }
2078
2079 fn peel_to_unnest_with_modifiers<'a>(
2090 &self,
2091 plan: &'a LogicalPlan,
2092 query: &mut Option<QueryBuilder>,
2093 flatten_alias: Option<&str>,
2094 ) -> Result<Option<(&'a Unnest, &'a LogicalPlan)>> {
2095 match plan {
2096 LogicalPlan::Unnest(unnest) => Ok(Some((unnest, plan))),
2097 LogicalPlan::Limit(limit) => {
2098 if let Some(fetch) = &limit.fetch
2099 && let Some(q) = query.as_mut()
2100 {
2101 q.limit(Some(self.expr_to_sql(fetch)?));
2102 }
2103 if let Some(skip) = &limit.skip
2104 && let Some(q) = query.as_mut()
2105 {
2106 q.offset(Some(ast::Offset {
2107 rows: ast::OffsetRows::None,
2108 value: self.expr_to_sql(skip)?,
2109 }));
2110 }
2111 self.peel_to_unnest_with_modifiers(
2112 limit.input.as_ref(),
2113 query,
2114 flatten_alias,
2115 )
2116 }
2117 LogicalPlan::Sort(sort) => {
2118 let Some(query_ref) = query.as_mut() else {
2119 return internal_err!(
2120 "Sort between Projection and Unnest requires a statement context."
2121 );
2122 };
2123 if let Some(fetch) = sort.fetch {
2124 query_ref.limit(Some(ast::Expr::value(ast::Value::Number(
2125 fetch.to_string(),
2126 false,
2127 ))));
2128 }
2129 let unnest_node = match sort.input.as_ref() {
2133 LogicalPlan::Unnest(u) => Some(u),
2134 _ => find_unnest_node_within_select(sort.input.as_ref()),
2135 };
2136 let sort_exprs = if let Some(alias) = flatten_alias
2137 && let Some(unnest) = unnest_node
2138 {
2139 sort.expr
2140 .iter()
2141 .map(|s| {
2142 let rewritten = unproject_unnest_expr_as_flatten_value(
2143 s.expr.clone(),
2144 unnest,
2145 alias,
2146 )?;
2147 Ok(SortExpr {
2148 expr: rewritten,
2149 ..s.clone()
2150 })
2151 })
2152 .collect::<Result<Vec<_>>>()?
2153 } else {
2154 sort.expr.clone()
2155 };
2156 query_ref.order_by(self.sorts_to_sql(&sort_exprs)?);
2157 self.peel_to_unnest_with_modifiers(
2158 sort.input.as_ref(),
2159 query,
2160 flatten_alias,
2161 )
2162 }
2163 _ => Ok(None),
2164 }
2165 }
2166
2167 fn find_unnest_placeholder(expr: &Expr) -> Option<UnnestInputType> {
2174 let mut result = None;
2175 let _ = expr.apply(|e| {
2176 if let Some(t) = Self::classify_placeholder_column(e) {
2177 result = Some(t);
2178 return Ok(TreeNodeRecursion::Stop);
2179 }
2180 Ok(TreeNodeRecursion::Continue)
2181 });
2182 result
2183 }
2184
2185 fn is_bare_unnest_placeholder(expr: &Expr) -> bool {
2192 let inner = match expr {
2194 Expr::Alias(Alias { expr, .. }) => expr.as_ref(),
2195 other => other,
2196 };
2197 Self::classify_placeholder_column(inner).is_some()
2198 }
2199
2200 fn classify_placeholder_column(expr: &Expr) -> Option<UnnestInputType> {
2204 if let Expr::Column(Column { name, .. }) = expr
2205 && let Some(prefix) = name.strip_prefix(UNNEST_PLACEHOLDER)
2206 {
2207 if prefix.starts_with(&format!("({OUTER_REFERENCE_COLUMN_PREFIX}(")) {
2208 return Some(UnnestInputType::OuterReference);
2209 }
2210 return Some(UnnestInputType::Scalar);
2211 }
2212 None
2213 }
2214
2215 fn has_internal_unnest_alias(expr: &Expr) -> bool {
2223 match expr {
2224 Expr::Column(col) => {
2225 col.name.starts_with(&format!("{UNNEST_COLUMN_PREFIX}("))
2226 }
2227 Expr::Alias(Alias { name, .. }) => {
2228 name.starts_with(&format!("{UNNEST_COLUMN_PREFIX}("))
2229 }
2230 _ => false,
2231 }
2232 }
2233
2234 fn contains_unnest(plan: &LogicalPlan) -> bool {
2241 match plan {
2242 LogicalPlan::Unnest(_) => true,
2243 LogicalPlan::Projection(p) => Self::contains_unnest(&p.input),
2244 LogicalPlan::Subquery(s) => Self::contains_unnest(&s.subquery),
2245 LogicalPlan::SubqueryAlias(a) => Self::contains_unnest(&a.input),
2246 _ => false,
2247 }
2248 }
2249
2250 fn collect_flatten_aliases(plan: &LogicalPlan, select: &mut SelectBuilder) {
2251 match plan {
2252 LogicalPlan::SubqueryAlias(alias)
2253 if Self::contains_unnest(alias.input.as_ref()) =>
2254 {
2255 select.add_flatten_table_alias(alias.alias.table().to_string());
2256 }
2257 LogicalPlan::Join(join) => {
2258 Self::collect_flatten_aliases(&join.left, select);
2259 Self::collect_flatten_aliases(&join.right, select);
2260 }
2261 _ => {}
2262 }
2263 }
2264
2265 fn try_unnest_to_table_factor_sql(
2266 &self,
2267 unnest: &Unnest,
2268 ) -> Result<Option<UnnestRelationBuilder>> {
2269 let mut unnest_relation = UnnestRelationBuilder::default();
2270 let LogicalPlan::Projection(projection) = unnest.input.as_ref() else {
2271 return Ok(None);
2272 };
2273
2274 if !matches!(projection.input.as_ref(), LogicalPlan::EmptyRelation(_)) {
2275 return Ok(None);
2283 }
2284
2285 let exprs = projection
2286 .expr
2287 .iter()
2288 .map(|e| self.expr_to_sql(e))
2289 .collect::<Result<Vec<_>>>()?;
2290 unnest_relation.array_exprs(exprs);
2291
2292 Ok(Some(unnest_relation))
2293 }
2294
2295 fn build_flatten_value_select_item(
2297 &self,
2298 flatten_alias: &str,
2299 user_alias: Option<&str>,
2300 ) -> ast::SelectItem {
2301 let compound = ast::Expr::CompoundIdentifier(vec![
2302 self.new_ident_quoted_if_needs(flatten_alias.to_string()),
2303 Ident::with_quote('"', "VALUE"),
2304 ]);
2305 match user_alias {
2306 Some(alias) => ast::SelectItem::ExprWithAlias {
2307 expr: compound,
2308 alias: self.new_ident_quoted_if_needs(alias.to_string()),
2309 },
2310 None => ast::SelectItem::UnnamedExpr(compound),
2311 }
2312 }
2313
2314 fn try_unnest_to_lateral_flatten_sql(
2317 &self,
2318 unnest: &Unnest,
2319 ) -> Result<Option<FlattenRelationBuilder>> {
2320 let Some(projection) = Self::peel_to_inner_projection(unnest.input.as_ref())
2321 else {
2322 return Ok(None);
2323 };
2324
2325 let Some(first_expr) = projection.expr.first() else {
2328 return Ok(None);
2329 };
2330
2331 let input_expr = self.expr_to_sql(first_expr)?;
2332
2333 let mut flatten = FlattenRelationBuilder::default();
2334 flatten.input_expr(input_expr);
2335 flatten.outer(unnest.options.preserve_nulls());
2336
2337 Ok(Some(flatten))
2338 }
2339
2340 fn is_scan_with_pushdown(scan: &TableScan) -> bool {
2341 scan.projection.is_some()
2342 || !scan.filters.is_empty()
2343 || scan.fetch.is_some()
2344 || scan.skip.is_some()
2345 }
2346
2347 fn requires_derived_subquery(plan: &LogicalPlan) -> bool {
2353 matches!(
2354 plan,
2355 LogicalPlan::Aggregate(_)
2356 | LogicalPlan::Window(_)
2357 | LogicalPlan::Sort(_)
2358 | LogicalPlan::Limit(_)
2359 | LogicalPlan::Union(_)
2360 )
2361 }
2362
2363 fn asof_input_requires_derived(plan: &LogicalPlan) -> bool {
2364 let simple_scan =
2365 |scan: &TableScan| scan.filters.is_empty() && scan.fetch.is_none();
2366 match plan {
2367 LogicalPlan::TableScan(scan) => !simple_scan(scan),
2368 LogicalPlan::SubqueryAlias(alias) => {
2369 !matches!(alias.input.as_ref(), LogicalPlan::TableScan(scan) if simple_scan(scan))
2370 }
2371 _ => true,
2372 }
2373 }
2374
2375 fn derive_asof_input(
2376 &self,
2377 plan: &LogicalPlan,
2378 relation: &mut RelationBuilder,
2379 ) -> Result<Option<TableReference>> {
2380 if let LogicalPlan::SubqueryAlias(alias) = plan {
2381 let (inner, columns) = subquery_alias_inner_query_and_columns(alias);
2382 let table_alias = alias.alias.clone();
2383 if !columns.is_empty() && !self.dialect.supports_column_alias_in_table_alias()
2384 {
2385 let rewritten =
2386 inject_column_aliases_into_subquery(inner.clone(), columns)?;
2387 self.derive(
2388 &rewritten,
2389 relation,
2390 Some(self.new_table_alias(table_alias.table().to_string(), vec![])),
2391 false,
2392 )?;
2393 } else {
2394 self.derive(
2395 inner,
2396 relation,
2397 Some(self.new_table_alias(table_alias.table().to_string(), columns)),
2398 false,
2399 )?;
2400 }
2401 return Ok(Some(table_alias));
2402 }
2403
2404 let qualifier = plan
2405 .schema()
2406 .iter()
2407 .find_map(|(qualifier, _)| qualifier.cloned());
2408 let alias = qualifier
2409 .as_ref()
2410 .map(|qualifier| self.new_table_alias(qualifier.table().to_string(), vec![]));
2411 self.derive(plan, relation, alias, false)?;
2412 Ok(qualifier)
2413 }
2414
2415 fn derived_input_projection(
2416 &self,
2417 plan: &LogicalPlan,
2418 qualifier: Option<&TableReference>,
2419 ) -> Result<Vec<ast::SelectItem>> {
2420 plan.schema()
2421 .iter()
2422 .map(|(field_qualifier, field)| {
2423 self.select_item_to_sql(&Expr::Column(Column::new(
2424 qualifier.cloned().or_else(|| field_qualifier.cloned()),
2425 field.name(),
2426 )))
2427 })
2428 .collect()
2429 }
2430
2431 fn is_qualified_passthrough_projection(projection: &Projection) -> bool {
2432 projection
2433 .expr
2434 .iter()
2435 .all(|expr| matches!(expr, Expr::Column(column) if column.relation.is_some()))
2436 }
2437
2438 fn unwrap_qualified_passthrough_join_projection(
2439 plan: Arc<LogicalPlan>,
2440 ) -> Arc<LogicalPlan> {
2441 if let LogicalPlan::Projection(projection) = plan.as_ref()
2442 && matches!(
2443 projection.input.as_ref(),
2444 LogicalPlan::Join(_) | LogicalPlan::AsOfJoin(_)
2445 )
2446 && Self::is_qualified_passthrough_projection(projection)
2447 {
2448 Arc::clone(&projection.input)
2449 } else {
2450 plan
2451 }
2452 }
2453
2454 fn join_input_to_nested_relation(
2455 &self,
2456 plan: &LogicalPlan,
2457 query: &mut Option<QueryBuilder>,
2458 ) -> Result<Option<RelationBuilder>> {
2459 let join_plan = match plan {
2460 LogicalPlan::Join(_) | LogicalPlan::AsOfJoin(_) => plan,
2461 LogicalPlan::Projection(projection)
2462 if matches!(
2463 projection.input.as_ref(),
2464 LogicalPlan::Join(_) | LogicalPlan::AsOfJoin(_)
2465 ) && Self::is_qualified_passthrough_projection(projection) =>
2466 {
2467 projection.input.as_ref()
2468 }
2469 _ => return Ok(None),
2470 };
2471
2472 let original_query = query.clone();
2473 let mut nested_select = SelectBuilder::default();
2474 nested_select.push_from(TableWithJoinsBuilder::default());
2475 let mut nested_relation = RelationBuilder::default();
2476 self.select_to_sql_recursively(
2477 join_plan,
2478 query,
2479 &mut nested_select,
2480 &mut nested_relation,
2481 )?;
2482 if nested_select.has_selection() {
2483 *query = original_query;
2484 return Ok(None);
2485 }
2486
2487 let Some(mut nested_from) = nested_select.pop_from() else {
2488 return internal_err!("Failed to build nested join input relation");
2489 };
2490 nested_from.relation(nested_relation);
2491 let Some(table_with_joins) = nested_from.build()? else {
2492 return internal_err!("Failed to build nested join input relation");
2493 };
2494
2495 let mut relation = RelationBuilder::default();
2496 relation.nested_join(table_with_joins, None);
2497 Ok(Some(relation))
2498 }
2499
2500 fn strip_column_qualifiers(expr: Expr) -> Result<Expr> {
2504 expr.transform(|e| match e {
2505 Expr::Column(mut column) => {
2506 column.relation = None;
2507 Ok(Transformed::yes(Expr::Column(column)))
2508 }
2509 other => Ok(Transformed::no(other)),
2510 })
2511 .data()
2512 }
2513
2514 fn strip_column_qualifiers_for_schema(expr: Expr, schema: &DFSchema) -> Result<Expr> {
2515 expr.transform(|e| match e {
2516 Expr::Column(mut column)
2517 if column.relation.is_some()
2518 && schema.index_of_column(&column).is_ok() =>
2519 {
2520 column.relation = None;
2521 Ok(Transformed::yes(Expr::Column(column)))
2522 }
2523 other => Ok(Transformed::no(other)),
2524 })
2525 .data()
2526 }
2527
2528 fn unparse_table_scan_pushdown(
2531 &self,
2532 plan: &LogicalPlan,
2533 alias: Option<TableReference>,
2534 already_projected: bool,
2535 ) -> Result<Option<LogicalPlan>> {
2536 match plan {
2537 LogicalPlan::TableScan(table_scan) => {
2538 if !Self::is_scan_with_pushdown(table_scan) {
2539 return Ok(None);
2540 }
2541 let table_schema = table_scan.source.schema();
2542 let filter_schema = DFSchema::try_from_qualified_schema(
2543 table_scan.table_name.clone(),
2544 table_schema.as_ref(),
2545 )?;
2546 let mut filter_alias_rewriter =
2547 alias.as_ref().map(|alias_name| TableAliasRewriter {
2548 table_schema: &filter_schema,
2549 alias_name: alias_name.clone(),
2550 rewrite_unqualified: true,
2551 });
2552
2553 let mut builder = LogicalPlanBuilder::scan(
2554 table_scan.table_name.clone(),
2555 Arc::clone(&table_scan.source),
2556 None,
2557 )?;
2558 if let Some(ref alias) = alias
2564 && (table_scan.projection.is_some() || !table_scan.filters.is_empty())
2565 {
2566 builder = builder.alias(alias.clone())?;
2567 }
2568
2569 if !already_projected && let Some(project_vec) = &table_scan.projection {
2573 if project_vec.is_empty() {
2574 builder = builder.project(self.empty_projection_fallback())?;
2575 } else {
2576 let schema = table_scan.source.schema();
2577 let project_columns = project_vec
2578 .iter()
2579 .copied()
2580 .map(|i| {
2581 let field = schema.field(i);
2582 if alias.is_some() {
2583 Column::new(alias.clone(), field.name().clone())
2584 } else {
2585 Column::new(
2586 Some(table_scan.table_name.clone()),
2587 field.name().clone(),
2588 )
2589 }
2590 })
2591 .collect::<Vec<_>>();
2592 builder = builder.project(project_columns)?;
2593 }
2594 }
2595
2596 let filter_expr: Result<Option<Expr>> = table_scan
2597 .filters
2598 .iter()
2599 .cloned()
2600 .map(|expr| {
2601 if let Some(ref mut rewriter) = filter_alias_rewriter {
2602 expr.rewrite(rewriter).data()
2603 } else {
2604 Ok(expr)
2605 }
2606 })
2607 .reduce(|acc, expr_result| {
2608 acc.and_then(|acc_expr| {
2609 expr_result.map(|expr| acc_expr.and(expr))
2610 })
2611 })
2612 .transpose();
2613
2614 if let Some(filter) = filter_expr? {
2615 builder = builder.filter(filter)?;
2616 }
2617
2618 match (table_scan.skip, table_scan.fetch) {
2619 (Some(offset), Some(fetch)) => {
2620 builder = builder.limit(offset, Some(fetch))?
2621 }
2622 (Some(offset), None) => builder = builder.limit(offset, None)?,
2623 (None, Some(fetch)) => builder = builder.limit(0, Some(fetch))?,
2624 (None, None) => (),
2625 }
2626
2627 if let Some(alias) = alias
2632 && table_scan.projection.is_none()
2633 && table_scan.filters.is_empty()
2634 {
2635 builder = builder.alias(alias)?;
2636 }
2637
2638 Ok(Some(builder.build()?))
2639 }
2640 LogicalPlan::SubqueryAlias(subquery_alias) => {
2641 let ret = self.unparse_table_scan_pushdown(
2642 &subquery_alias.input,
2643 Some(subquery_alias.alias.clone()),
2644 already_projected,
2645 )?;
2646 if let Some(alias) = alias
2647 && let Some(plan) = ret
2648 {
2649 let plan = LogicalPlanBuilder::new(plan).alias(alias)?.build()?;
2650 return Ok(Some(plan));
2651 }
2652 Ok(ret)
2653 }
2654 LogicalPlan::Projection(projection) => {
2657 if let Some(plan) = self.unparse_table_scan_pushdown(
2658 &projection.input,
2659 alias.clone(),
2660 already_projected,
2661 )? {
2662 if alias.is_some() && matches!(plan, LogicalPlan::Projection(_)) {
2677 let exprs = projection
2678 .expr
2679 .iter()
2680 .cloned()
2681 .map(Self::strip_column_qualifiers)
2682 .collect::<Result<Vec<_>>>()?;
2683 return Ok(Some(LogicalPlan::Projection(Projection::try_new(
2684 exprs,
2685 Arc::new(plan),
2686 )?)));
2687 }
2688
2689 let exprs = if alias.is_some() {
2690 let mut alias_rewriter =
2691 alias.as_ref().map(|alias_name| TableAliasRewriter {
2692 table_schema: plan.schema().as_ref(),
2693 alias_name: alias_name.clone(),
2694 rewrite_unqualified: false,
2695 });
2696 projection
2697 .expr
2698 .iter()
2699 .cloned()
2700 .map(|expr| {
2701 if let Some(ref mut rewriter) = alias_rewriter {
2702 expr.rewrite(rewriter).data()
2703 } else {
2704 Ok(expr)
2705 }
2706 })
2707 .collect::<Result<Vec<_>>>()?
2708 } else {
2709 projection.expr.clone()
2710 };
2711 Ok(Some(
2712 LogicalPlanBuilder::from(plan).project(exprs)?.build()?,
2713 ))
2714 } else {
2715 Ok(None)
2716 }
2717 }
2718 _ => Ok(None),
2719 }
2720 }
2721
2722 fn select_item_to_sql(&self, expr: &Expr) -> Result<ast::SelectItem> {
2723 match expr {
2724 Expr::Alias(Alias { expr, name, .. }) => {
2725 let inner = self.expr_to_sql(expr)?;
2726
2727 Ok(ast::SelectItem::ExprWithAlias {
2728 expr: inner,
2729 alias: self.column_alias_to_sql(name)?,
2730 })
2731 }
2732 _ => {
2733 let inner = self.expr_to_sql(expr)?;
2734
2735 Ok(ast::SelectItem::UnnamedExpr(inner))
2736 }
2737 }
2738 }
2739
2740 fn column_alias_to_sql(&self, name: &str) -> Result<Ident> {
2741 let name = self
2742 .dialect
2743 .col_alias_overrides(name)?
2744 .unwrap_or_else(|| name.to_string());
2745 Ok(self.new_ident_quoted_if_needs(name))
2746 }
2747
2748 fn sorts_to_sql(&self, sort_exprs: &[SortExpr]) -> Result<OrderByKind> {
2749 Ok(OrderByKind::Expressions(
2750 sort_exprs
2751 .iter()
2752 .map(|sort_expr| self.sort_to_sql(sort_expr))
2753 .collect::<Result<Vec<_>>>()?,
2754 ))
2755 }
2756
2757 fn join_operator_to_sql(
2758 &self,
2759 join_type: JoinType,
2760 constraint: ast::JoinConstraint,
2761 ) -> Result<ast::JoinOperator> {
2762 Ok(match join_type {
2763 JoinType::Inner => match &constraint {
2764 ast::JoinConstraint::On(_)
2765 | ast::JoinConstraint::Using(_)
2766 | ast::JoinConstraint::Natural => ast::JoinOperator::Inner(constraint),
2767 ast::JoinConstraint::None => {
2768 ast::JoinOperator::CrossJoin(constraint)
2771 }
2772 },
2773 JoinType::Left => ast::JoinOperator::LeftOuter(constraint),
2774 JoinType::Right => ast::JoinOperator::RightOuter(constraint),
2775 JoinType::Full => ast::JoinOperator::FullOuter(constraint),
2776 JoinType::LeftAnti => ast::JoinOperator::LeftAnti(constraint),
2777 JoinType::LeftSemi => ast::JoinOperator::LeftSemi(constraint),
2778 JoinType::RightAnti => ast::JoinOperator::RightAnti(constraint),
2779 JoinType::RightSemi => ast::JoinOperator::RightSemi(constraint),
2780 JoinType::LeftMark | JoinType::RightMark => {
2781 unimplemented!("Unparsing of Mark join type")
2782 }
2783 })
2784 }
2785
2786 fn join_using_to_sql(
2790 &self,
2791 join_conditions: &[(Expr, Expr)],
2792 ) -> Option<ast::JoinConstraint> {
2793 let mut object_names = Vec::with_capacity(join_conditions.len());
2794 for (left, right) in join_conditions {
2795 match (left, right) {
2796 (
2797 Expr::Column(Column {
2798 relation: _,
2799 name: left_name,
2800 spans: _,
2801 }),
2802 Expr::Column(Column {
2803 relation: _,
2804 name: right_name,
2805 spans: _,
2806 }),
2807 ) if left_name == right_name => {
2808 let ident = self.new_ident_quoted_if_needs(left_name.to_string());
2812 object_names.push(ast::ObjectName::from(vec![ident]));
2813 }
2814 _ => return None,
2817 }
2818 }
2819 Some(ast::JoinConstraint::Using(object_names))
2820 }
2821
2822 fn join_constraint_to_sql(
2824 &self,
2825 constraint: JoinConstraint,
2826 conditions: &[(Expr, Expr)],
2827 filter: Option<&Expr>,
2828 ) -> Result<ast::JoinConstraint> {
2829 match (constraint, conditions, filter) {
2830 (JoinConstraint::On | JoinConstraint::Using, [], None) => {
2832 Ok(ast::JoinConstraint::None)
2833 }
2834
2835 (JoinConstraint::Using, conditions, None) => {
2836 match self.join_using_to_sql(conditions) {
2837 Some(using) => Ok(using),
2838 None => self.join_conditions_to_sql_on(conditions, None),
2841 }
2842 }
2843
2844 (JoinConstraint::On | JoinConstraint::Using, conditions, filter) => {
2852 self.join_conditions_to_sql_on(conditions, filter)
2853 }
2854 }
2855 }
2856
2857 fn join_conditions_to_sql_on(
2861 &self,
2862 join_conditions: &[(Expr, Expr)],
2863 filter: Option<&Expr>,
2864 ) -> Result<ast::JoinConstraint> {
2865 let mut condition = None;
2866 for (left, right) in join_conditions {
2868 let l = self.expr_to_sql(left)?;
2870 let r = self.expr_to_sql(right)?;
2871 let e = self.binary_op_to_sql(l, r, ast::BinaryOperator::Eq);
2872 condition = match condition {
2873 Some(expr) => Some(self.and_op_to_sql(expr, e)),
2874 None => Some(e),
2875 };
2876 }
2877
2878 condition = match (condition, filter) {
2880 (Some(expr), Some(filter)) => {
2881 Some(self.and_op_to_sql(expr, self.expr_to_sql(filter)?))
2882 }
2883 (Some(expr), None) => Some(expr),
2884 (None, Some(filter)) => Some(self.expr_to_sql(filter)?),
2885 (None, None) => None,
2886 };
2887
2888 let constraint = match condition {
2889 Some(filter) => ast::JoinConstraint::On(filter),
2890 None => ast::JoinConstraint::None,
2891 };
2892
2893 Ok(constraint)
2894 }
2895
2896 fn and_op_to_sql(&self, lhs: ast::Expr, rhs: ast::Expr) -> ast::Expr {
2897 self.binary_op_to_sql(lhs, rhs, ast::BinaryOperator::And)
2898 }
2899
2900 fn new_table_alias(&self, alias: String, columns: Vec<Ident>) -> ast::TableAlias {
2901 let columns = columns
2902 .into_iter()
2903 .map(|ident| TableAliasColumnDef {
2904 name: ident,
2905 data_type: None,
2906 })
2907 .collect();
2908 ast::TableAlias {
2909 name: self.new_ident_quoted_if_needs(alias),
2910 columns,
2911 explicit: true,
2912 at: None,
2913 }
2914 }
2915
2916 fn dml_to_sql(&self, plan: &LogicalPlan) -> Result<ast::Statement> {
2917 not_impl_err!("Unsupported plan: {plan:?}")
2918 }
2919
2920 fn empty_projection_fallback(&self) -> Vec<Expr> {
2924 if self.dialect.supports_empty_select_list() {
2925 Vec::new()
2926 } else {
2927 vec![Expr::Literal(ScalarValue::Int64(Some(1)), None)]
2928 }
2929 }
2930
2931 fn split_join_on_and_where_filters(
2940 join_type: JoinType,
2941 join_filter: Option<&Expr>,
2942 table_scan_filters: Vec<Expr>,
2943 ) -> (Option<Expr>, Vec<Expr>) {
2944 if table_scan_filters.is_empty() {
2945 return (join_filter.cloned(), vec![]);
2946 }
2947
2948 if join_type == JoinType::Inner {
2949 return (join_filter.cloned(), table_scan_filters);
2952 }
2953
2954 let combined = table_scan_filters.into_iter().reduce(|acc, filter| {
2956 Expr::BinaryExpr(BinaryExpr {
2957 left: Box::new(acc),
2958 op: Operator::And,
2959 right: Box::new(filter),
2960 })
2961 });
2962
2963 let on_filter = match (join_filter, combined) {
2964 (Some(jf), Some(c)) => Some(Expr::BinaryExpr(BinaryExpr {
2965 left: Box::new(jf.clone()),
2966 op: Operator::And,
2967 right: Box::new(c),
2968 })),
2969 (Some(jf), None) => Some(jf.clone()),
2970 (None, Some(c)) => Some(c),
2971 (None, None) => None,
2972 };
2973
2974 (on_filter, vec![])
2975 }
2976}
2977
2978impl From<BuilderError> for DataFusionError {
2979 fn from(e: BuilderError) -> Self {
2980 DataFusionError::External(Box::new(e))
2981 }
2982}
2983
2984#[derive(Debug)]
2986enum UnnestInputType {
2987 OuterReference,
2989 Scalar,
2991}