Skip to content

Apache DataFusion SQL Query Engine

Fix `plan_to_sql`: Add wildcard projection to SELECT statement if no projection was set (#11744)

Yasser Latreche1ce546168de2
diff --git a/datafusion/sql/src/unparser/plan.rs b/datafusion/sql/src/unparser/plan.rs
index b30e109881..e08f25d3c2 100644
--- a/datafusion/sql/src/unparser/plan.rs
+++ b/datafusion/sql/src/unparser/plan.rs
@@ -142,6 +142,14 @@ impl Unparser<'_> {
return Ok(*body);
}
+ // If no projection is set, add a wildcard projection to the select
+ // which will be translated to `SELECT *` in the SQL statement
+ if !select_builder.already_projected() {
+ select_builder.projection(vec![ast::SelectItem::Wildcard(
+ ast::WildcardAdditionalOptions::default(),
+ )]);
+ }
+
let mut twj = select_builder.pop_from().unwrap();
twj.relation(relation_builder);
select_builder.push_from(twj);
diff --git a/datafusion/sql/tests/cases/plan_to_sql.rs b/datafusion/sql/tests/cases/plan_to_sql.rs
index a52333e54f..d1ac7a0c96 100644
--- a/datafusion/sql/tests/cases/plan_to_sql.rs
+++ b/datafusion/sql/tests/cases/plan_to_sql.rs
@@ -449,6 +449,30 @@ fn test_table_references_in_plan_to_sql() {
);
}
+#[test]
+fn test_table_scan_with_no_projection_in_plan_to_sql() {
+ fn test(table_name: &str, expected_sql: &str) {
+ let schema = Schema::new(vec![
+ Field::new("id", DataType::Utf8, false),
+ Field::new("value", DataType::Utf8, false),
+ ]);
+
+ let plan = table_scan(Some(table_name), &schema, None)
+ .unwrap()
+ .build()
+ .unwrap();
+ let sql = plan_to_sql(&plan).unwrap();
+ assert_eq!(format!("{}", sql), expected_sql)
+ }
+
+ test(
+ "catalog.schema.table",
+ "SELECT * FROM catalog.\"schema\".\"table\"",
+ );
+ test("schema.table", "SELECT * FROM \"schema\".\"table\"");
+ test("table", "SELECT * FROM \"table\"");
+}
+
#[test]
fn test_pretty_roundtrip() -> Result<()> {
let schema = Schema::new(vec![