Skip to content

Apache DataFusion SQL Query Engine

WITH ORDER support on CREATE EXTERNAL TABLE (#5618)

Metehan Yıldırım01e5b80730c7
diff --git a/datafusion/core/src/catalog/listing_schema.rs b/datafusion/core/src/catalog/listing_schema.rs
index 3ea7a1098f..b39c3693c7 100644
--- a/datafusion/core/src/catalog/listing_schema.rs
+++ b/datafusion/core/src/catalog/listing_schema.rs
@@ -144,6 +144,7 @@ impl ListingSchemaProvider {
if_not_exists: false,
definition: None,
file_compression_type: CompressionTypeVariant::UNCOMPRESSED,
+ order_exprs: vec![],
options: Default::default(),
},
)
diff --git a/datafusion/core/src/datasource/listing_table_factory.rs b/datafusion/core/src/datasource/listing_table_factory.rs
index 8b7dd46a8f..6c7b058520 100644
--- a/datafusion/core/src/datasource/listing_table_factory.rs
+++ b/datafusion/core/src/datasource/listing_table_factory.rs
@@ -124,12 +124,18 @@ impl TableProviderFactory for ListingTableFactory {
(Some(schema), table_partition_cols)
};
+ let file_sort_order = if cmd.order_exprs.is_empty() {
+ None
+ } else {
+ Some(cmd.order_exprs.clone())
+ };
+
let options = ListingOptions::new(file_format)
.with_collect_stat(state.config().collect_statistics())
.with_file_extension(file_extension)
.with_target_partitions(state.config().target_partitions())
.with_table_partition_cols(table_partition_cols)
- .with_file_sort_order(None);
+ .with_file_sort_order(file_sort_order);
let table_path = ListingTableUrl::parse(&cmd.location)?;
let resolved_schema = match provided_schema {
diff --git a/datafusion/core/tests/sql/order.rs b/datafusion/core/tests/sql/order.rs
index e29904c214..da7663cb8b 100644
--- a/datafusion/core/tests/sql/order.rs
+++ b/datafusion/core/tests/sql/order.rs
@@ -16,6 +16,9 @@
// under the License.
use super::*;
+use datafusion::datasource::datasource::TableProviderFactory;
+use datafusion::datasource::listing::ListingTable;
+use datafusion::datasource::listing_table_factory::ListingTableFactory;
use test_utils::{batches_to_vec, partitions_to_sorted_vec};
#[tokio::test]
@@ -40,6 +43,56 @@ async fn sort_with_lots_of_repetition_values() -> Result<()> {
Ok(())
}
+#[tokio::test]
+async fn create_external_table_with_order() -> Result<()> {
+ let ctx = SessionContext::new();
+ let sql = "CREATE EXTERNAL TABLE dt (a_id integer, a_str string, a_bool boolean) STORED AS CSV WITH ORDER (a_id ASC) LOCATION 'file://path/to/table';";
+ if let LogicalPlan::CreateExternalTable(cmd) =
+ ctx.state().create_logical_plan(sql).await?
+ {
+ let listing_table_factory = Arc::new(ListingTableFactory::new());
+ let table_dyn = listing_table_factory.create(&ctx.state(), &cmd).await?;
+ let table = table_dyn.as_any().downcast_ref::<ListingTable>().unwrap();
+ assert_eq!(cmd.order_exprs.len(), 1);
+ assert_eq!(
+ &cmd.order_exprs,
+ table.options().file_sort_order.as_ref().unwrap()
+ )
+ } else {
+ panic!("Wrong command")
+ }
+ Ok(())
+}
+
+#[tokio::test]
+async fn create_external_table_with_ddl_ordered_non_cols() -> Result<()> {
+ let ctx = SessionContext::new();
+ let sql = "CREATE EXTERNAL TABLE dt (a_id integer, a_str string, a_bool boolean) STORED AS CSV WITH ORDER (a ASC) LOCATION 'file://path/to/table';";
+ match ctx.state().create_logical_plan(sql).await {
+ Ok(_) => panic!("Expecting error."),
+ Err(e) => {
+ assert_eq!(
+ e.to_string(),
+ "Error during planning: Column a is not in schema"
+ )
+ }
+ }
+ Ok(())
+}
+
+#[tokio::test]
+async fn create_external_table_with_ddl_ordered_without_schema() -> Result<()> {
+ let ctx = SessionContext::new();
+ let sql = "CREATE EXTERNAL TABLE dt STORED AS CSV WITH ORDER (a ASC) LOCATION 'file://path/to/table';";
+ match ctx.state().create_logical_plan(sql).await {
+ Ok(_) => panic!("Expecting error."),
+ Err(e) => {
+ assert_eq!(e.to_string(), "Error during planning: Provide a schema before specifying the order while creating a table.")
+ }
+ }
+ Ok(())
+}
+
#[tokio::test]
async fn sort_with_duplicate_sort_exprs() -> Result<()> {
let ctx = SessionContext::new();
diff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rs
index 5c93bb6f2d..237e7a81c5 100644
--- a/datafusion/expr/src/logical_plan/plan.rs
+++ b/datafusion/expr/src/logical_plan/plan.rs
@@ -1631,6 +1631,8 @@ pub struct CreateExternalTable {
pub if_not_exists: bool,
/// SQL used to create the table, if available
pub definition: Option<String>,
+ /// Order expressions supplied by user
+ pub order_exprs: Vec<Expr>,
/// File compression type (GZIP, BZIP2, XZ, ZSTD)
pub file_compression_type: CompressionTypeVariant,
/// Table(provider) specific options
@@ -1651,6 +1653,7 @@ impl Hash for CreateExternalTable {
self.if_not_exists.hash(state);
self.definition.hash(state);
self.file_compression_type.hash(state);
+ self.order_exprs.hash(state);
self.options.len().hash(state); // HashMap is not hashable
}
}
diff --git a/datafusion/proto/proto/datafusion.proto b/datafusion/proto/proto/datafusion.proto
index 93ae09194d..76ec5b0017 100644
--- a/datafusion/proto/proto/datafusion.proto
+++ b/datafusion/proto/proto/datafusion.proto
@@ -183,6 +183,7 @@ message CreateExternalTableNode {
string delimiter = 8;
string definition = 9;
string file_compression_type = 10;
+ repeated LogicalExprNode order_exprs = 13;
map<string, string> options = 11;
}
diff --git a/datafusion/proto/src/generated/pbjson.rs b/datafusion/proto/src/generated/pbjson.rs
index 0ccb62fc94..406d9ee27a 100644
--- a/datafusion/proto/src/generated/pbjson.rs
+++ b/datafusion/proto/src/generated/pbjson.rs
@@ -3362,6 +3362,9 @@ impl serde::Serialize for CreateExternalTableNode {
if !self.file_compression_type.is_empty() {
len += 1;
}
+ if !self.order_exprs.is_empty() {
+ len += 1;
+ }
if !self.options.is_empty() {
len += 1;
}
@@ -3396,6 +3399,9 @@ impl serde::Serialize for CreateExternalTableNode {
if !self.file_compression_type.is_empty() {
struct_ser.serialize_field("fileCompressionType", &self.file_compression_type)?;
}
+ if !self.order_exprs.is_empty() {
+ struct_ser.serialize_field("orderExprs", &self.order_exprs)?;
+ }
if !self.options.is_empty() {
struct_ser.serialize_field("options", &self.options)?;
}
@@ -3424,6 +3430,8 @@ impl<'de> serde::Deserialize<'de> for CreateExternalTableNode {
"definition",
"file_compression_type",
"fileCompressionType",
+ "order_exprs",
+ "orderExprs",
"options",
];
@@ -3439,6 +3447,7 @@ impl<'de> serde::Deserialize<'de> for CreateExternalTableNode {
Delimiter,
Definition,
FileCompressionType,
+ OrderExprs,
Options,
}
impl<'de> serde::Deserialize<'de> for GeneratedField {
@@ -3471,6 +3480,7 @@ impl<'de> serde::Deserialize<'de> for CreateExternalTableNode {
"delimiter" => Ok(GeneratedField::Delimiter),
"definition" => Ok(GeneratedField::Definition),
"fileCompressionType" | "file_compression_type" => Ok(GeneratedField::FileCompressionType),
+ "orderExprs" | "order_exprs" => Ok(GeneratedField::OrderExprs),
"options" => Ok(GeneratedField::Options),
_ => Err(serde::de::Error::unknown_field(value, FIELDS)),
}
@@ -3501,6 +3511,7 @@ impl<'de> serde::Deserialize<'de> for CreateExternalTableNode {
let mut delimiter__ = None;
let mut definition__ = None;
let mut file_compression_type__ = None;
+ let mut order_exprs__ = None;
let mut options__ = None;
while let Some(k) = map.next_key()? {
match k {
@@ -3564,6 +3575,12 @@ impl<'de> serde::Deserialize<'de> for CreateExternalTableNode {
}
file_compression_type__ = Some(map.next_value()?);
}
+ GeneratedField::OrderExprs => {
+ if order_exprs__.is_some() {
+ return Err(serde::de::Error::duplicate_field("orderExprs"));
+ }
+ order_exprs__ = Some(map.next_value()?);
+ }
GeneratedField::Options => {
if options__.is_some() {
return Err(serde::de::Error::duplicate_field("options"));
@@ -3585,6 +3602,7 @@ impl<'de> serde::Deserialize<'de> for CreateExternalTableNode {
delimiter: delimiter__.unwrap_or_default(),
definition: definition__.unwrap_or_default(),
file_compression_type: file_compression_type__.unwrap_or_default(),
+ order_exprs: order_exprs__.unwrap_or_default(),
options: options__.unwrap_or_default(),
})
}
diff --git a/datafusion/proto/src/generated/prost.rs b/datafusion/proto/src/generated/prost.rs
index 6209989def..e5b4534f60 100644
--- a/datafusion/proto/src/generated/prost.rs
+++ b/datafusion/proto/src/generated/prost.rs
@@ -291,6 +291,8 @@ pub struct CreateExternalTableNode {
pub definition: ::prost::alloc::string::String,
#[prost(string, tag = "10")]
pub file_compression_type: ::prost::alloc::string::String,
+ #[prost(message, repeated, tag = "13")]
+ pub order_exprs: ::prost::alloc::vec::Vec<LogicalExprNode>,
#[prost(map = "string, string", tag = "11")]
pub options: ::std::collections::HashMap<
::prost::alloc::string::String,
diff --git a/datafusion/proto/src/logical_plan/mod.rs b/datafusion/proto/src/logical_plan/mod.rs
index cce62653b6..2a8d24d410 100644
--- a/datafusion/proto/src/logical_plan/mod.rs
+++ b/datafusion/proto/src/logical_plan/mod.rs
@@ -510,6 +510,12 @@ impl AsLogicalPlan for LogicalPlanNode {
)))?
}
+ let order_exprs = create_extern_table
+ .order_exprs
+ .iter()
+ .map(|expr| from_proto::parse_expr(expr, ctx))
+ .collect::<Result<Vec<Expr>, _>>()?;
+
Ok(LogicalPlan::CreateExternalTable(CreateExternalTable {
schema: pb_schema.try_into()?,
name: from_owned_table_reference(create_extern_table.name.as_ref(), "CreateExternalTable")?,
@@ -522,6 +528,7 @@ impl AsLogicalPlan for LogicalPlanNode {
table_partition_cols: create_extern_table
.table_partition_cols
.clone(),
+ order_exprs,
if_not_exists: create_extern_table.if_not_exists,
file_compression_type: CompressionTypeVariant::from_str(&create_extern_table.file_compression_type).map_err(|_| DataFusionError::NotImplemented(format!("Unsupported file compression type {}", create_extern_table.file_compression_type)))?,
definition,
@@ -1174,6 +1181,7 @@ impl AsLogicalPlan for LogicalPlanNode {
if_not_exists,
definition,
file_compression_type,
+ order_exprs,
options,
}) => Ok(protobuf::LogicalPlanNode {
logical_plan_type: Some(LogicalPlanType::CreateExternalTable(
@@ -1186,6 +1194,10 @@ impl AsLogicalPlan for LogicalPlanNode {
table_partition_cols: table_partition_cols.clone(),
if_not_exists: *if_not_exists,
delimiter: String::from(*delimiter),
+ order_exprs: order_exprs
+ .iter()
+ .map(|expr| expr.try_into())
+ .collect::<Result<Vec<_>, to_proto::Error>>()?,
definition: definition.clone().unwrap_or_default(),
file_compression_type: file_compression_type.to_string(),
options: options.clone(),
diff --git a/datafusion/sql/src/parser.rs b/datafusion/sql/src/parser.rs
index 521466214f..27bfa32501 100644
--- a/datafusion/sql/src/parser.rs
+++ b/datafusion/sql/src/parser.rs
@@ -18,6 +18,7 @@
//! DataFusion SQL Parser based on [`sqlparser`]
use datafusion_common::parsers::CompressionTypeVariant;
+use sqlparser::ast::OrderByExpr;
use sqlparser::{
ast::{
ColumnDef, ColumnOptionDef, ObjectName, Statement as SQLStatement,
@@ -58,6 +59,8 @@ pub struct CreateExternalTable {
pub location: String,
/// Partition Columns
pub table_partition_cols: Vec<String>,
+ /// Ordered expressions
+ pub order_exprs: Vec<OrderByExpr>,
/// Option to not error if table already exists
pub if_not_exists: bool,
/// File compression type (GZIP, BZIP2, XZ)
@@ -215,7 +218,7 @@ impl<'a> DFParser<'a> {
}))
}
- /// Parse a SQL `CREATE` statementm handling `CREATE EXTERNAL TABLE`
+ /// Parse a SQL `CREATE` statement handling `CREATE EXTERNAL TABLE`
pub fn parse_create(&mut self) -> Result<Statement, ParserError> {
if self.parser.parse_keyword(Keyword::EXTERNAL) {
self.parse_create_external_table()
@@ -253,6 +256,49 @@ impl<'a> DFParser<'a> {
Ok(partitions)
}
+ /// Parse the ordering clause of a `CREATE EXTERNAL TABLE` SQL statement
+ pub fn parse_order_by_exprs(&mut self) -> Result<Vec<OrderByExpr>, ParserError> {
+ let mut values = vec![];
+ self.parser.expect_token(&Token::LParen)?;
+ loop {
+ values.push(self.parse_order_by_expr()?);
+ if !self.parser.consume_token(&Token::Comma) {
+ self.parser.expect_token(&Token::RParen)?;
+ return Ok(values);
+ }
+ }
+ }
+
+ /// Parse an ORDER BY sub-expression optionally followed by ASC or DESC.
+ pub fn parse_order_by_expr(&mut self) -> Result<OrderByExpr, ParserError> {
+ let expr = self.parser.parse_expr()?;
+
+ let asc = if self.parser.parse_keyword(Keyword::ASC) {
+ Some(true)
+ } else if self.parser.parse_keyword(Keyword::DESC) {
+ Some(false)
+ } else {
+ None
+ };
+
+ let nulls_first = if self
+ .parser
+ .parse_keywords(&[Keyword::NULLS, Keyword::FIRST])
+ {
+ Some(true)
+ } else if self.parser.parse_keywords(&[Keyword::NULLS, Keyword::LAST]) {
+ Some(false)
+ } else {
+ None
+ };
+
+ Ok(OrderByExpr {
+ expr,
+ asc,
+ nulls_first,
+ })
+ }
+
// This is a copy of the equivalent implementation in sqlparser.
fn parse_columns(
&mut self,
@@ -359,6 +405,12 @@ impl<'a> DFParser<'a> {
vec![]
};
+ let order_exprs = if self.parse_has_order() {
+ self.parse_order_by_exprs()?
+ } else {
+ vec![]
+ };
+
let options = if self.parse_has_options() {
self.parse_options()?
} else {
@@ -376,6 +428,7 @@ impl<'a> DFParser<'a> {
delimiter,
location,
table_partition_cols,
+ order_exprs,
if_not_exists,
file_compression_type,
options,
@@ -458,12 +511,17 @@ impl<'a> DFParser<'a> {
self.parser
.parse_keywords(&[Keyword::PARTITIONED, Keyword::BY])
}
+
+ fn parse_has_order(&mut self) -> bool {
+ self.parser.parse_keywords(&[Keyword::WITH, Keyword::ORDER])
+ }
}
#[cfg(test)]
mod tests {
use super::*;
- use sqlparser::ast::{DataType, Ident};
+ use sqlparser::ast::Expr::Identifier;
+ use sqlparser::ast::{BinaryOperator, DataType, Expr, Ident};
use CompressionTypeVariant::UNCOMPRESSED;
fn expect_parse_ok(sql: &str, expected: Statement) -> Result<(), ParserError> {
@@ -520,6 +578,7 @@ mod tests {
delimiter: ',',
location: "foo.csv".into(),
table_partition_cols: vec![],
+ order_exprs: vec![],
if_not_exists: false,
file_compression_type: UNCOMPRESSED,
options: HashMap::new(),
@@ -537,6 +596,7 @@ mod tests {
delimiter: '|',
location: "foo.csv".into(),
table_partition_cols: vec![],
+ order_exprs: vec![],
if_not_exists: false,
file_compression_type: UNCOMPRESSED,
options: HashMap::new(),
@@ -554,6 +614,7 @@ mod tests {
delimiter: ',',
location: "foo.csv".into(),
table_partition_cols: vec!["p1".to_string(), "p2".to_string()],
+ order_exprs: vec![],
if_not_exists: false,
file_compression_type: UNCOMPRESSED,
options: HashMap::new(),
@@ -574,6 +635,7 @@ mod tests {
delimiter: ',',
location: "foo.csv".into(),
table_partition_cols: vec![],
+ order_exprs: vec![],
if_not_exists: false,
file_compression_type: UNCOMPRESSED,
options: HashMap::new(),
@@ -597,6 +659,7 @@ mod tests {
delimiter: ',',
location: "foo.csv".into(),
table_partition_cols: vec![],
+ order_exprs: vec![],
if_not_exists: false,
file_compression_type: CompressionTypeVariant::from_str(
file_compression_type,
@@ -616,6 +679,7 @@ mod tests {
delimiter: ',',
location: "foo.parquet".into(),
table_partition_cols: vec![],
+ order_exprs: vec![],
if_not_exists: false,
file_compression_type: UNCOMPRESSED,
options: HashMap::new(),
@@ -632,6 +696,7 @@ mod tests {
delimiter: ',',
location: "foo.parquet".into(),
table_partition_cols: vec![],
+ order_exprs: vec![],
if_not_exists: false,
file_compression_type: UNCOMPRESSED,
options: HashMap::new(),
@@ -648,6 +713,7 @@ mod tests {
delimiter: ',',
location: "foo.avro".into(),
table_partition_cols: vec![],
+ order_exprs: vec![],
if_not_exists: false,
file_compression_type: UNCOMPRESSED,
options: HashMap::new(),
@@ -665,6 +731,7 @@ mod tests {
delimiter: ',',
location: "foo.parquet".into(),
table_partition_cols: vec![],
+ order_exprs: vec![],
if_not_exists: true,
file_compression_type: UNCOMPRESSED,
options: HashMap::new(),
@@ -687,6 +754,7 @@ mod tests {
delimiter: ',',
location: "blahblah".into(),
table_partition_cols: vec![],
+ order_exprs: vec![],
if_not_exists: false,
file_compression_type: UNCOMPRESSED,
options: HashMap::from([("k1".into(), "v1".into())]),
@@ -704,6 +772,7 @@ mod tests {
delimiter: ',',
location: "blahblah".into(),
table_partition_cols: vec![],
+ order_exprs: vec![],
if_not_exists: false,
file_compression_type: UNCOMPRESSED,
options: HashMap::from([
@@ -713,11 +782,139 @@ mod tests {
});
expect_parse_ok(sql, expected)?;
+ // Ordered Col
+ let sqls = vec!["CREATE EXTERNAL TABLE t(c1 int) STORED AS CSV WITH ORDER (c1) LOCATION 'foo.csv'",
+ "CREATE EXTERNAL TABLE t(c1 int) STORED AS CSV WITH ORDER (c1 NULLS FIRST) LOCATION 'foo.csv'",
+ "CREATE EXTERNAL TABLE t(c1 int) STORED AS CSV WITH ORDER (c1 NULLS LAST) LOCATION 'foo.csv'",
+ "CREATE EXTERNAL TABLE t(c1 int) STORED AS CSV WITH ORDER (c1 ASC) LOCATION 'foo.csv'",
+ "CREATE EXTERNAL TABLE t(c1 int) STORED AS CSV WITH ORDER (c1 DESC) LOCATION 'foo.csv'",
+ "CREATE EXTERNAL TABLE t(c1 int) STORED AS CSV WITH ORDER (c1 DESC NULLS FIRST) LOCATION 'foo.csv'",
+ "CREATE EXTERNAL TABLE t(c1 int) STORED AS CSV WITH ORDER (c1 DESC NULLS LAST) LOCATION 'foo.csv'",
+ "CREATE EXTERNAL TABLE t(c1 int) STORED AS CSV WITH ORDER (c1 ASC NULLS FIRST) LOCATION 'foo.csv'",
+ "CREATE EXTERNAL TABLE t(c1 int) STORED AS CSV WITH ORDER (c1 ASC NULLS LAST) LOCATION 'foo.csv'"];
+ let expected = vec![
+ (None, None),
+ (None, Some(true)),
+ (None, Some(false)),
+ (Some(true), None),
+ (Some(false), None),
+ (Some(false), Some(true)),
+ (Some(false), Some(false)),
+ (Some(true), Some(true)),
+ (Some(true), Some(false)),
+ ];
+ for (sql, (asc, nulls_first)) in sqls.iter().zip(expected.into_iter()) {
+ let expected = Statement::CreateExternalTable(CreateExternalTable {
+ name: "t".into(),
+ columns: vec![make_column_def("c1", DataType::Int(None))],
+ file_type: "CSV".to_string(),
+ has_header: false,
+ delimiter: ',',
+ location: "foo.csv".into(),
+ table_partition_cols: vec![],
+ order_exprs: vec![OrderByExpr {
+ expr: Identifier(Ident {
+ value: "c1".to_owned(),
+ quote_style: None,
+ }),
+ asc,
+ nulls_first,
+ }],
+ if_not_exists: false,
+ file_compression_type: UNCOMPRESSED,
+ options: HashMap::new(),
+ });
+ expect_parse_ok(sql, expected)?;
+ }
+
+ // Ordered Col
+ let sql = "CREATE EXTERNAL TABLE t(c1 int, c2 int) STORED AS CSV WITH ORDER (c1 ASC, c2 DESC NULLS FIRST) LOCATION 'foo.csv'";
+ let display = None;
+ let expected = Statement::CreateExternalTable(CreateExternalTable {
+ name: "t".into(),
+ columns: vec![
+ make_column_def("c1", DataType::Int(display)),
+ make_column_def("c2", DataType::Int(display)),
+ ],
+ file_type: "CSV".to_string(),
+ has_header: false,
+ delimiter: ',',
+ location: "foo.csv".into(),
+ table_partition_cols: vec![],
+ order_exprs: vec![
+ OrderByExpr {
+ expr: Identifier(Ident {
+ value: "c1".to_owned(),
+ quote_style: None,
+ }),
+ asc: Some(true),
+ nulls_first: None,
+ },
+ OrderByExpr {
+ expr: Identifier(Ident {
+ value: "c2".to_owned(),
+ quote_style: None,
+ }),
+ asc: Some(false),
+ nulls_first: Some(true),
+ },
+ ],
+ if_not_exists: false,
+ file_compression_type: UNCOMPRESSED,
+ options: HashMap::new(),
+ });
+ expect_parse_ok(sql, expected)?;
+
+ // Ordered Binary op
+ let sql = "CREATE EXTERNAL TABLE t(c1 int, c2 int) STORED AS CSV WITH ORDER (c1 - c2 ASC) LOCATION 'foo.csv'";
+ let display = None;
+ let expected = Statement::CreateExternalTable(CreateExternalTable {
+ name: "t".into(),
+ columns: vec![
+ make_column_def("c1", DataType::Int(display)),
+ make_column_def("c2", DataType::Int(display)),
+ ],
+ file_type: "CSV".to_string(),
+ has_header: false,
+ delimiter: ',',
+ location: "foo.csv".into(),
+ table_partition_cols: vec![],
+ order_exprs: vec![OrderByExpr {
+ expr: Expr::BinaryOp {
+ left: Box::new(Identifier(Ident {
+ value: "c1".to_owned(),
+ quote_style: None,
+ })),
+ op: BinaryOperator::Minus,
+ right: Box::new(Identifier(Ident {
+ value: "c2".to_owned(),
+ quote_style: None,
+ })),
+ },
+ asc: Some(true),
+ nulls_first: None,
+ }],
+ if_not_exists: false,
+ file_compression_type: UNCOMPRESSED,
+ options: HashMap::new(),
+ });
+ expect_parse_ok(sql, expected)?;
+
// Error cases: partition column does not support type
let sql =
"CREATE EXTERNAL TABLE t STORED AS x OPTIONS ('k1' 'v1', k2 v2, k3) LOCATION 'blahblah'";
expect_parse_error(sql, "sql parser error: Expected literal string, found: )");
+ // Error cases: partition column does not support type
+ let sql =
+ "CREATE EXTERNAL TABLE t(c1 int) STORED AS CSV WITH ORDER c1 LOCATION 'foo.csv'";
+ expect_parse_error(sql, "sql parser error: Expected (, found: c1");
+
+ // Error cases: partition column does not support type
+ let sql =
+ "CREATE EXTERNAL TABLE t(c1 int) STORED AS CSV WITH ORDER (c1 LOCATION 'foo.csv'";
+ expect_parse_error(sql, "sql parser error: Expected ), found: LOCATION");
+
// Error case: `with header` is an invalid syntax
let sql = "CREATE EXTERNAL TABLE t STORED AS CSV WITH HEADER LOCATION 'abc'";
expect_parse_error(sql, "sql parser error: Expected LOCATION, found: WITH");
diff --git a/datafusion/sql/src/statement.rs b/datafusion/sql/src/statement.rs
index 56d0700e0d..8d5b46d29c 100644
--- a/datafusion/sql/src/statement.rs
+++ b/datafusion/sql/src/statement.rs
@@ -40,8 +40,8 @@ use datafusion_expr::{
};
use sqlparser::ast;
use sqlparser::ast::{
- Assignment, Expr as SQLExpr, Expr, Ident, ObjectName, ObjectType, Query, SchemaName,
- SetExpr, ShowCreateObject, ShowStatementFilter, Statement, TableFactor,
+ Assignment, Expr as SQLExpr, Expr, Ident, ObjectName, ObjectType, OrderByExpr, Query,
+ SchemaName, SetExpr, ShowCreateObject, ShowStatementFilter, Statement, TableFactor,
TableWithJoins, UnaryOperator, Value,
};
use sqlparser::parser::ParserError::ParserError;
@@ -423,6 +423,40 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
}))
}
+ fn build_order_by(
+ &self,
+ order_exprs: Vec<OrderByExpr>,
+ schema: &DFSchemaRef,
+ ) -> Result<Vec<datafusion_expr::Expr>> {
+ // Ask user to provide a schema if schema is empty.
+ if !order_exprs.is_empty() && schema.fields().is_empty() {
+ return Err(DataFusionError::Plan(
+ "Provide a schema before specifying the order while creating a table."
+ .to_owned(),
+ ));
+ }
+ // Convert each OrderByExpr to a SortExpr:
+ let result = order_exprs
+ .into_iter()
+ .map(|e| self.order_by_to_sort_expr(e, schema))
+ .collect::<Result<Vec<_>>>()?;
+ // Verify that columns of all SortExprs exist in the schema:
+ for expr in result.iter() {
+ for column in expr.to_columns()?.iter() {
+ if !schema.has_column(column) {
+ // Return an error if any column is not in the schema:
+ return Err(DataFusionError::Plan(format!(
+ "Column {} is not in schema",
+ column
+ )));
+ }
+ }
+ }
+
+ // If all SortExprs are valid, return them as an expression vector
+ Ok(result)
+ }
+
/// Generate a logical plan from a CREATE EXTERNAL TABLE statement
fn external_table_to_plan(
&self,
@@ -439,6 +473,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
table_partition_cols,
if_not_exists,
file_compression_type,
+ order_exprs,
options,
} = statement;
@@ -459,12 +494,15 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
}
let schema = self.build_schema(columns)?;
+ let df_schema = schema.to_dfschema_ref()?;
+
+ let ordered_exprs = self.build_order_by(order_exprs, &df_schema)?;
// External tables do not support schemas at the moment, so the name is just a table name
let name = OwnedTableReference::bare(name);
Ok(LogicalPlan::CreateExternalTable(PlanCreateExternalTable {
- schema: schema.to_dfschema_ref()?,
+ schema: df_schema,
name,
location,
file_type,
@@ -474,6 +512,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
if_not_exists,
definition,
file_compression_type,
+ order_exprs: ordered_exprs,
options,
}))
}
diff --git a/docs/source/user-guide/sql/ddl.md b/docs/source/user-guide/sql/ddl.md
index c531312b1e..29a156bd01 100644
--- a/docs/source/user-guide/sql/ddl.md
+++ b/docs/source/user-guide/sql/ddl.md
@@ -63,6 +63,47 @@ WITH HEADER ROW
LOCATION '/path/to/aggregate_test_100.csv';
```
+When creating an output from a data source that is already ordered by an expression, you can pre-specify the order of
+the data using the `WITH ORDER` clause. This applies even if the expression used for sorting is complex,
+allowing for greater flexibility.
+
+Here's an example of how to use `WITH ORDER` query
+
+```sql
+CREATE EXTERNAL TABLE test (
+ c1 VARCHAR NOT NULL,
+ c2 INT NOT NULL,
+ c3 SMALLINT NOT NULL,
+ c4 SMALLINT NOT NULL,
+ c5 INT NOT NULL,
+ c6 BIGINT NOT NULL,
+ c7 SMALLINT NOT NULL,
+ c8 INT NOT NULL,
+ c9 BIGINT NOT NULL,
+ c10 VARCHAR NOT NULL,
+ c11 FLOAT NOT NULL,
+ c12 DOUBLE NOT NULL,
+ c13 VARCHAR NOT NULL
+)
+STORED AS CSV
+WITH HEADER ROW
+WITH ORDER (c2 ASC, c5 + c8 DESC NULL FIRST)
+LOCATION '/path/to/aggregate_test_100.csv';
+```
+
+where `WITH ORDER` clause specifies the sort order:
+
+```sql
+WITH ORDER (sort_expression1 [ASC | DESC] [NULLS { FIRST | LAST }]
+ [, sort_expression2 [ASC | DESC] [NULLS { FIRST | LAST }] ...])
+```
+
+#### Cautions When Using the WITH ORDER Clause
+
+- It's important to understand that using the `WITH ORDER` clause in the `CREATE EXTERNAL TABLE` statement only specifies the order in which the data should be read from the external file. If the data in the file is not already sorted according to the specified order, then the results may not be correct.
+
+- It's also important to note that the `WITH ORDER` clause does not affect the ordering of the data in the original external file.
+
If data sources are already partitioned in Hive style, `PARTITIONED BY` can be used for partition pruning.
```