Skip to content

Apache DataFusion SQL Query Engine

Fix wildcard dataframe case (#15230)

Jay Zhana27a92886a3c
diff --git a/benchmarks/src/imdb/convert.rs b/benchmarks/src/imdb/convert.rs
index 4e470d711d..e7949aa715 100644
--- a/benchmarks/src/imdb/convert.rs
+++ b/benchmarks/src/imdb/convert.rs
@@ -16,6 +16,7 @@
// under the License.
use datafusion::dataframe::DataFrameWriteOptions;
+use datafusion::logical_expr::select_expr::SelectExpr;
use datafusion_common::instant::Instant;
use std::path::PathBuf;
@@ -74,7 +75,8 @@ impl ConvertOpt {
.iter()
.take(schema.fields.len())
.map(Expr::from)
- .collect();
+ .map(SelectExpr::from)
+ .collect::<Vec<_>>();
csv = csv.select(selection)?;
diff --git a/benchmarks/src/tpch/convert.rs b/benchmarks/src/tpch/convert.rs
index 30178d17aa..7f391d9300 100644
--- a/benchmarks/src/tpch/convert.rs
+++ b/benchmarks/src/tpch/convert.rs
@@ -15,6 +15,7 @@
// specific language governing permissions and limitations
// under the License.
+use datafusion::logical_expr::select_expr::SelectExpr;
use datafusion_common::instant::Instant;
use std::fs;
use std::path::{Path, PathBuf};
@@ -89,7 +90,8 @@ impl ConvertOpt {
.iter()
.take(schema.fields.len() - 1)
.map(Expr::from)
- .collect();
+ .map(SelectExpr::from)
+ .collect::<Vec<_>>();
csv = csv.select(selection)?;
// optionally, repartition the file
diff --git a/datafusion/core/src/dataframe/mod.rs b/datafusion/core/src/dataframe/mod.rs
index e87cc81300..9c27c7c5d3 100644
--- a/datafusion/core/src/dataframe/mod.rs
+++ b/datafusion/core/src/dataframe/mod.rs
@@ -54,6 +54,7 @@ use datafusion_common::{
exec_err, not_impl_err, plan_datafusion_err, plan_err, Column, DFSchema,
DataFusionError, ParamValues, ScalarValue, SchemaError, UnnestOptions,
};
+use datafusion_expr::select_expr::SelectExpr;
use datafusion_expr::{
case,
dml::InsertOp,
@@ -342,13 +343,28 @@ impl DataFrame {
/// # Ok(())
/// # }
/// ```
- pub fn select(self, expr_list: Vec<Expr>) -> Result<DataFrame> {
- let window_func_exprs = find_window_exprs(&expr_list);
+ pub fn select(
+ self,
+ expr_list: impl IntoIterator<Item = impl Into<SelectExpr>>,
+ ) -> Result<DataFrame> {
+ let expr_list: Vec<SelectExpr> =
+ expr_list.into_iter().map(|e| e.into()).collect::<Vec<_>>();
+
+ let expressions = expr_list
+ .iter()
+ .filter_map(|e| match e {
+ SelectExpr::Expression(expr) => Some(expr.clone()),
+ _ => None,
+ })
+ .collect::<Vec<_>>();
+
+ let window_func_exprs = find_window_exprs(&expressions);
let plan = if window_func_exprs.is_empty() {
self.plan
} else {
LogicalPlanBuilder::window_plan(self.plan, window_func_exprs)?
};
+
let project_plan = LogicalPlanBuilder::from(plan).project(expr_list)?.build()?;
Ok(DataFrame {
diff --git a/datafusion/core/tests/dataframe/mod.rs b/datafusion/core/tests/dataframe/mod.rs
index 308568bb5f..a6c06749b5 100644
--- a/datafusion/core/tests/dataframe/mod.rs
+++ b/datafusion/core/tests/dataframe/mod.rs
@@ -73,7 +73,7 @@ use datafusion_expr::expr::{GroupingSet, Sort, WindowFunction};
use datafusion_expr::var_provider::{VarProvider, VarType};
use datafusion_expr::{
cast, col, create_udf, exists, in_subquery, lit, out_ref_col, placeholder,
- scalar_subquery, when, Expr, ExprFunctionExt, ExprSchemable, LogicalPlan,
+ scalar_subquery, when, wildcard, Expr, ExprFunctionExt, ExprSchemable, LogicalPlan,
ScalarFunctionImplementation, WindowFrame, WindowFrameBound, WindowFrameUnits,
WindowFunctionDefinition,
};
@@ -269,6 +269,16 @@ async fn select_expr() -> Result<()> {
Ok(())
}
+#[tokio::test]
+async fn select_all() -> Result<()> {
+ let t = test_table().await?;
+ let plan = t.select([wildcard()])?.logical_plan().clone();
+ let sql_plan = create_plan("SELECT * FROM aggregate_test_100").await?;
+ assert_same_plan(&plan, &sql_plan);
+
+ Ok(())
+}
+
#[tokio::test]
async fn select_exprs() -> Result<()> {
// build plan using `select_expr``
diff --git a/datafusion/expr/src/expr_fn.rs b/datafusion/expr/src/expr_fn.rs
index c08738c183..966aba7d11 100644
--- a/datafusion/expr/src/expr_fn.rs
+++ b/datafusion/expr/src/expr_fn.rs
@@ -25,6 +25,7 @@ use crate::function::{
AccumulatorArgs, AccumulatorFactoryFunction, PartitionEvaluatorFactory,
StateFieldsArgs,
};
+use crate::select_expr::SelectExpr;
use crate::{
conditional_expressions::CaseBuilder, expr::Sort, logical_plan::Subquery,
AggregateUDF, Expr, LogicalPlan, Operator, PartitionEvaluator, ScalarFunctionArgs,
@@ -120,21 +121,13 @@ pub fn placeholder(id: impl Into<String>) -> Expr {
/// let p = wildcard();
/// assert_eq!(p.to_string(), "*")
/// ```
-pub fn wildcard() -> Expr {
- #[expect(deprecated)]
- Expr::Wildcard {
- qualifier: None,
- options: Box::new(WildcardOptions::default()),
- }
+pub fn wildcard() -> SelectExpr {
+ SelectExpr::Wildcard(WildcardOptions::default())
}
/// Create an '*' [`Expr::Wildcard`] expression with the wildcard options
-pub fn wildcard_with_options(options: WildcardOptions) -> Expr {
- #[expect(deprecated)]
- Expr::Wildcard {
- qualifier: None,
- options: Box::new(options),
- }
+pub fn wildcard_with_options(options: WildcardOptions) -> SelectExpr {
+ SelectExpr::Wildcard(options)
}
/// Create an 't.*' [`Expr::Wildcard`] expression that matches all columns from a specific table
@@ -147,24 +140,16 @@ pub fn wildcard_with_options(options: WildcardOptions) -> Expr {
/// let p = qualified_wildcard(TableReference::bare("t"));
/// assert_eq!(p.to_string(), "t.*")
/// ```
-pub fn qualified_wildcard(qualifier: impl Into<TableReference>) -> Expr {
- #[expect(deprecated)]
- Expr::Wildcard {
- qualifier: Some(qualifier.into()),
- options: Box::new(WildcardOptions::default()),
- }
+pub fn qualified_wildcard(qualifier: impl Into<TableReference>) -> SelectExpr {
+ SelectExpr::QualifiedWildcard(qualifier.into(), WildcardOptions::default())
}
/// Create an 't.*' [`Expr::Wildcard`] expression with the wildcard options
pub fn qualified_wildcard_with_options(
qualifier: impl Into<TableReference>,
options: WildcardOptions,
-) -> Expr {
- #[expect(deprecated)]
- Expr::Wildcard {
- qualifier: Some(qualifier.into()),
- options: Box::new(options),
- }
+) -> SelectExpr {
+ SelectExpr::QualifiedWildcard(qualifier.into(), options)
}
/// Return a new expression `left <op> right`
diff --git a/datafusion/expr/src/lib.rs b/datafusion/expr/src/lib.rs
index 52286c5a7f..d951ca96b6 100644
--- a/datafusion/expr/src/lib.rs
+++ b/datafusion/expr/src/lib.rs
@@ -48,6 +48,7 @@ pub mod expr_fn;
pub mod expr_rewriter;
pub mod expr_schema;
pub mod function;
+pub mod select_expr;
pub mod groups_accumulator {
pub use datafusion_expr_common::groups_accumulator::*;
}
diff --git a/datafusion/expr/src/logical_plan/builder.rs b/datafusion/expr/src/logical_plan/builder.rs
index 605db26553..a1fa8c6483 100644
--- a/datafusion/expr/src/logical_plan/builder.rs
+++ b/datafusion/expr/src/logical_plan/builder.rs
@@ -24,7 +24,7 @@ use std::iter::once;
use std::sync::Arc;
use crate::dml::CopyTo;
-use crate::expr::{Alias, Sort as SortExpr};
+use crate::expr::{Alias, PlannedReplaceSelectItem, Sort as SortExpr};
use crate::expr_rewriter::{
coerce_plan_expr_for_schema, normalize_col,
normalize_col_with_schemas_and_ambiguity_check, normalize_cols, normalize_sorts,
@@ -36,9 +36,11 @@ use crate::logical_plan::{
Projection, Repartition, Sort, SubqueryAlias, TableScan, Union, Unnest, Values,
Window,
};
+use crate::select_expr::SelectExpr;
use crate::utils::{
- can_hash, columnize_expr, compare_sort_expr, expr_to_columns,
- find_valid_equijoin_key_pair, group_window_expr_by_sort_keys,
+ can_hash, columnize_expr, compare_sort_expr, expand_qualified_wildcard,
+ expand_wildcard, expr_to_columns, find_valid_equijoin_key_pair,
+ group_window_expr_by_sort_keys,
};
use crate::{
and, binary_expr, lit, DmlStatement, Expr, ExprSchemable, Operator, RecursiveQuery,
@@ -520,10 +522,11 @@ impl LogicalPlanBuilder {
}
Ok(plan)
}
+
/// Apply a projection without alias.
pub fn project(
self,
- expr: impl IntoIterator<Item = impl Into<Expr>>,
+ expr: impl IntoIterator<Item = impl Into<SelectExpr>>,
) -> Result<Self> {
project(Arc::unwrap_or_clone(self.plan), expr).map(Self::new)
}
@@ -532,7 +535,7 @@ impl LogicalPlanBuilder {
/// (true to validate, false to not validate)
pub fn project_with_validation(
self,
- expr: Vec<(impl Into<Expr>, bool)>,
+ expr: Vec<(impl Into<SelectExpr>, bool)>,
) -> Result<Self> {
project_with_validation(Arc::unwrap_or_clone(self.plan), expr).map(Self::new)
}
@@ -1657,7 +1660,7 @@ pub fn union_by_name(
/// * An invalid expression is used (e.g. a `sort` expression)
pub fn project(
plan: LogicalPlan,
- expr: impl IntoIterator<Item = impl Into<Expr>>,
+ expr: impl IntoIterator<Item = impl Into<SelectExpr>>,
) -> Result<LogicalPlan> {
project_with_validation(plan, expr.into_iter().map(|e| (e, true)))
}
@@ -1671,15 +1674,54 @@ pub fn project(
/// * An invalid expression is used (e.g. a `sort` expression)
fn project_with_validation(
plan: LogicalPlan,
- expr: impl IntoIterator<Item = (impl Into<Expr>, bool)>,
+ expr: impl IntoIterator<Item = (impl Into<SelectExpr>, bool)>,
) -> Result<LogicalPlan> {
let mut projected_expr = vec![];
for (e, validate) in expr {
let e = e.into();
match e {
- #[expect(deprecated)]
- Expr::Wildcard { .. } => projected_expr.push(e),
- _ => {
+ SelectExpr::Wildcard(opt) => {
+ let expanded = expand_wildcard(plan.schema(), &plan, Some(&opt))?;
+
+ // If there is a REPLACE statement, replace that column with the given
+ // replace expression. Column name remains the same.
+ let expanded = if let Some(replace) = opt.replace {
+ replace_columns(expanded, &replace)?
+ } else {
+ expanded
+ };
+
+ for e in expanded {
+ if validate {
+ projected_expr
+ .push(columnize_expr(normalize_col(e, &plan)?, &plan)?)
+ } else {
+ projected_expr.push(e)
+ }
+ }
+ }
+ SelectExpr::QualifiedWildcard(table_ref, opt) => {
+ let expanded =
+ expand_qualified_wildcard(&table_ref, plan.schema(), Some(&opt))?;
+
+ // If there is a REPLACE statement, replace that column with the given
+ // replace expression. Column name remains the same.
+ let expanded = if let Some(replace) = opt.replace {
+ replace_columns(expanded, &replace)?
+ } else {
+ expanded
+ };
+
+ for e in expanded {
+ if validate {
+ projected_expr
+ .push(columnize_expr(normalize_col(e, &plan)?, &plan)?)
+ } else {
+ projected_expr.push(e)
+ }
+ }
+ }
+ SelectExpr::Expression(e) => {
if validate {
projected_expr.push(columnize_expr(normalize_col(e, &plan)?, &plan)?)
} else {
@@ -1693,6 +1735,29 @@ fn project_with_validation(
Projection::try_new(projected_expr, Arc::new(plan)).map(LogicalPlan::Projection)
}
+/// If there is a REPLACE statement in the projected expression in the form of
+/// "REPLACE (some_column_within_an_expr AS some_column)", this function replaces
+/// that column with the given replace expression. Column name remains the same.
+/// Multiple REPLACEs are also possible with comma separations.
+fn replace_columns(
+ mut exprs: Vec<Expr>,
+ replace: &PlannedReplaceSelectItem,
+) -> Result<Vec<Expr>> {
+ for expr in exprs.iter_mut() {
+ if let Expr::Column(Column { name, .. }) = expr {
+ if let Some((_, new_expr)) = replace
+ .items()
+ .iter()
+ .zip(replace.expressions().iter())
+ .find(|(item, _)| item.column_name.value == *name)
+ {
+ *expr = new_expr.clone().alias(name.clone())
+ }
+ }
+ }
+ Ok(exprs)
+}
+
/// Create a SubqueryAlias to wrap a LogicalPlan.
pub fn subquery_alias(
plan: LogicalPlan,
@@ -1811,7 +1876,7 @@ pub fn wrap_projection_for_join_if_necessary(
projection.extend(join_key_items);
LogicalPlanBuilder::from(input)
- .project(projection)?
+ .project(projection.into_iter().map(SelectExpr::from))?
.build()?
} else {
input
diff --git a/datafusion/expr/src/select_expr.rs b/datafusion/expr/src/select_expr.rs
new file mode 100644
index 0000000000..039df20f39
--- /dev/null
+++ b/datafusion/expr/src/select_expr.rs
@@ -0,0 +1,101 @@
+// 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::fmt;
+
+use arrow::datatypes::FieldRef;
+use datafusion_common::{Column, TableReference};
+
+use crate::{expr::WildcardOptions, Expr};
+
+/// Represents a SELECT expression in a SQL query.
+///
+/// `SelectExpr` supports three types of expressions commonly found in the SELECT clause:
+///
+/// * Wildcard (`*`) - Selects all columns
+/// * Qualified wildcard (`table.*`) - Selects all columns from a specific table
+/// * Regular expression - Any other expression like columns, functions, literals etc.
+///
+/// This enum is typically used when you need to handle wildcards. After expanding `*` in the query,
+/// you can use `Expr` for all other expressions.
+///
+/// # Examples
+///
+/// ```
+/// use datafusion_expr::col;
+/// use datafusion_expr::expr::WildcardOptions;
+/// use datafusion_expr::select_expr::SelectExpr;
+///
+/// // SELECT *
+/// let wildcard = SelectExpr::Wildcard(WildcardOptions::default());
+///
+/// // SELECT mytable.*
+/// let qualified = SelectExpr::QualifiedWildcard(
+/// "mytable".into(),
+/// WildcardOptions::default()
+/// );
+///
+/// // SELECT col1
+/// let expr = SelectExpr::Expression(col("col1").into());
+/// ```
+#[derive(Clone, Debug)]
+pub enum SelectExpr {
+ /// Represents a wildcard (`*`) that selects all columns from all tables.
+ /// The `WildcardOptions` control additional behavior like exclusions.
+ Wildcard(WildcardOptions),
+
+ /// Represents a qualified wildcard (`table.*`) that selects all columns from a specific table.
+ /// The `TableReference` specifies the table and `WildcardOptions` control additional behavior.
+ QualifiedWildcard(TableReference, WildcardOptions),
+
+ /// Represents any other valid SELECT expression like column references,
+ /// function calls, literals, etc.
+ Expression(Expr),
+}
+
+impl fmt::Display for SelectExpr {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ match self {
+ SelectExpr::Wildcard(opt) => write!(f, "*{opt}"),
+ SelectExpr::QualifiedWildcard(table, opt) => write!(f, "{table}.*{opt}"),
+ SelectExpr::Expression(expr) => write!(f, "{expr}"),
+ }
+ }
+}
+
+impl From<Expr> for SelectExpr {
+ fn from(expr: Expr) -> Self {
+ SelectExpr::Expression(expr)
+ }
+}
+
+/// Create an [`SelectExpr::Expression`] from a [`Column`]
+impl From<Column> for SelectExpr {
+ fn from(value: Column) -> Self {
+ Expr::Column(value).into()
+ }
+}
+
+/// Create an [`SelectExpr::Expression`] from an optional qualifier and a [`FieldRef`]. This is
+/// useful for creating [`SelectExpr::Expression`] from a `DFSchema`.
+///
+/// See example on [`Expr`]
+impl<'a> From<(Option<&'a TableReference>, &'a FieldRef)> for SelectExpr {
+ fn from(value: (Option<&'a TableReference>, &'a FieldRef)) -> Self {
+ Expr::from(Column::from(value)).into()
+ }
+}
diff --git a/datafusion/proto/tests/cases/roundtrip_logical_plan.rs b/datafusion/proto/tests/cases/roundtrip_logical_plan.rs
index 9cc7514a0d..9fa1f74ae1 100644
--- a/datafusion/proto/tests/cases/roundtrip_logical_plan.rs
+++ b/datafusion/proto/tests/cases/roundtrip_logical_plan.rs
@@ -67,7 +67,7 @@ use datafusion_common::{
use datafusion_expr::dml::CopyTo;
use datafusion_expr::expr::{
self, Between, BinaryExpr, Case, Cast, GroupingSet, InList, Like, ScalarFunction,
- Unnest,
+ Unnest, WildcardOptions,
};
use datafusion_expr::logical_plan::{Extension, UserDefinedLogicalNodeCore};
use datafusion_expr::{
@@ -2029,7 +2029,11 @@ fn roundtrip_unnest() {
#[test]
fn roundtrip_wildcard() {
- let test_expr = wildcard();
+ #[expect(deprecated)]
+ let test_expr = Expr::Wildcard {
+ qualifier: None,
+ options: Box::new(WildcardOptions::default()),
+ };
let ctx = SessionContext::new();
roundtrip_expr_test(test_expr, ctx);
@@ -2037,7 +2041,11 @@ fn roundtrip_wildcard() {
#[test]
fn roundtrip_qualified_wildcard() {
- let test_expr = qualified_wildcard("foo");
+ #[expect(deprecated)]
+ let test_expr = Expr::Wildcard {
+ qualifier: Some("foo".into()),
+ options: Box::new(WildcardOptions::default()),
+ };
let ctx = SessionContext::new();
roundtrip_expr_test(test_expr, ctx);
diff --git a/datafusion/sql/src/expr/function.rs b/datafusion/sql/src/expr/function.rs
index cdf61183eb..b77bfab96a 100644
--- a/datafusion/sql/src/expr/function.rs
+++ b/datafusion/sql/src/expr/function.rs
@@ -22,11 +22,10 @@ use datafusion_common::{
internal_datafusion_err, internal_err, not_impl_err, plan_datafusion_err, plan_err,
DFSchema, Dependency, Diagnostic, Result, Span,
};
-use datafusion_expr::expr::{ScalarFunction, Unnest};
+use datafusion_expr::expr::{ScalarFunction, Unnest, WildcardOptions};
use datafusion_expr::planner::{PlannerResult, RawAggregateExpr, RawWindowExpr};
use datafusion_expr::{
- expr, qualified_wildcard, wildcard, Expr, ExprFunctionExt, ExprSchemable,
- WindowFrame, WindowFunctionDefinition,
+ expr, Expr, ExprFunctionExt, ExprSchemable, WindowFrame, WindowFunctionDefinition,
};
use sqlparser::ast::{
DuplicateTreatment, Expr as SQLExpr, Function as SQLFunction, FunctionArg,
@@ -473,11 +472,27 @@ impl<S: ContextProvider> SqlToRel<'_, S> {
name: _,
arg: FunctionArgExpr::Wildcard,
operator: _,
- } => Ok(wildcard()),
+ } => {
+ #[expect(deprecated)]
+ let expr = Expr::Wildcard {
+ qualifier: None,
+ options: Box::new(WildcardOptions::default()),
+ };
+
+ Ok(expr)
+ }
FunctionArg::Unnamed(FunctionArgExpr::Expr(arg)) => {
self.sql_expr_to_logical_expr(arg, schema, planner_context)
}
- FunctionArg::Unnamed(FunctionArgExpr::Wildcard) => Ok(wildcard()),
+ FunctionArg::Unnamed(FunctionArgExpr::Wildcard) => {
+ #[expect(deprecated)]
+ let expr = Expr::Wildcard {
+ qualifier: None,
+ options: Box::new(WildcardOptions::default()),
+ };
+
+ Ok(expr)
+ }
FunctionArg::Unnamed(FunctionArgExpr::QualifiedWildcard(object_name)) => {
let qualifier = self.object_name_to_table_reference(object_name)?;
// Sanity check on qualifier with schema
@@ -485,7 +500,14 @@ impl<S: ContextProvider> SqlToRel<'_, S> {
if qualified_indices.is_empty() {
return plan_err!("Invalid qualifier {qualifier}");
}
- Ok(qualified_wildcard(qualifier))
+
+ #[expect(deprecated)]
+ let expr = Expr::Wildcard {
+ qualifier: qualifier.into(),
+ options: Box::new(WildcardOptions::default()),
+ };
+
+ Ok(expr)
}
_ => not_impl_err!("Unsupported qualified wildcard argument: {sql:?}"),
}
diff --git a/datafusion/sql/src/select.rs b/datafusion/sql/src/select.rs
index ce9c5d2f7c..e9cf4ce48a 100644
--- a/datafusion/sql/src/select.rs
+++ b/datafusion/sql/src/select.rs
@@ -27,15 +27,15 @@ use crate::utils::{
use datafusion_common::error::DataFusionErrorBuilder;
use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion};
-use datafusion_common::{not_impl_err, plan_err, Column, Result};
+use datafusion_common::{not_impl_err, plan_err, Result};
use datafusion_common::{RecursionUnnestOption, UnnestOptions};
use datafusion_expr::expr::{Alias, PlannedReplaceSelectItem, WildcardOptions};
use datafusion_expr::expr_rewriter::{
normalize_col, normalize_col_with_schemas_and_ambiguity_check, normalize_sorts,
};
+use datafusion_expr::select_expr::SelectExpr;
use datafusion_expr::utils::{
- expand_qualified_wildcard, expand_wildcard, expr_as_column_expr, expr_to_columns,
- find_aggregate_exprs, find_window_exprs,
+ expr_as_column_expr, expr_to_columns, find_aggregate_exprs, find_window_exprs,
};
use datafusion_expr::{
Aggregate, Expr, Filter, GroupingSet, LogicalPlan, LogicalPlanBuilder,
@@ -92,14 +92,9 @@ impl<S: ContextProvider> SqlToRel<'_, S> {
planner_context,
)?;
- // TOOD: remove this after Expr::Wildcard is removed
- #[allow(deprecated)]
- for expr in &select_exprs {
- debug_assert!(!matches!(expr, Expr::Wildcard { .. }));
- }
-
// Having and group by clause may reference aliases defined in select projection
- let projected_plan = self.project(base_plan.clone(), select_exprs.clone())?;
+ let projected_plan = self.project(base_plan.clone(), select_exprs)?;
+ let select_exprs = projected_plan.expressions();
// Place the fields of the base plan at the front so that when there are references
// with the same name, the fields of the base plan will be searched first.
@@ -584,12 +579,12 @@ impl<S: ContextProvider> SqlToRel<'_, S> {
projection: Vec<SelectItem>,
empty_from: bool,
planner_context: &mut PlannerContext,
- ) -> Result<Vec<Expr>> {
+ ) -> Result<Vec<SelectExpr>> {
let mut prepared_select_exprs = vec![];
let mut error_builder = DataFusionErrorBuilder::new();
for expr in projection {
match self.sql_select_to_rex(expr, plan, empty_from, planner_context) {
- Ok(expr) => prepared_select_exprs.extend(expr),
+ Ok(expr) => prepared_select_exprs.push(expr),
Err(err) => error_builder.add_error(err),
}
}
@@ -603,7 +598,7 @@ impl<S: ContextProvider> SqlToRel<'_, S> {
plan: &LogicalPlan,
empty_from: bool,
planner_context: &mut PlannerContext,
- ) -> Result<Vec<Expr>> {
+ ) -> Result<SelectExpr> {
match sql {
SelectItem::UnnamedExpr(expr) => {
let expr = self.sql_to_expr(expr, plan.schema(), planner_context)?;
@@ -612,7 +607,8 @@ impl<S: ContextProvider> SqlToRel<'_, S> {
&[&[plan.schema()]],
&plan.using_columns()?,
)?;
- Ok(vec![col])
+
+ Ok(SelectExpr::Expression(col))
}
SelectItem::ExprWithAlias { expr, alias } => {
let select_expr =
@@ -628,7 +624,8 @@ impl<S: ContextProvider> SqlToRel<'_, S> {
Expr::Column(column) if column.name.eq(&name) => col,
_ => col.alias(name),
};
- Ok(vec![expr])
+
+ Ok(SelectExpr::Expression(expr))
}
SelectItem::Wildcard(options) => {
Self::check_wildcard_options(&options)?;
@@ -642,16 +639,7 @@ impl<S: ContextProvider> SqlToRel<'_, S> {
options,
)?;
- let expanded =
- expand_wildcard(plan.schema(), plan, Some(&planned_options))?;
-
- // If there is a REPLACE statement, replace that column with the given
- // replace expression. Column name remains the same.
- if let Some(replace) = planned_options.replace {
- replace_columns(expanded, &replace)
- } else {
- Ok(expanded)
- }
+ Ok(SelectExpr::Wildcard(planned_options))
}
SelectItem::QualifiedWildcard(object_name, options) => {
Self::check_wildcard_options(&options)?;
@@ -663,18 +651,7 @@ impl<S: ContextProvider> SqlToRel<'_, S> {
options,
)?;
- let expanded = expand_qualified_wildcard(
- &qualifier,
- plan.schema(),
- Some(&planned_options),
- )?;
- // If there is a REPLACE statement, replace that column with the given
- // replace expression. Column name remains the same.
- if let Some(replace) = planned_options.replace {
- replace_columns(expanded, &replace)
- } else {
- Ok(expanded)
- }
+ Ok(SelectExpr::QualifiedWildcard(qualifier, planned_options))
}
}
}
@@ -728,8 +705,12 @@ impl<S: ContextProvider> SqlToRel<'_, S> {
})
.collect::<Result<Vec<_>>>()?
.into_iter()
- .flatten()
- .collect();
+ .filter_map(|expr| match expr {
+ SelectExpr::Expression(expr) => Some(expr),
+ _ => None,
+ })
+ .collect::<Vec<_>>();
+
let planned_replace = PlannedReplaceSelectItem {
items: replace.items.into_iter().map(|i| *i).collect(),
planned_expressions: replace_expr,
@@ -741,8 +722,17 @@ impl<S: ContextProvider> SqlToRel<'_, S> {
}
/// Wrap a plan in a projection
- fn project(&self, input: LogicalPlan, expr: Vec<Expr>) -> Result<LogicalPlan> {
- self.validate_schema_satisfies_exprs(input.schema(), &expr)?;
+ fn project(&self, input: LogicalPlan, expr: Vec<SelectExpr>) -> Result<LogicalPlan> {
+ // convert to Expr for validate_schema_satisfies_exprs
+ let exprs = expr
+ .iter()
+ .filter_map(|e| match e {
+ SelectExpr::Expression(expr) => Some(expr.to_owned()),
+ _ => None,
+ })
+ .collect::<Vec<_>>();
+ self.validate_schema_satisfies_exprs(input.schema(), &exprs)?;
+
LogicalPlanBuilder::from(input).project(expr)?.build()
}
@@ -915,26 +905,3 @@ fn match_window_definitions(
}
Ok(())
}
-
-/// If there is a REPLACE statement in the projected expression in the form of
-/// "REPLACE (some_column_within_an_expr AS some_column)", this function replaces
-/// that column with the given replace expression. Column name remains the same.
-/// Multiple REPLACEs are also possible with comma separations.
-fn replace_columns(
- mut exprs: Vec<Expr>,
- replace: &PlannedReplaceSelectItem,
-) -> Result<Vec<Expr>> {
- for expr in exprs.iter_mut() {
- if let Expr::Column(Column { name, .. }) = expr {
- if let Some((_, new_expr)) = replace
- .items()
- .iter()
- .zip(replace.expressions().iter())
- .find(|(item, _)| item.column_name.value == *name)
- {
- *expr = new_expr.clone().alias(name.clone())
- }
- }
- }
- Ok(exprs)
-}
diff --git a/datafusion/sql/src/statement.rs b/datafusion/sql/src/statement.rs
index b4e378a724..1d0dd2390f 100644
--- a/datafusion/sql/src/statement.rs
+++ b/datafusion/sql/src/statement.rs
@@ -437,6 +437,7 @@ impl<S: ContextProvider> SqlToRel<'_, S> {
.alias(field.name())
})
.collect::<Vec<_>>();
+
LogicalPlanBuilder::from(plan.clone())
.project(project_exprs)?
.build()?
diff --git a/datafusion/sql/src/unparser/expr.rs b/datafusion/sql/src/unparser/expr.rs
index bf63613127..45c3e1c03d 100644
--- a/datafusion/sql/src/unparser/expr.rs
+++ b/datafusion/sql/src/unparser/expr.rs
@@ -1661,8 +1661,8 @@ mod tests {
use datafusion_expr::{
case, cast, col, cube, exists, grouping_set, interval_datetime_lit,
interval_year_month_lit, lit, not, not_exists, out_ref_col, placeholder, rollup,
- table_scan, try_cast, when, wildcard, ScalarUDF, ScalarUDFImpl, Signature,
- Volatility, WindowFrame, WindowFunctionDefinition,
+ table_scan, try_cast, when, ScalarUDF, ScalarUDFImpl, Signature, Volatility,
+ WindowFrame, WindowFunctionDefinition,
};
use datafusion_expr::{interval_month_day_nano_lit, ExprFunctionExt};
use datafusion_functions::expr_fn::{get_field, named_struct};
@@ -1913,16 +1913,24 @@ mod tests {
),
(sum(col("a")), r#"sum(a)"#),
(
+ #[expect(deprecated)]
count_udaf()
- .call(vec![wildcard()])
+ .call(vec![Expr::Wildcard {
+ qualifier: None,
+ options: Box::new(WildcardOptions::default()),
+ }])
.distinct()
.build()
.unwrap(),
"count(DISTINCT *)",
),
(
+ #[expect(deprecated)]
count_udaf()
- .call(vec![wildcard()])
+ .call(vec![Expr::Wildcard {
+ qualifier: None,
+ options: Box::new(WildcardOptions::default()),
+ }])
.filter(lit(true))
.build()
.unwrap(),
@@ -1942,10 +1950,14 @@ mod tests {
r#"row_number(col) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)"#,
),
(
+ #[expect(deprecated)]
Expr::WindowFunction(WindowFunction {
fun: WindowFunctionDefinition::AggregateUDF(count_udaf()),
params: WindowFunctionParams {
- args: vec![wildcard()],
+ args: vec![Expr::Wildcard {
+ qualifier: None,
+ options: Box::new(WildcardOptions::default()),
+ }],
partition_by: vec![],
order_by: vec![Sort::new(col("a"), false, true)],
window_frame: WindowFrame::new_bounds(
diff --git a/datafusion/sql/tests/cases/plan_to_sql.rs b/datafusion/sql/tests/cases/plan_to_sql.rs
index 8599de8646..0abc890dfa 100644
--- a/datafusion/sql/tests/cases/plan_to_sql.rs
+++ b/datafusion/sql/tests/cases/plan_to_sql.rs
@@ -1090,7 +1090,7 @@ fn test_table_scan_pushdown() -> Result<()> {
plan_to_sql(&query_from_table_scan_with_two_projections)?;
assert_eq!(
query_from_table_scan_with_two_projections.to_string(),
- "SELECT * FROM (SELECT t1.id, t1.age FROM t1)"
+ "SELECT t1.id, t1.age FROM (SELECT t1.id, t1.age FROM t1)"
);
let table_scan_with_filter = table_scan_with_filters(
diff --git a/datafusion/sqllogictest/test_files/select.slt b/datafusion/sqllogictest/test_files/select.slt
index d5e0c44976..a2f1657e40 100644
--- a/datafusion/sqllogictest/test_files/select.slt
+++ b/datafusion/sqllogictest/test_files/select.slt
@@ -1855,3 +1855,19 @@ select * from t a, t b where id = id + 1;
statement count 0
drop table t;
+
+
+# test wildcard + other columns
+statement count 0
+create table t(a int) as values (1), (2), (3), (1);
+
+query II
+select *, count(*) over() as ta from t;
+----
+1 4
+2 4
+3 4
+1 4
+
+query
+drop table t;
\ No newline at end of file