Apache DataFusion SQL Query Engine
Parse identifiers properly for TableReferences (#5183)
Jeffrey3f9b99663ce2
diff --git a/datafusion/common/src/table_reference.rs b/datafusion/common/src/table_reference.rsindex 0c74a35ae4..370f5e46ee 100644--- a/datafusion/common/src/table_reference.rs+++ b/datafusion/common/src/table_reference.rs@@ -15,15 +15,24 @@// specific language governing permissions and limitations// under the License.+use crate::error::Result;+use sqlparser::{+ ast::Ident,+ dialect::GenericDialect,+ parser::{Parser, ParserError},+ tokenizer::{Token, TokenWithLocation},+};+use std::borrow::Cow;+/// A resolved path to a table of the form "catalog.schema.table"-#[derive(Debug, Clone, Copy)]+#[derive(Debug, Clone)]pub struct ResolvedTableReference<'a> {/// The catalog (aka database) containing the table- pub catalog: &'a str,+ pub catalog: Cow<'a, str>,/// The schema containing the table- pub schema: &'a str,+ pub schema: Cow<'a, str>,/// The table name- pub table: &'a str,+ pub table: Cow<'a, str>,}impl<'a> std::fmt::Display for ResolvedTableReference<'a> {@@ -33,28 +42,28 @@ impl<'a> std::fmt::Display for ResolvedTableReference<'a> {}/// Represents a path to a table that may require further resolution-#[derive(Debug, Clone, Copy)]+#[derive(Debug, Clone, PartialEq, Eq)]pub enum TableReference<'a> {/// An unqualified table reference, e.g. "table"Bare {/// The table name- table: &'a str,+ table: Cow<'a, str>,},/// A partially resolved table reference, e.g. "schema.table"Partial {/// The schema containing the table- schema: &'a str,+ schema: Cow<'a, str>,/// The table name- table: &'a str,+ table: Cow<'a, str>,},/// A fully resolved table reference, e.g. "catalog.schema.table"Full {/// The catalog (aka database) containing the table- catalog: &'a str,+ catalog: Cow<'a, str>,/// The schema containing the table- schema: &'a str,+ schema: Cow<'a, str>,/// The table name- table: &'a str,+ table: Cow<'a, str>,},}@@ -89,19 +98,33 @@ impl OwnedTableReference {/// Return a `TableReference` view of this `OwnedTableReference`pub fn as_table_reference(&self) -> TableReference<'_> {match self {- Self::Bare { table } => TableReference::Bare { table },- Self::Partial { schema, table } => TableReference::Partial { schema, table },+ Self::Bare { table } => TableReference::Bare {+ table: table.into(),+ },+ Self::Partial { schema, table } => TableReference::Partial {+ schema: schema.into(),+ table: table.into(),+ },Self::Full {catalog,schema,table,} => TableReference::Full {- catalog,- schema,- table,+ catalog: catalog.into(),+ schema: schema.into(),+ table: table.into(),},}}++ /// Retrieve the actual table name, regardless of qualification+ pub fn table(&self) -> &str {+ match self {+ Self::Full { table, .. }+ | Self::Partial { table, .. }+ | Self::Bare { table } => table,+ }+ }}impl std::fmt::Display for OwnedTableReference {@@ -121,7 +144,7 @@ impl std::fmt::Display for OwnedTableReference {}/// Convert `OwnedTableReference` into a `TableReference`. Somewhat-/// akward to use but 'idiomatic': `(&table_ref).into()`+/// awkward to use but 'idiomatic': `(&table_ref).into()`impl<'a> From<&'a OwnedTableReference> for TableReference<'a> {fn from(r: &'a OwnedTableReference) -> Self {r.as_table_reference()@@ -155,50 +178,109 @@ impl<'a> TableReference<'a> {table,},Self::Partial { schema, table } => ResolvedTableReference {- catalog: default_catalog,+ catalog: default_catalog.into(),schema,table,},Self::Bare { table } => ResolvedTableReference {- catalog: default_catalog,- schema: default_schema,+ catalog: default_catalog.into(),+ schema: default_schema.into(),table,},}}- /// Forms a [`TableReference`] by splitting `s` on periods `.`.- ///- /// Note that this function does NOT handle periods or name- /// normalization correctly (e.g. `"foo.bar"` will be parsed as- /// `"foo`.`bar"`. and `Foo` will be parsed as `Foo` (not `foo`).- ///- /// If you need to handle such identifiers correctly, you should- /// use a SQL parser or form the [`OwnedTableReference`] directly.+ /// Forms a [`TableReference`] by attempting to parse `s` as a multipart identifier,+ /// failing that then taking the entire unnormalized input as the identifier itself.///- /// See more detail in <https://github.com/apache/arrow-datafusion/issues/4532>+ /// Will normalize (convert to lowercase) any unquoted identifiers.+ /// e.g. `Foo` will be parsed as `foo`, and `"Foo"".bar"` will be parsed as+ /// `Foo".bar` (note the preserved case and requiring two double quotes to represent+ /// a single double quote in the identifier)pub fn parse_str(s: &'a str) -> Self {- let parts: Vec<&str> = s.split('.').collect();+ let mut parts = parse_identifiers(s)+ .unwrap_or(vec![])+ .into_iter()+ .map(|id| match id.quote_style {+ Some(_) => id.value,+ None => id.value.to_ascii_lowercase(),+ })+ .collect::<Vec<_>>();match parts.len() {- 1 => Self::Bare { table: s },+ 1 => Self::Bare {+ table: parts.remove(0).into(),+ },2 => Self::Partial {- schema: parts[0],- table: parts[1],+ schema: parts.remove(0).into(),+ table: parts.remove(0).into(),},3 => Self::Full {- catalog: parts[0],- schema: parts[1],- table: parts[2],+ catalog: parts.remove(0).into(),+ schema: parts.remove(0).into(),+ table: parts.remove(0).into(),},- _ => Self::Bare { table: s },+ _ => Self::Bare { table: s.into() },}}}-/// Parse a string into a TableReference, by splittig on `.`+// TODO: remove when can use https://github.com/sqlparser-rs/sqlparser-rs/issues/805+fn parse_identifiers(s: &str) -> Result<Vec<Ident>> {+ let dialect = GenericDialect;+ let mut parser = Parser::new(&dialect).try_with_sql(s)?;+ let mut idents = vec![];++ // expecting at least one word for identifier+ match parser.next_token_no_skip() {+ Some(TokenWithLocation {+ token: Token::Word(w),+ ..+ }) => idents.push(w.to_ident()),+ Some(TokenWithLocation { token, .. }) => {+ return Err(ParserError::ParserError(format!(+ "Unexpected token in identifier: {token}"+ )))?+ }+ None => {+ return Err(ParserError::ParserError(+ "Empty input when parsing identifier".to_string(),+ ))?+ }+ };++ while let Some(TokenWithLocation { token, .. }) = parser.next_token_no_skip() {+ match token {+ // ensure that optional period is succeeded by another identifier+ Token::Period => match parser.next_token_no_skip() {+ Some(TokenWithLocation {+ token: Token::Word(w),+ ..+ }) => idents.push(w.to_ident()),+ Some(TokenWithLocation { token, .. }) => {+ return Err(ParserError::ParserError(format!(+ "Unexpected token following period in identifier: {token}"+ )))?+ }+ None => {+ return Err(ParserError::ParserError(+ "Trailing period in identifier".to_string(),+ ))?+ }+ },+ _ => {+ return Err(ParserError::ParserError(format!(+ "Unexpected token in identifier: {token}"+ )))?+ }+ }+ }+ Ok(idents)+}++/// Parse a string into a TableReference, normalizing where appropriate///-/// See caveats on [`TableReference::parse_str`]+/// See full details on [`TableReference::parse_str`]impl<'a> From<&'a str> for TableReference<'a> {fn from(s: &'a str) -> Self {Self::parse_str(s)@@ -214,3 +296,97 @@ impl<'a> From<ResolvedTableReference<'a>> for TableReference<'a> {}}}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_parse_identifiers() -> Result<()> {+ let s = "CATALOG.\"F(o)o. \"\"bar\".table";+ let actual = parse_identifiers(s)?;+ let expected = vec![+ Ident {+ value: "CATALOG".to_string(),+ quote_style: None,+ },+ Ident {+ value: "F(o)o. \"bar".to_string(),+ quote_style: Some('"'),+ },+ Ident {+ value: "table".to_string(),+ quote_style: None,+ },+ ];+ assert_eq!(expected, actual);++ let s = "";+ let err = parse_identifiers(s).expect_err("didn't fail to parse");+ assert_eq!(+ "SQL(ParserError(\"Empty input when parsing identifier\"))",+ format!("{err:?}")+ );++ let s = "*schema.table";+ let err = parse_identifiers(s).expect_err("didn't fail to parse");+ assert_eq!(+ "SQL(ParserError(\"Unexpected token in identifier: *\"))",+ format!("{err:?}")+ );++ let s = "schema.table*";+ let err = parse_identifiers(s).expect_err("didn't fail to parse");+ assert_eq!(+ "SQL(ParserError(\"Unexpected token in identifier: *\"))",+ format!("{err:?}")+ );++ let s = "schema.table.";+ let err = parse_identifiers(s).expect_err("didn't fail to parse");+ assert_eq!(+ "SQL(ParserError(\"Trailing period in identifier\"))",+ format!("{err:?}")+ );++ let s = "schema.*";+ let err = parse_identifiers(s).expect_err("didn't fail to parse");+ assert_eq!(+ "SQL(ParserError(\"Unexpected token following period in identifier: *\"))",+ format!("{err:?}")+ );++ Ok(())+ }++ #[test]+ fn test_table_reference_from_str_normalizes() {+ let expected = TableReference::Full {+ catalog: Cow::Owned("catalog".to_string()),+ schema: Cow::Owned("FOO\".bar".to_string()),+ table: Cow::Owned("table".to_string()),+ };+ let actual = TableReference::from("catalog.\"FOO\"\".bar\".TABLE");+ assert_eq!(expected, actual);++ let expected = TableReference::Partial {+ schema: Cow::Owned("FOO\".bar".to_string()),+ table: Cow::Owned("table".to_string()),+ };+ let actual = TableReference::from("\"FOO\"\".bar\".TABLE");+ assert_eq!(expected, actual);++ let expected = TableReference::Bare {+ table: Cow::Owned("table".to_string()),+ };+ let actual = TableReference::from("TABLE");+ assert_eq!(expected, actual);++ // if fail to parse, take entire input string as identifier+ let expected = TableReference::Bare {+ table: Cow::Owned("TABLE()".to_string()),+ };+ let actual = TableReference::from("TABLE()");+ assert_eq!(expected, actual);+ }+}diff --git a/datafusion/core/src/execution/context.rs b/datafusion/core/src/execution/context.rsindex b3243b2188..132d5711a5 100644--- a/datafusion/core/src/execution/context.rs+++ b/datafusion/core/src/execution/context.rs@@ -222,7 +222,12 @@ impl SessionContext {batch: RecordBatch,) -> Result<Option<Arc<dyn TableProvider>>> {let table = MemTable::try_new(batch.schema(), vec![vec![batch]])?;- self.register_table(TableReference::Bare { table: table_name }, Arc::new(table))+ self.register_table(+ TableReference::Bare {+ table: table_name.into(),+ },+ Arc::new(table),+ )}/// Return the [RuntimeEnv] used to run queries with this [SessionContext]@@ -556,19 +561,20 @@ impl SessionContext {table_type: TableType,) -> Result<bool> {let table_ref = table_ref.into();+ let table = table_ref.table().to_owned();let maybe_schema = {let state = self.state.read();let resolved = state.resolve_table_ref(table_ref);state.catalog_list- .catalog(resolved.catalog)- .and_then(|c| c.schema(resolved.schema))+ .catalog(&resolved.catalog)+ .and_then(|c| c.schema(&resolved.schema))};if let Some(schema) = maybe_schema {- if let Some(table_provider) = schema.table(table_ref.table()).await {+ if let Some(table_provider) = schema.table(&table).await {if table_provider.table_type() == table_type {- schema.deregister_table(table_ref.table())?;+ schema.deregister_table(&table)?;return Ok(true);}}@@ -753,7 +759,10 @@ impl SessionContext {.with_listing_options(options).with_schema(resolved_schema);let table = ListingTable::try_new(config)?.with_definition(sql_definition);- self.register_table(TableReference::Bare { table: name }, Arc::new(table))?;+ self.register_table(+ TableReference::Bare { table: name.into() },+ Arc::new(table),+ )?;Ok(())}@@ -875,10 +884,11 @@ impl SessionContext {provider: Arc<dyn TableProvider>,) -> Result<Option<Arc<dyn TableProvider>>> {let table_ref = table_ref.into();+ let table = table_ref.table().to_owned();self.state.read().schema_for_ref(table_ref)?- .register_table(table_ref.table().to_owned(), provider)+ .register_table(table, provider)}/// Deregisters the given table.@@ -889,10 +899,11 @@ impl SessionContext {table_ref: impl Into<TableReference<'a>>,) -> Result<Option<Arc<dyn TableProvider>>> {let table_ref = table_ref.into();+ let table = table_ref.table().to_owned();self.state.read().schema_for_ref(table_ref)?- .deregister_table(table_ref.table())+ .deregister_table(&table)}/// Return true if the specified table exists in the schema provider.@@ -901,11 +912,12 @@ impl SessionContext {table_ref: impl Into<TableReference<'a>>,) -> Result<bool> {let table_ref = table_ref.into();+ let table = table_ref.table().to_owned();Ok(self.state.read().schema_for_ref(table_ref)?- .table_exist(table_ref.table()))+ .table_exist(&table))}/// Retrieves a [`DataFrame`] representing a table previously@@ -920,9 +932,10 @@ impl SessionContext {table_ref: impl Into<TableReference<'a>>,) -> Result<DataFrame> {let table_ref = table_ref.into();+ let table = table_ref.table().to_owned();let provider = self.table_provider(table_ref).await?;let plan = LogicalPlanBuilder::scan(- table_ref.table(),+ &table,provider_as_source(Arc::clone(&provider)),None,)?@@ -936,13 +949,11 @@ impl SessionContext {table_ref: impl Into<TableReference<'a>>,) -> Result<Arc<dyn TableProvider>> {let table_ref = table_ref.into();+ let table = table_ref.table().to_owned();let schema = self.state.read().schema_for_ref(table_ref)?;- match schema.table(table_ref.table()).await {+ match schema.table(&table).await {Some(ref provider) => Ok(Arc::clone(provider)),- _ => Err(DataFusionError::Plan(format!(- "No table named '{}'",- table_ref.table()- ))),+ _ => Err(DataFusionError::Plan(format!("No table named '{table}'"))),}}@@ -960,7 +971,7 @@ impl SessionContext {.state.read()// a bare reference will always resolve to the default catalog and schema- .schema_for_ref(TableReference::Bare { table: "" })?+ .schema_for_ref(TableReference::Bare { table: "".into() })?.table_names().iter().cloned()@@ -1601,14 +1612,14 @@ impl SessionState {}self.catalog_list- .catalog(resolved_ref.catalog)+ .catalog(&resolved_ref.catalog).ok_or_else(|| {DataFusionError::Plan(format!("failed to resolve catalog: {}",resolved_ref.catalog))})?- .schema(resolved_ref.schema)+ .schema(&resolved_ref.schema).ok_or_else(|| {DataFusionError::Plan(format!("failed to resolve schema: {}",@@ -1764,10 +1775,11 @@ impl SessionState {for relation in relations {let reference =object_name_to_table_reference(relation, enable_ident_normalization)?;+ let table = reference.table();let resolved = self.resolve_table_ref(reference.as_table_reference());if let Entry::Vacant(v) = provider.tables.entry(resolved.to_string()) {if let Ok(schema) = self.schema_for_ref(resolved) {- if let Some(table) = schema.table(resolved.table).await {+ if let Some(table) = schema.table(table).await {v.insert(provider_as_source(table));}}diff --git a/datafusion/sql/src/statement.rs b/datafusion/sql/src/statement.rsindex ebbafbd5df..201cf7a852 100644--- a/datafusion/sql/src/statement.rs+++ b/datafusion/sql/src/statement.rs@@ -946,7 +946,10 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {/// Return true if there is a table provider available for "schema.table"fn has_table(&self, schema: &str, table: &str) -> bool {- let tables_reference = TableReference::Partial { schema, table };+ let tables_reference = TableReference::Partial {+ schema: schema.into(),+ table: table.into(),+ };self.schema_provider.get_table_provider(tables_reference).is_ok()diff --git a/datafusion/substrait/src/consumer.rs b/datafusion/substrait/src/consumer.rsindex 52f1f052a6..1ae5568af1 100644--- a/datafusion/substrait/src/consumer.rs+++ b/datafusion/substrait/src/consumer.rs@@ -371,16 +371,16 @@ pub async fn from_substrait_rel());}1 => TableReference::Bare {- table: &nt.names[0],+ table: (&nt.names[0]).into(),},2 => TableReference::Partial {- schema: &nt.names[0],- table: &nt.names[1],+ schema: (&nt.names[0]).into(),+ table: (&nt.names[1]).into(),},_ => TableReference::Full {- catalog: &nt.names[0],- schema: &nt.names[1],- table: &nt.names[2],+ catalog: (&nt.names[0]).into(),+ schema: (&nt.names[1]).into(),+ table: (&nt.names[2]).into(),},};let t = ctx.table(table_reference).await?;