Skip to content

Apache DataFusion SQL Query Engine

Remove `OwnedTableReference` and `OwnedSchemaReference` (#9933)

comphead3ae029988754
diff --git a/datafusion/common/src/column.rs b/datafusion/common/src/column.rs
index 16f9579c66..dec87d9d07 100644
--- a/datafusion/common/src/column.rs
+++ b/datafusion/common/src/column.rs
@@ -21,7 +21,7 @@ use arrow_schema::Field;
use crate::error::_schema_err;
use crate::utils::{parse_identifiers_normalized, quote_identifier};
-use crate::{DFSchema, DataFusionError, OwnedTableReference, Result, SchemaError};
+use crate::{DFSchema, DataFusionError, Result, SchemaError, TableReference};
use std::collections::HashSet;
use std::convert::Infallible;
use std::fmt;
@@ -32,7 +32,7 @@ use std::sync::Arc;
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Column {
/// relation/table reference.
- pub relation: Option<OwnedTableReference>,
+ pub relation: Option<TableReference>,
/// field/column name.
pub name: String,
}
@@ -45,7 +45,7 @@ impl Column {
///
/// [`TableReference::parse_str`]: crate::TableReference::parse_str
pub fn new(
- relation: Option<impl Into<OwnedTableReference>>,
+ relation: Option<impl Into<TableReference>>,
name: impl Into<String>,
) -> Self {
Self {
@@ -74,20 +74,20 @@ impl Column {
let (relation, name) = match idents.len() {
1 => (None, idents.remove(0)),
2 => (
- Some(OwnedTableReference::Bare {
+ Some(TableReference::Bare {
table: idents.remove(0).into(),
}),
idents.remove(0),
),
3 => (
- Some(OwnedTableReference::Partial {
+ Some(TableReference::Partial {
schema: idents.remove(0).into(),
table: idents.remove(0).into(),
}),
idents.remove(0),
),
4 => (
- Some(OwnedTableReference::Full {
+ Some(TableReference::Full {
catalog: idents.remove(0).into(),
schema: idents.remove(0).into(),
table: idents.remove(0).into(),
@@ -340,8 +340,8 @@ impl From<String> for Column {
}
/// Create a column, use qualifier and field name
-impl From<(Option<&OwnedTableReference>, &Field)> for Column {
- fn from((relation, field): (Option<&OwnedTableReference>, &Field)) -> Self {
+impl From<(Option<&TableReference>, &Field)> for Column {
+ fn from((relation, field): (Option<&TableReference>, &Field)) -> Self {
Self::new(relation.cloned(), field.name())
}
}
diff --git a/datafusion/common/src/dfschema.rs b/datafusion/common/src/dfschema.rs
index 8109c1c126..9f167fd1f6 100644
--- a/datafusion/common/src/dfschema.rs
+++ b/datafusion/common/src/dfschema.rs
@@ -27,7 +27,7 @@ use std::sync::Arc;
use crate::error::{DataFusionError, Result, _plan_err, _schema_err};
use crate::{
field_not_found, unqualified_field_not_found, Column, FunctionalDependencies,
- OwnedTableReference, SchemaError, TableReference,
+ SchemaError, TableReference,
};
use arrow::compute::can_cast_types;
@@ -111,7 +111,7 @@ pub struct DFSchema {
inner: SchemaRef,
/// Optional qualifiers for each column in this schema. In the same order as
/// the `self.inner.fields()`
- field_qualifiers: Vec<Option<OwnedTableReference>>,
+ field_qualifiers: Vec<Option<TableReference>>,
/// Stores functional dependencies in the schema.
functional_dependencies: FunctionalDependencies,
}
@@ -128,10 +128,10 @@ impl DFSchema {
/// Create a `DFSchema` from an Arrow schema where all the fields have a given qualifier
pub fn new_with_metadata(
- qualified_fields: Vec<(Option<OwnedTableReference>, Arc<Field>)>,
+ qualified_fields: Vec<(Option<TableReference>, Arc<Field>)>,
metadata: HashMap<String, String>,
) -> Result<Self> {
- let (qualifiers, fields): (Vec<Option<OwnedTableReference>>, Vec<Arc<Field>>) =
+ let (qualifiers, fields): (Vec<Option<TableReference>>, Vec<Arc<Field>>) =
qualified_fields.into_iter().unzip();
let schema = Arc::new(Schema::new_with_metadata(fields, metadata));
@@ -170,10 +170,9 @@ impl DFSchema {
schema: &Schema,
) -> Result<Self> {
let qualifier = qualifier.into();
- let owned_qualifier = qualifier.to_owned_reference();
let schema = DFSchema {
inner: schema.clone().into(),
- field_qualifiers: vec![Some(owned_qualifier); schema.fields.len()],
+ field_qualifiers: vec![Some(qualifier); schema.fields.len()],
functional_dependencies: FunctionalDependencies::empty(),
};
schema.check_names()?;
@@ -182,16 +181,12 @@ impl DFSchema {
/// Create a `DFSchema` from an Arrow schema where all the fields have a given qualifier
pub fn from_field_specific_qualified_schema(
- qualifiers: Vec<Option<impl Into<TableReference>>>,
+ qualifiers: Vec<Option<TableReference>>,
schema: &SchemaRef,
) -> Result<Self> {
- let owned_qualifiers = qualifiers
- .into_iter()
- .map(|qualifier| qualifier.map(|q| q.into().to_owned_reference()))
- .collect();
let dfschema = Self {
inner: schema.clone(),
- field_qualifiers: owned_qualifiers,
+ field_qualifiers: qualifiers,
functional_dependencies: FunctionalDependencies::empty(),
};
dfschema.check_names()?;
@@ -216,7 +211,7 @@ impl DFSchema {
for (qualifier, name) in qualified_names {
if unqualified_names.contains(name) {
return _schema_err!(SchemaError::AmbiguousReference {
- field: Column::new(Some(qualifier.to_owned_reference()), name)
+ field: Column::new(Some(qualifier.clone()), name)
});
}
}
@@ -270,7 +265,7 @@ impl DFSchema {
return;
}
- let self_fields: HashSet<(Option<&OwnedTableReference>, &FieldRef)> =
+ let self_fields: HashSet<(Option<&TableReference>, &FieldRef)> =
self.iter().collect();
let self_unqualified_names: HashSet<&str> = self
.inner
@@ -316,7 +311,7 @@ impl DFSchema {
/// Returns an immutable reference of a specific `Field` instance selected using an
/// offset within the internal `fields` vector and its qualifier
- pub fn qualified_field(&self, i: usize) -> (Option<&OwnedTableReference>, &Field) {
+ pub fn qualified_field(&self, i: usize) -> (Option<&TableReference>, &Field) {
(self.field_qualifiers[i].as_ref(), self.field(i))
}
@@ -383,13 +378,11 @@ impl DFSchema {
&self,
qualifier: Option<&TableReference>,
name: &str,
- ) -> Result<(Option<&OwnedTableReference>, &Field)> {
+ ) -> Result<(Option<&TableReference>, &Field)> {
if let Some(qualifier) = qualifier {
let idx = self
.index_of_column_by_name(Some(qualifier), name)?
- .ok_or_else(|| {
- field_not_found(Some(qualifier.to_string()), name, self)
- })?;
+ .ok_or_else(|| field_not_found(Some(qualifier.clone()), name, self))?;
Ok((self.field_qualifiers[idx].as_ref(), self.field(idx)))
} else {
self.qualified_field_with_unqualified_name(name)
@@ -428,7 +421,7 @@ impl DFSchema {
pub fn qualified_fields_with_unqualified_name(
&self,
name: &str,
- ) -> Vec<(Option<&OwnedTableReference>, &Field)> {
+ ) -> Vec<(Option<&TableReference>, &Field)> {
self.iter()
.filter(|(_, field)| field.name() == name)
.map(|(qualifier, field)| (qualifier, field.as_ref()))
@@ -456,7 +449,7 @@ impl DFSchema {
pub fn qualified_field_with_unqualified_name(
&self,
name: &str,
- ) -> Result<(Option<&OwnedTableReference>, &Field)> {
+ ) -> Result<(Option<&TableReference>, &Field)> {
let matches = self.qualified_fields_with_unqualified_name(name);
match matches.len() {
0 => Err(unqualified_field_not_found(name, self)),
@@ -527,7 +520,7 @@ impl DFSchema {
) -> Result<&Field> {
let idx = self
.index_of_column_by_name(Some(qualifier), name)?
- .ok_or_else(|| field_not_found(Some(qualifier.to_string()), name, self))?;
+ .ok_or_else(|| field_not_found(Some(qualifier.clone()), name, self))?;
Ok(self.field(idx))
}
@@ -544,7 +537,7 @@ impl DFSchema {
pub fn qualified_field_from_column(
&self,
column: &Column,
- ) -> Result<(Option<&OwnedTableReference>, &Field)> {
+ ) -> Result<(Option<&TableReference>, &Field)> {
self.qualified_field_with_name(column.relation.as_ref(), &column.name)
}
@@ -750,7 +743,7 @@ impl DFSchema {
}
/// Replace all field qualifier with new value in schema
- pub fn replace_qualifier(self, qualifier: impl Into<OwnedTableReference>) -> Self {
+ pub fn replace_qualifier(self, qualifier: impl Into<TableReference>) -> Self {
let qualifier = qualifier.into();
DFSchema {
field_qualifiers: vec![Some(qualifier); self.inner.fields.len()],
@@ -777,9 +770,7 @@ impl DFSchema {
}
/// Iterate over the qualifiers and fields in the DFSchema
- pub fn iter(
- &self,
- ) -> impl Iterator<Item = (Option<&OwnedTableReference>, &FieldRef)> {
+ pub fn iter(&self) -> impl Iterator<Item = (Option<&TableReference>, &FieldRef)> {
self.field_qualifiers
.iter()
.zip(self.inner.fields().iter())
@@ -1065,7 +1056,7 @@ mod tests {
#[test]
fn test_from_field_specific_qualified_schema() -> Result<()> {
let schema = DFSchema::from_field_specific_qualified_schema(
- vec![Some("t1"), None],
+ vec![Some("t1".into()), None],
&Arc::new(Schema::new(vec![
Field::new("c0", DataType::Boolean, true),
Field::new("c1", DataType::Boolean, true),
diff --git a/datafusion/common/src/error.rs b/datafusion/common/src/error.rs
index 234b653922..4d9233d1f7 100644
--- a/datafusion/common/src/error.rs
+++ b/datafusion/common/src/error.rs
@@ -26,7 +26,7 @@ use std::result;
use std::sync::Arc;
use crate::utils::quote_identifier;
-use crate::{Column, DFSchema, OwnedTableReference};
+use crate::{Column, DFSchema, TableReference};
#[cfg(feature = "avro")]
use apache_avro::Error as AvroError;
use arrow::error::ArrowError;
@@ -141,7 +141,7 @@ pub enum SchemaError {
AmbiguousReference { field: Column },
/// Schema contains duplicate qualified field name
DuplicateQualifiedField {
- qualifier: Box<OwnedTableReference>,
+ qualifier: Box<TableReference>,
name: String,
},
/// Schema contains duplicate unqualified field name
@@ -606,7 +606,7 @@ pub use plan_err as _plan_err;
pub use schema_err as _schema_err;
/// Create a "field not found" DataFusion::SchemaError
-pub fn field_not_found<R: Into<OwnedTableReference>>(
+pub fn field_not_found<R: Into<TableReference>>(
qualifier: Option<R>,
name: &str,
schema: &DFSchema,
diff --git a/datafusion/common/src/lib.rs b/datafusion/common/src/lib.rs
index 4d2e8b7417..e64acd0bfe 100644
--- a/datafusion/common/src/lib.rs
+++ b/datafusion/common/src/lib.rs
@@ -65,9 +65,9 @@ pub use functional_dependencies::{
pub use join_type::{JoinConstraint, JoinSide, JoinType};
pub use param_value::ParamValues;
pub use scalar::{ScalarType, ScalarValue};
-pub use schema_reference::{OwnedSchemaReference, SchemaReference};
+pub use schema_reference::SchemaReference;
pub use stats::{ColumnStatistics, Statistics};
-pub use table_reference::{OwnedTableReference, ResolvedTableReference, TableReference};
+pub use table_reference::{ResolvedTableReference, TableReference};
pub use unnest::UnnestOptions;
pub use utils::project_schema;
diff --git a/datafusion/common/src/schema_reference.rs b/datafusion/common/src/schema_reference.rs
index 60e21f232e..e5048f63dc 100644
--- a/datafusion/common/src/schema_reference.rs
+++ b/datafusion/common/src/schema_reference.rs
@@ -33,8 +33,6 @@ impl SchemaReference {
}
}
-pub type OwnedSchemaReference = SchemaReference;
-
impl std::fmt::Display for SchemaReference {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
@@ -43,9 +41,3 @@ impl std::fmt::Display for SchemaReference {
}
}
}
-
-impl<'a> From<&'a OwnedSchemaReference> for SchemaReference {
- fn from(value: &'a OwnedSchemaReference) -> Self {
- value.clone()
- }
-}
diff --git a/datafusion/common/src/table_reference.rs b/datafusion/common/src/table_reference.rs
index 63dbb95177..8c09fc9a89 100644
--- a/datafusion/common/src/table_reference.rs
+++ b/datafusion/common/src/table_reference.rs
@@ -92,18 +92,6 @@ pub enum TableReference {
},
}
-/// This is a [`TableReference`] that has 'static lifetime (aka it
-/// owns the underlying string)
-///
-/// To convert a [`TableReference`] to an [`OwnedTableReference`], use
-///
-/// ```
-/// # use datafusion_common::{OwnedTableReference, TableReference};
-/// let table_reference = TableReference::from("mytable");
-/// let owned_reference = table_reference.to_owned_reference();
-/// ```
-pub type OwnedTableReference = TableReference;
-
impl std::fmt::Display for TableReference {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
@@ -244,12 +232,6 @@ impl TableReference {
}
}
- /// Converts directly into an [`OwnedTableReference`] by cloning
- /// the underlying data.
- pub fn to_owned_reference(&self) -> OwnedTableReference {
- self.clone()
- }
-
/// Forms a string where the identifiers are quoted
///
/// # Example
@@ -322,19 +304,6 @@ impl TableReference {
}
}
-/// Parse a `String` into a OwnedTableReference as a multipart SQL identifier.
-impl From<String> for OwnedTableReference {
- fn from(s: String) -> Self {
- TableReference::parse_str(&s).to_owned_reference()
- }
-}
-
-impl<'a> From<&'a OwnedTableReference> for TableReference {
- fn from(value: &'a OwnedTableReference) -> Self {
- value.clone()
- }
-}
-
/// Parse a string into a TableReference, normalizing where appropriate
///
/// See full details on [`TableReference::parse_str`]
@@ -350,6 +319,12 @@ impl<'a> From<&'a String> for TableReference {
}
}
+impl From<String> for TableReference {
+ fn from(s: String) -> Self {
+ Self::parse_str(&s)
+ }
+}
+
impl From<ResolvedTableReference> for TableReference {
fn from(resolved: ResolvedTableReference) -> Self {
Self::Full {
diff --git a/datafusion/core/src/catalog/listing_schema.rs b/datafusion/core/src/catalog/listing_schema.rs
index a9ae47ec90..a5960b21df 100644
--- a/datafusion/core/src/catalog/listing_schema.rs
+++ b/datafusion/core/src/catalog/listing_schema.rs
@@ -28,7 +28,7 @@ use crate::datasource::TableProvider;
use crate::execution::context::SessionState;
use datafusion_common::parsers::CompressionTypeVariant;
-use datafusion_common::{Constraints, DFSchema, DataFusionError, OwnedTableReference};
+use datafusion_common::{Constraints, DFSchema, DataFusionError, TableReference};
use datafusion_expr::CreateExternalTable;
use async_trait::async_trait;
@@ -129,7 +129,7 @@ impl ListingSchemaProvider {
if !self.table_exist(table_name) {
let table_url = format!("{}/{}", self.authority, table_path);
- let name = OwnedTableReference::bare(table_name);
+ let name = TableReference::bare(table_name);
let provider = self
.factory
.create(
diff --git a/datafusion/core/src/datasource/listing_table_factory.rs b/datafusion/core/src/datasource/listing_table_factory.rs
index c48082954e..cbadf163ce 100644
--- a/datafusion/core/src/datasource/listing_table_factory.rs
+++ b/datafusion/core/src/datasource/listing_table_factory.rs
@@ -171,7 +171,7 @@ mod tests {
use crate::execution::context::SessionContext;
use datafusion_common::parsers::CompressionTypeVariant;
- use datafusion_common::{Constraints, DFSchema, OwnedTableReference};
+ use datafusion_common::{Constraints, DFSchema, TableReference};
#[tokio::test]
async fn test_create_using_non_std_file_ext() {
@@ -184,7 +184,7 @@ mod tests {
let factory = ListingTableFactory::new();
let context = SessionContext::new();
let state = context.state();
- let name = OwnedTableReference::bare("foo");
+ let name = TableReference::bare("foo");
let cmd = CreateExternalTable {
name,
location: csv_file.path().to_str().unwrap().to_string(),
@@ -222,7 +222,7 @@ mod tests {
let factory = ListingTableFactory::new();
let context = SessionContext::new();
let state = context.state();
- let name = OwnedTableReference::bare("foo");
+ let name = TableReference::bare("foo");
let mut options = HashMap::new();
options.insert("format.schema_infer_max_rec".to_owned(), "1000".to_owned());
diff --git a/datafusion/core/src/execution/context/mod.rs b/datafusion/core/src/execution/context/mod.rs
index 4eaaf94ecf..1a582be301 100644
--- a/datafusion/core/src/execution/context/mod.rs
+++ b/datafusion/core/src/execution/context/mod.rs
@@ -66,7 +66,7 @@ use datafusion_common::{
config::{ConfigExtension, TableOptions},
exec_err, not_impl_err, plan_datafusion_err, plan_err,
tree_node::{TreeNode, TreeNodeRecursion, TreeNodeVisitor},
- OwnedTableReference, SchemaReference,
+ SchemaReference, TableReference,
};
use datafusion_execution::registry::SerializerRegistry;
use datafusion_expr::type_coercion::aggregates::NUMERICS;
@@ -80,7 +80,7 @@ use datafusion_physical_expr::create_first_value_accumulator;
use datafusion_sql::{
parser::{CopyToSource, CopyToStatement, DFParser},
planner::{object_name_to_table_reference, ContextProvider, ParserOptions, SqlToRel},
- ResolvedTableReference, TableReference,
+ ResolvedTableReference,
};
use async_trait::async_trait;
@@ -507,7 +507,7 @@ impl SessionContext {
&self,
cmd: &CreateExternalTable,
) -> Result<DataFrame> {
- let exist = self.table_exist(&cmd.name)?;
+ let exist = self.table_exist(cmd.name.clone())?;
if exist {
match cmd.if_not_exists {
true => return self.return_empty_dataframe(),
@@ -519,7 +519,7 @@ impl SessionContext {
let table_provider: Arc<dyn TableProvider> =
self.create_custom_table(cmd).await?;
- self.register_table(&cmd.name, table_provider)?;
+ self.register_table(cmd.name.clone(), table_provider)?;
self.return_empty_dataframe()
}
@@ -535,11 +535,11 @@ impl SessionContext {
let input = Arc::try_unwrap(input).unwrap_or_else(|e| e.as_ref().clone());
let input = self.state().optimize(&input)?;
- let table = self.table(&name).await;
+ let table = self.table(name.clone()).await;
match (if_not_exists, or_replace, table) {
(true, false, Ok(_)) => self.return_empty_dataframe(),
(false, true, Ok(_)) => {
- self.deregister_table(&name)?;
+ self.deregister_table(name.clone())?;
let schema = Arc::new(input.schema().as_ref().into());
let physical = DataFrame::new(self.state(), input);
@@ -551,7 +551,7 @@ impl SessionContext {
.with_column_defaults(column_defaults.into_iter().collect()),
);
- self.register_table(&name, table)?;
+ self.register_table(name.clone(), table)?;
self.return_empty_dataframe()
}
(true, true, Ok(_)) => {
@@ -570,7 +570,7 @@ impl SessionContext {
.with_column_defaults(column_defaults.into_iter().collect()),
);
- self.register_table(&name, table)?;
+ self.register_table(name, table)?;
self.return_empty_dataframe()
}
(false, false, Ok(_)) => exec_err!("Table '{name}' already exists"),
@@ -585,20 +585,20 @@ impl SessionContext {
definition,
} = cmd;
- let view = self.table(&name).await;
+ let view = self.table(name.clone()).await;
match (or_replace, view) {
(true, Ok(_)) => {
- self.deregister_table(&name)?;
+ self.deregister_table(name.clone())?;
let table = Arc::new(ViewTable::try_new((*input).clone(), definition)?);
- self.register_table(&name, table)?;
+ self.register_table(name, table)?;
self.return_empty_dataframe()
}
(_, Err(_)) => {
let table = Arc::new(ViewTable::try_new((*input).clone(), definition)?);
- self.register_table(&name, table)?;
+ self.register_table(name, table)?;
self.return_empty_dataframe()
}
(false, Ok(_)) => exec_err!("Table '{name}' already exists"),
@@ -674,7 +674,9 @@ impl SessionContext {
let DropTable {
name, if_exists, ..
} = cmd;
- let result = self.find_and_deregister(&name, TableType::Base).await;
+ let result = self
+ .find_and_deregister(name.clone(), TableType::Base)
+ .await;
match (result, if_exists) {
(Ok(true), _) => self.return_empty_dataframe(),
(_, true) => self.return_empty_dataframe(),
@@ -686,7 +688,9 @@ impl SessionContext {
let DropView {
name, if_exists, ..
} = cmd;
- let result = self.find_and_deregister(&name, TableType::View).await;
+ let result = self
+ .find_and_deregister(name.clone(), TableType::View)
+ .await;
match (result, if_exists) {
(Ok(true), _) => self.return_empty_dataframe(),
(_, true) => self.return_empty_dataframe(),
@@ -1134,13 +1138,14 @@ impl SessionContext {
/// Return `true` if the specified table exists in the schema provider.
pub fn table_exist(&self, table_ref: impl Into<TableReference>) -> Result<bool> {
- let table_ref = table_ref.into();
- let table = table_ref.table().to_owned();
+ let table_ref: TableReference = table_ref.into();
+ let table = table_ref.table();
+ let table_ref = table_ref.clone();
Ok(self
.state
.read()
.schema_for_ref(table_ref)?
- .table_exist(&table))
+ .table_exist(table))
}
/// Retrieves a [`DataFrame`] representing a table previously
@@ -1154,10 +1159,10 @@ impl SessionContext {
&self,
table_ref: impl Into<TableReference>,
) -> Result<DataFrame> {
- let table_ref = table_ref.into();
- let provider = self.table_provider(table_ref.to_owned_reference()).await?;
+ let table_ref: TableReference = table_ref.into();
+ let provider = self.table_provider(table_ref.clone()).await?;
let plan = LogicalPlanBuilder::scan(
- table_ref.to_owned_reference(),
+ table_ref,
provider_as_source(Arc::clone(&provider)),
None,
)?
@@ -1716,7 +1721,7 @@ impl SessionState {
pub fn resolve_table_references(
&self,
statement: &datafusion_sql::parser::Statement,
- ) -> Result<Vec<OwnedTableReference>> {
+ ) -> Result<Vec<TableReference>> {
use crate::catalog::information_schema::INFORMATION_SCHEMA_TABLES;
use datafusion_sql::parser::Statement as DFStatement;
use sqlparser::ast::*;
@@ -1816,11 +1821,10 @@ impl SessionState {
let parse_float_as_decimal =
self.config.options().sql_parser.parse_float_as_decimal;
for reference in references {
- let table = reference.table();
- let resolved = self.resolve_table_ref(&reference);
+ let resolved = &self.resolve_table_ref(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(table).await? {
+ if let Ok(schema) = self.schema_for_ref(resolved.clone()) {
+ if let Some(table) = schema.table(&resolved.table).await? {
v.insert(provider_as_source(table));
}
}
diff --git a/datafusion/core/src/physical_planner.rs b/datafusion/core/src/physical_planner.rs
index 275d639a7a..c1067d75ed 100644
--- a/datafusion/core/src/physical_planner.rs
+++ b/datafusion/core/src/physical_planner.rs
@@ -626,7 +626,7 @@ impl DefaultPhysicalPlanner {
..
}) => {
let name = table_name.table();
- let schema = session_state.schema_for_ref(table_name)?;
+ let schema = session_state.schema_for_ref(table_name.clone())?;
if let Some(provider) = schema.table(name).await? {
let input_exec = self.create_initial_plan(input, session_state).await?;
provider.insert_into(session_state, input_exec, false).await
@@ -643,7 +643,7 @@ impl DefaultPhysicalPlanner {
..
}) => {
let name = table_name.table();
- let schema = session_state.schema_for_ref(table_name)?;
+ let schema = session_state.schema_for_ref(table_name.clone())?;
if let Some(provider) = schema.table(name).await? {
let input_exec = self.create_initial_plan(input, session_state).await?;
provider.insert_into(session_state, input_exec, true).await
@@ -2687,7 +2687,7 @@ mod tests {
match ctx.read_csv(path, options).await?.into_optimized_plan()? {
LogicalPlan::TableScan(ref scan) => {
let mut scan = scan.clone();
- let table_reference = TableReference::from(name).to_owned_reference();
+ let table_reference = TableReference::from(name);
scan.table_name = table_reference;
let new_schema = scan
.projected_schema
diff --git a/datafusion/expr/src/expr.rs b/datafusion/expr/src/expr.rs
index 427c3fde7c..b11636d831 100644
--- a/datafusion/expr/src/expr.rs
+++ b/datafusion/expr/src/expr.rs
@@ -35,7 +35,7 @@ use crate::{
use arrow::datatypes::DataType;
use datafusion_common::tree_node::{Transformed, TransformedResult, TreeNode};
use datafusion_common::{
- internal_err, plan_err, Column, DFSchema, OwnedTableReference, Result, ScalarValue,
+ internal_err, plan_err, Column, DFSchema, Result, ScalarValue, TableReference,
};
use sqlparser::ast::NullTreatment;
@@ -193,7 +193,7 @@ pub struct Unnest {
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct Alias {
pub expr: Box<Expr>,
- pub relation: Option<OwnedTableReference>,
+ pub relation: Option<TableReference>,
pub name: String,
}
@@ -201,7 +201,7 @@ impl Alias {
/// Create an alias with an optional schema/field qualifier.
pub fn new(
expr: Expr,
- relation: Option<impl Into<OwnedTableReference>>,
+ relation: Option<impl Into<TableReference>>,
name: impl Into<String>,
) -> Self {
Self {
@@ -1029,7 +1029,7 @@ impl Expr {
/// Return `self AS name` alias expression with a specific qualifier
pub fn alias_qualified(
self,
- relation: Option<impl Into<OwnedTableReference>>,
+ relation: Option<impl Into<TableReference>>,
name: impl Into<String>,
) -> Expr {
match self {
diff --git a/datafusion/expr/src/expr_rewriter/mod.rs b/datafusion/expr/src/expr_rewriter/mod.rs
index 60942adb63..d678fe7ee3 100644
--- a/datafusion/expr/src/expr_rewriter/mod.rs
+++ b/datafusion/expr/src/expr_rewriter/mod.rs
@@ -29,6 +29,7 @@ use datafusion_common::config::ConfigOptions;
use datafusion_common::tree_node::{
Transformed, TransformedResult, TreeNode, TreeNodeRewriter,
};
+use datafusion_common::TableReference;
use datafusion_common::{Column, DFSchema, Result};
mod order_by;
@@ -162,13 +163,20 @@ pub fn create_col_from_scalar_expr(
subqry_alias: String,
) -> Result<Column> {
match scalar_expr {
- Expr::Alias(Alias { name, .. }) => Ok(Column::new(Some(subqry_alias), name)),
- Expr::Column(Column { relation: _, name }) => {
- Ok(Column::new(Some(subqry_alias), name))
- }
+ Expr::Alias(Alias { name, .. }) => Ok(Column::new(
+ Some::<TableReference>(subqry_alias.into()),
+ name,
+ )),
+ Expr::Column(Column { relation: _, name }) => Ok(Column::new(
+ Some::<TableReference>(subqry_alias.into()),
+ name,
+ )),
_ => {
let scalar_column = scalar_expr.display_name()?;
- Ok(Column::new(Some(subqry_alias), scalar_column))
+ Ok(Column::new(
+ Some::<TableReference>(subqry_alias.into()),
+ scalar_column,
+ ))
}
}
}
@@ -286,7 +294,7 @@ mod test {
use crate::{col, lit, Cast};
use arrow::datatypes::{DataType, Field, Schema};
use datafusion_common::tree_node::{TreeNode, TreeNodeRewriter};
- use datafusion_common::{DFSchema, OwnedTableReference, ScalarValue};
+ use datafusion_common::{DFSchema, ScalarValue, TableReference};
#[derive(Default)]
struct RecordingRewriter {
@@ -401,7 +409,7 @@ mod test {
}
fn make_schema_with_empty_metadata(
- qualifiers: Vec<Option<OwnedTableReference>>,
+ qualifiers: Vec<Option<TableReference>>,
fields: Vec<&str>,
) -> DFSchema {
let fields = fields
diff --git a/datafusion/expr/src/expr_schema.rs b/datafusion/expr/src/expr_schema.rs
index de157f3cda..39892d9e0c 100644
--- a/datafusion/expr/src/expr_schema.rs
+++ b/datafusion/expr/src/expr_schema.rs
@@ -29,7 +29,7 @@ use arrow::compute::can_cast_types;
use arrow::datatypes::{DataType, Field};
use datafusion_common::{
internal_err, not_impl_err, plan_datafusion_err, plan_err, Column, ExprSchema,
- OwnedTableReference, Result,
+ Result, TableReference,
};
use std::collections::HashMap;
use std::sync::Arc;
@@ -49,7 +49,7 @@ pub trait ExprSchemable {
fn to_field(
&self,
input_schema: &dyn ExprSchema,
- ) -> Result<(Option<OwnedTableReference>, Arc<Field>)>;
+ ) -> Result<(Option<TableReference>, Arc<Field>)>;
/// cast to a type with respect to a schema
fn cast_to(self, cast_to_type: &DataType, schema: &dyn ExprSchema) -> Result<Expr>;
@@ -442,7 +442,7 @@ impl ExprSchemable for Expr {
fn to_field(
&self,
input_schema: &dyn ExprSchema,
- ) -> Result<(Option<OwnedTableReference>, Arc<Field>)> {
+ ) -> Result<(Option<TableReference>, Arc<Field>)> {
match self {
Expr::Column(c) => {
let (data_type, nullable) = self.data_type_and_nullable(input_schema)?;
@@ -719,7 +719,7 @@ mod tests {
let schema = builder.finish();
let dfschema = DFSchema::from_field_specific_qualified_schema(
- vec![Some("table_name"), None],
+ vec![Some("table_name".into()), None],
&Arc::new(schema),
)
.unwrap();
diff --git a/datafusion/expr/src/logical_plan/builder.rs b/datafusion/expr/src/logical_plan/builder.rs
index ad0fc263cc..beac5a7f4e 100644
--- a/datafusion/expr/src/logical_plan/builder.rs
+++ b/datafusion/expr/src/logical_plan/builder.rs
@@ -52,8 +52,8 @@ use datafusion_common::config::FormatOptions;
use datafusion_common::display::ToStringifiedPlan;
use datafusion_common::{
get_target_functional_dependencies, not_impl_err, plan_datafusion_err, plan_err,
- Column, DFSchema, DFSchemaRef, DataFusionError, OwnedTableReference, Result,
- ScalarValue, TableReference, ToDFSchema, UnnestOptions,
+ Column, DFSchema, DFSchemaRef, DataFusionError, Result, ScalarValue, TableReference,
+ ToDFSchema, UnnestOptions,
};
/// Default table name for unnamed table
@@ -258,7 +258,7 @@ impl LogicalPlanBuilder {
/// let scan = LogicalPlanBuilder::scan(table_reference, table, None);
/// ```
pub fn scan(
- table_name: impl Into<OwnedTableReference>,
+ table_name: impl Into<TableReference>,
table_source: Arc<dyn TableSource>,
projection: Option<Vec<usize>>,
) -> Result<Self> {
@@ -285,7 +285,7 @@ impl LogicalPlanBuilder {
/// Create a [DmlStatement] for inserting the contents of this builder into the named table
pub fn insert_into(
input: LogicalPlan,
- table_name: impl Into<OwnedTableReference>,
+ table_name: impl Into<TableReference>,
table_schema: &Schema,
overwrite: bool,
) -> Result<Self> {
@@ -307,7 +307,7 @@ impl LogicalPlanBuilder {
/// Convert a table provider into a builder with a TableScan
pub fn scan_with_filters(
- table_name: impl Into<OwnedTableReference>,
+ table_name: impl Into<TableReference>,
table_source: Arc<dyn TableSource>,
projection: Option<Vec<usize>>,
filters: Vec<Expr>,
@@ -403,7 +403,7 @@ impl LogicalPlanBuilder {
}
/// Apply an alias
- pub fn alias(self, alias: impl Into<OwnedTableReference>) -> Result<Self> {
+ pub fn alias(self, alias: impl Into<TableReference>) -> Result<Self> {
subquery_alias(self.plan, alias).map(Self::from)
}
@@ -1152,13 +1152,13 @@ pub fn build_join_schema(
join_type: &JoinType,
) -> Result<DFSchema> {
fn nullify_fields<'a>(
- fields: impl Iterator<Item = (Option<&'a OwnedTableReference>, &'a Arc<Field>)>,
- ) -> Vec<(Option<OwnedTableReference>, Arc<Field>)> {
+ fields: impl Iterator<Item = (Option<&'a TableReference>, &'a Arc<Field>)>,
+ ) -> Vec<(Option<TableReference>, Arc<Field>)> {
fields
.map(|(q, f)| {
// TODO: find a good way to do that
let field = f.as_ref().clone().with_nullable(true);
- (q.map(|r| r.to_owned_reference()), Arc::new(field))
+ (q.cloned(), Arc::new(field))
})
.collect()
}
@@ -1166,22 +1166,21 @@ pub fn build_join_schema(
let right_fields = right.iter();
let left_fields = left.iter();
- let qualified_fields: Vec<(Option<OwnedTableReference>, Arc<Field>)> = match join_type
- {
+ let qualified_fields: Vec<(Option<TableReference>, Arc<Field>)> = match join_type {
JoinType::Inner => {
// left then right
let left_fields = left_fields
- .map(|(q, f)| (q.map(|r| r.to_owned_reference()), f.clone()))
+ .map(|(q, f)| (q.cloned(), f.clone()))
.collect::<Vec<_>>();
let right_fields = right_fields
- .map(|(q, f)| (q.map(|r| r.to_owned_reference()), f.clone()))
+ .map(|(q, f)| (q.cloned(), f.clone()))
.collect::<Vec<_>>();
left_fields.into_iter().chain(right_fields).collect()
}
JoinType::Left => {
// left then right, right set to nullable in case of not matched scenario
let left_fields = left_fields
- .map(|(q, f)| (q.map(|r| r.to_owned_reference()), f.clone()))
+ .map(|(q, f)| (q.cloned(), f.clone()))
.collect::<Vec<_>>();
left_fields
.into_iter()
@@ -1191,7 +1190,7 @@ pub fn build_join_schema(
JoinType::Right => {
// left then right, left set to nullable in case of not matched scenario
let right_fields = right_fields
- .map(|(q, f)| (q.map(|r| r.to_owned_reference()), f.clone()))
+ .map(|(q, f)| (q.cloned(), f.clone()))
.collect::<Vec<_>>();
nullify_fields(left_fields)
.into_iter()
@@ -1207,15 +1206,11 @@ pub fn build_join_schema(
}
JoinType::LeftSemi | JoinType::LeftAnti => {
// Only use the left side for the schema
- left_fields
- .map(|(q, f)| (q.map(|r| r.to_owned_reference()), f.clone()))
- .collect()
+ left_fields.map(|(q, f)| (q.cloned(), f.clone())).collect()
}
JoinType::RightSemi | JoinType::RightAnti => {
// Only use the right side for the schema
- right_fields
- .map(|(q, f)| (q.map(|r| r.to_owned_reference()), f.clone()))
- .collect()
+ right_fields.map(|(q, f)| (q.cloned(), f.clone())).collect()
}
};
let func_dependencies = left.functional_dependencies().join(
@@ -1417,7 +1412,7 @@ pub fn project(
/// Create a SubqueryAlias to wrap a LogicalPlan.
pub fn subquery_alias(
plan: LogicalPlan,
- alias: impl Into<OwnedTableReference>,
+ alias: impl Into<TableReference>,
) -> Result<LogicalPlan> {
SubqueryAlias::try_new(Arc::new(plan), alias).map(LogicalPlan::SubqueryAlias)
}
@@ -1444,8 +1439,7 @@ pub fn table_scan_with_filters(
let table_source = table_source(table_schema);
let name = name
.map(|n| n.into())
- .unwrap_or_else(|| OwnedTableReference::bare(UNNAMED_TABLE))
- .to_owned_reference();
+ .unwrap_or_else(|| TableReference::bare(UNNAMED_TABLE));
LogicalPlanBuilder::scan_with_filters(name, table_source, projection, filters)
}
@@ -1603,7 +1597,7 @@ mod tests {
use crate::{col, expr, expr_fn::exists, in_subquery, lit, scalar_subquery, sum};
use arrow::datatypes::{DataType, Field};
- use datafusion_common::{OwnedTableReference, SchemaError, TableReference};
+ use datafusion_common::{SchemaError, TableReference};
#[test]
fn plan_builder_simple() -> Result<()> {
@@ -1905,7 +1899,7 @@ mod tests {
SchemaError::AmbiguousReference {
field:
Column {
- relation: Some(OwnedTableReference::Bare { table }),
+ relation: Some(TableReference::Bare { table }),
name,
},
},
@@ -1935,7 +1929,7 @@ mod tests {
SchemaError::AmbiguousReference {
field:
Column {
- relation: Some(OwnedTableReference::Bare { table }),
+ relation: Some(TableReference::Bare { table }),
name,
},
},
diff --git a/datafusion/expr/src/logical_plan/ddl.rs b/datafusion/expr/src/logical_plan/ddl.rs
index 968c40c8bf..8d72c9a8b0 100644
--- a/datafusion/expr/src/logical_plan/ddl.rs
+++ b/datafusion/expr/src/logical_plan/ddl.rs
@@ -26,9 +26,7 @@ use crate::{Expr, LogicalPlan, Volatility};
use arrow::datatypes::DataType;
use datafusion_common::parsers::CompressionTypeVariant;
-use datafusion_common::{
- Constraints, DFSchemaRef, OwnedSchemaReference, OwnedTableReference,
-};
+use datafusion_common::{Constraints, DFSchemaRef, SchemaReference, TableReference};
use sqlparser::ast::Ident;
/// Various types of DDL (CREATE / DROP) catalog manipulation
@@ -187,7 +185,7 @@ pub struct CreateExternalTable {
/// The table schema
pub schema: DFSchemaRef,
/// The table name
- pub name: OwnedTableReference,
+ pub name: TableReference,
/// The physical location
pub location: String,
/// The file type of physical file
@@ -239,7 +237,7 @@ impl Hash for CreateExternalTable {
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct CreateMemoryTable {
/// The table name
- pub name: OwnedTableReference,
+ pub name: TableReference,
/// The list of constraints in the schema, such as primary key, unique, etc.
pub constraints: Constraints,
/// The logical plan
@@ -256,7 +254,7 @@ pub struct CreateMemoryTable {
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct CreateView {
/// The table name
- pub name: OwnedTableReference,
+ pub name: TableReference,
/// The logical plan
pub input: Arc<LogicalPlan>,
/// Option to not error if table already exists
@@ -291,7 +289,7 @@ pub struct CreateCatalogSchema {
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct DropTable {
/// The table name
- pub name: OwnedTableReference,
+ pub name: TableReference,
/// If the table exists
pub if_exists: bool,
/// Dummy schema
@@ -302,7 +300,7 @@ pub struct DropTable {
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct DropView {
/// The view name
- pub name: OwnedTableReference,
+ pub name: TableReference,
/// If the view exists
pub if_exists: bool,
/// Dummy schema
@@ -313,7 +311,7 @@ pub struct DropView {
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct DropCatalogSchema {
/// The schema name
- pub name: OwnedSchemaReference,
+ pub name: SchemaReference,
/// If the schema exists
pub if_exists: bool,
/// Whether drop should cascade
diff --git a/datafusion/expr/src/logical_plan/dml.rs b/datafusion/expr/src/logical_plan/dml.rs
index 6ab06a57c1..9c0fe0f304 100644
--- a/datafusion/expr/src/logical_plan/dml.rs
+++ b/datafusion/expr/src/logical_plan/dml.rs
@@ -21,7 +21,7 @@ use std::hash::{Hash, Hasher};
use std::sync::Arc;
use datafusion_common::config::FormatOptions;
-use datafusion_common::{DFSchemaRef, OwnedTableReference};
+use datafusion_common::{DFSchemaRef, TableReference};
use crate::LogicalPlan;
@@ -63,7 +63,7 @@ impl Hash for CopyTo {
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct DmlStatement {
/// The table name
- pub table_name: OwnedTableReference,
+ pub table_name: TableReference,
/// The schema of the table (must align with Rel input)
pub table_schema: DFSchemaRef,
/// The type of operation to perform
diff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rs
index 7a28b085cb..3d40dcae0e 100644
--- a/datafusion/expr/src/logical_plan/plan.rs
+++ b/datafusion/expr/src/logical_plan/plan.rs
@@ -50,7 +50,7 @@ use datafusion_common::tree_node::{
use datafusion_common::{
aggregate_functional_dependencies, internal_err, plan_err, Column, Constraints,
DFSchema, DFSchemaRef, DataFusionError, Dependency, FunctionalDependence,
- FunctionalDependencies, OwnedTableReference, ParamValues, Result, UnnestOptions,
+ FunctionalDependencies, ParamValues, Result, TableReference, UnnestOptions,
};
// backwards compatibility
@@ -1850,7 +1850,7 @@ pub struct SubqueryAlias {
/// The incoming logical plan
pub input: Arc<LogicalPlan>,
/// The alias for the input relation
- pub alias: OwnedTableReference,
+ pub alias: TableReference,
/// The schema with qualified field names
pub schema: DFSchemaRef,
}
@@ -1858,7 +1858,7 @@ pub struct SubqueryAlias {
impl SubqueryAlias {
pub fn try_new(
plan: Arc<LogicalPlan>,
- alias: impl Into<OwnedTableReference>,
+ alias: impl Into<TableReference>,
) -> Result<Self> {
let alias = alias.into();
let fields = change_redundant_column(plan.schema().fields());
@@ -1869,7 +1869,7 @@ impl SubqueryAlias {
// functional dependencies:
let func_dependencies = plan.schema().functional_dependencies().clone();
let schema = DFSchemaRef::new(
- DFSchema::try_from_qualified_schema(&alias, &schema)?
+ DFSchema::try_from_qualified_schema(alias.clone(), &schema)?
.with_functional_dependencies(func_dependencies)?,
);
Ok(SubqueryAlias {
@@ -2009,7 +2009,7 @@ pub struct Window {
impl Window {
/// Create a new window operator.
pub fn try_new(window_expr: Vec<Expr>, input: Arc<LogicalPlan>) -> Result<Self> {
- let fields: Vec<(Option<OwnedTableReference>, Arc<Field>)> = input
+ let fields: Vec<(Option<TableReference>, Arc<Field>)> = input
.schema()
.iter()
.map(|(q, f)| (q.cloned(), f.clone()))
@@ -2080,7 +2080,7 @@ impl Window {
#[derive(Clone)]
pub struct TableScan {
/// The name of the table
- pub table_name: OwnedTableReference,
+ pub table_name: TableReference,
/// The source of the table
pub source: Arc<dyn TableSource>,
/// Optional column indices to use as a projection
@@ -2119,7 +2119,7 @@ impl TableScan {
/// Initialize TableScan with appropriate schema from the given
/// arguments.
pub fn try_new(
- table_name: impl Into<OwnedTableReference>,
+ table_name: impl Into<TableReference>,
table_source: Arc<dyn TableSource>,
projection: Option<Vec<usize>>,
filters: Vec<Expr>,
diff --git a/datafusion/expr/src/utils.rs b/datafusion/expr/src/utils.rs
index 0edcfa4bb5..2b126da154 100644
--- a/datafusion/expr/src/utils.rs
+++ b/datafusion/expr/src/utils.rs
@@ -34,8 +34,8 @@ use arrow::datatypes::{DataType, Field, Schema, TimeUnit};
use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion};
use datafusion_common::utils::get_at_indices;
use datafusion_common::{
- internal_err, plan_datafusion_err, plan_err, Column, DFSchema, DFSchemaRef,
- OwnedTableReference, Result, ScalarValue, TableReference,
+ internal_err, plan_datafusion_err, plan_err, Column, DFSchema, DFSchemaRef, Result,
+ ScalarValue, TableReference,
};
use sqlparser::ast::{ExceptSelectItem, ExcludeSelectItem, WildcardAdditionalOptions};
@@ -741,7 +741,7 @@ fn agg_cols(agg: &Aggregate) -> Vec<Column> {
fn exprlist_to_fields_aggregate(
exprs: &[Expr],
agg: &Aggregate,
-) -> Result<Vec<(Option<OwnedTableReference>, Arc<Field>)>> {
+) -> Result<Vec<(Option<TableReference>, Arc<Field>)>> {
let agg_cols = agg_cols(agg);
let mut fields = vec![];
for expr in exprs {
@@ -760,7 +760,7 @@ fn exprlist_to_fields_aggregate(
pub fn exprlist_to_fields(
exprs: &[Expr],
plan: &LogicalPlan,
-) -> Result<Vec<(Option<OwnedTableReference>, Arc<Field>)>> {
+) -> Result<Vec<(Option<TableReference>, Arc<Field>)>> {
// when dealing with aggregate plans we cannot simply look in the aggregate output schema
// because it will contain columns representing complex expressions (such a column named
// `GROUPING(person.state)` so in order to resolve `person.state` in this case we need to
diff --git a/datafusion/optimizer/src/analyzer/function_rewrite.rs b/datafusion/optimizer/src/analyzer/function_rewrite.rs
index 15b5265df9..78f65c5b82 100644
--- a/datafusion/optimizer/src/analyzer/function_rewrite.rs
+++ b/datafusion/optimizer/src/analyzer/function_rewrite.rs
@@ -67,8 +67,10 @@ impl ApplyFunctionRewrites {
let mut schema = merge_schema(new_inputs.iter().collect());
if let LogicalPlan::TableScan(ts) = plan {
- let source_schema =
- DFSchema::try_from_qualified_schema(&ts.table_name, &ts.source.schema())?;
+ let source_schema = DFSchema::try_from_qualified_schema(
+ ts.table_name.clone(),
+ &ts.source.schema(),
+ )?;
schema.merge(&source_schema);
}
diff --git a/datafusion/optimizer/src/analyzer/type_coercion.rs b/datafusion/optimizer/src/analyzer/type_coercion.rs
index fbbd9a9456..04de243fba 100644
--- a/datafusion/optimizer/src/analyzer/type_coercion.rs
+++ b/datafusion/optimizer/src/analyzer/type_coercion.rs
@@ -86,8 +86,10 @@ fn analyze_internal(
let mut schema = merge_schema(new_inputs.iter().collect());
if let LogicalPlan::TableScan(ts) = plan {
- let source_schema =
- DFSchema::try_from_qualified_schema(&ts.table_name, &ts.source.schema())?;
+ let source_schema = DFSchema::try_from_qualified_schema(
+ ts.table_name.clone(),
+ &ts.source.schema(),
+ )?;
schema.merge(&source_schema);
}
diff --git a/datafusion/optimizer/src/simplify_expressions/simplify_exprs.rs b/datafusion/optimizer/src/simplify_expressions/simplify_exprs.rs
index 70b163acc2..8213af7698 100644
--- a/datafusion/optimizer/src/simplify_expressions/simplify_exprs.rs
+++ b/datafusion/optimizer/src/simplify_expressions/simplify_exprs.rs
@@ -80,7 +80,7 @@ impl SimplifyExpressions {
// Thus, use the full schema of the inner provider without any
// projection applied for simplification
Arc::new(DFSchema::try_from_qualified_schema(
- &scan.table_name,
+ scan.table_name.clone(),
&scan.source.schema(),
)?)
} else {
diff --git a/datafusion/optimizer/src/unwrap_cast_in_comparison.rs b/datafusion/optimizer/src/unwrap_cast_in_comparison.rs
index e4a777e7c7..f573ac6937 100644
--- a/datafusion/optimizer/src/unwrap_cast_in_comparison.rs
+++ b/datafusion/optimizer/src/unwrap_cast_in_comparison.rs
@@ -93,8 +93,10 @@ impl OptimizerRule for UnwrapCastInComparison {
let mut schema = merge_schema(plan.inputs());
if let LogicalPlan::TableScan(ts) = plan {
- let source_schema =
- DFSchema::try_from_qualified_schema(&ts.table_name, &ts.source.schema())?;
+ let source_schema = DFSchema::try_from_qualified_schema(
+ ts.table_name.clone(),
+ &ts.source.schema(),
+ )?;
schema.merge(&source_schema);
}
diff --git a/datafusion/proto/proto/datafusion.proto b/datafusion/proto/proto/datafusion.proto
index 6eb4a6b109..7f967657f5 100644
--- a/datafusion/proto/proto/datafusion.proto
+++ b/datafusion/proto/proto/datafusion.proto
@@ -107,7 +107,7 @@ message LogicalExprNodeCollection {
message ListingTableScanNode {
reserved 1; // was string table_name
- OwnedTableReference table_name = 14;
+ TableReference table_name = 14;
repeated string paths = 2;
string file_extension = 3;
ProjectionColumns projection = 4;
@@ -126,7 +126,7 @@ message ListingTableScanNode {
message ViewTableScanNode {
reserved 1; // was string table_name
- OwnedTableReference table_name = 6;
+ TableReference table_name = 6;
LogicalPlanNode input = 2;
Schema schema = 3;
ProjectionColumns projection = 4;
@@ -136,7 +136,7 @@ message ViewTableScanNode {
// Logical Plan to Scan a CustomTableProvider registered at runtime
message CustomTableScanNode {
reserved 1; // was string table_name
- OwnedTableReference table_name = 6;
+ TableReference table_name = 6;
ProjectionColumns projection = 2;
Schema schema = 3;
repeated LogicalExprNode filters = 4;
@@ -201,7 +201,7 @@ message Constraints{
message CreateExternalTableNode {
reserved 1; // was string name
- OwnedTableReference name = 12;
+ TableReference name = 12;
string location = 2;
string file_type = 3;
bool has_header = 4;
@@ -238,14 +238,14 @@ message CreateCatalogNode {
}
message DropViewNode {
- OwnedTableReference name = 1;
+ TableReference name = 1;
bool if_exists = 2;
DfSchema schema = 3;
}
message CreateViewNode {
reserved 1; // was string name
- OwnedTableReference name = 5;
+ TableReference name = 5;
LogicalPlanNode input = 2;
bool or_replace = 3;
string definition = 4;
@@ -357,7 +357,7 @@ message SelectionExecNode {
message SubqueryAliasNode {
reserved 2; // Was string alias
LogicalPlanNode input = 1;
- OwnedTableReference alias = 3;
+ TableReference alias = 3;
}
// logical expressions
@@ -513,7 +513,7 @@ message Not {
message AliasNode {
LogicalExprNode expr = 1;
string alias = 2;
- repeated OwnedTableReference relation = 3;
+ repeated TableReference relation = 3;
}
message BinaryExprNode {
@@ -1169,7 +1169,7 @@ message FullTableReference {
string table = 3;
}
-message OwnedTableReference {
+message TableReference {
oneof table_reference_enum {
BareTableReference bare = 1;
PartialTableReference partial = 2;
diff --git a/datafusion/proto/src/generated/pbjson.rs b/datafusion/proto/src/generated/pbjson.rs
index 658f06cfc1..966d7f7f74 100644
--- a/datafusion/proto/src/generated/pbjson.rs
+++ b/datafusion/proto/src/generated/pbjson.rs
@@ -15867,128 +15867,6 @@ impl<'de> serde::Deserialize<'de> for OptimizedPhysicalPlanType {
deserializer.deserialize_struct("datafusion.OptimizedPhysicalPlanType", FIELDS, GeneratedVisitor)
}
}
-impl serde::Serialize for OwnedTableReference {
- #[allow(deprecated)]
- fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
- where
- S: serde::Serializer,
- {
- use serde::ser::SerializeStruct;
- let mut len = 0;
- if self.table_reference_enum.is_some() {
- len += 1;
- }
- let mut struct_ser = serializer.serialize_struct("datafusion.OwnedTableReference", len)?;
- if let Some(v) = self.table_reference_enum.as_ref() {
- match v {
- owned_table_reference::TableReferenceEnum::Bare(v) => {
- struct_ser.serialize_field("bare", v)?;
- }
- owned_table_reference::TableReferenceEnum::Partial(v) => {
- struct_ser.serialize_field("partial", v)?;
- }
- owned_table_reference::TableReferenceEnum::Full(v) => {
- struct_ser.serialize_field("full", v)?;
- }
- }
- }
- struct_ser.end()
- }
-}
-impl<'de> serde::Deserialize<'de> for OwnedTableReference {
- #[allow(deprecated)]
- fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
- where
- D: serde::Deserializer<'de>,
- {
- const FIELDS: &[&str] = &[
- "bare",
- "partial",
- "full",
- ];
-
- #[allow(clippy::enum_variant_names)]
- enum GeneratedField {
- Bare,
- Partial,
- Full,
- }
- impl<'de> serde::Deserialize<'de> for GeneratedField {
- fn deserialize<D>(deserializer: D) -> std::result::Result<GeneratedField, D::Error>
- where
- D: serde::Deserializer<'de>,
- {
- struct GeneratedVisitor;
-
- impl<'de> serde::de::Visitor<'de> for GeneratedVisitor {
- type Value = GeneratedField;
-
- fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(formatter, "expected one of: {:?}", &FIELDS)
- }
-
- #[allow(unused_variables)]
- fn visit_str<E>(self, value: &str) -> std::result::Result<GeneratedField, E>
- where
- E: serde::de::Error,
- {
- match value {
- "bare" => Ok(GeneratedField::Bare),
- "partial" => Ok(GeneratedField::Partial),
- "full" => Ok(GeneratedField::Full),
- _ => Err(serde::de::Error::unknown_field(value, FIELDS)),
- }
- }
- }
- deserializer.deserialize_identifier(GeneratedVisitor)
- }
- }
- struct GeneratedVisitor;
- impl<'de> serde::de::Visitor<'de> for GeneratedVisitor {
- type Value = OwnedTableReference;
-
- fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- formatter.write_str("struct datafusion.OwnedTableReference")
- }
-
- fn visit_map<V>(self, mut map_: V) -> std::result::Result<OwnedTableReference, V::Error>
- where
- V: serde::de::MapAccess<'de>,
- {
- let mut table_reference_enum__ = None;
- while let Some(k) = map_.next_key()? {
- match k {
- GeneratedField::Bare => {
- if table_reference_enum__.is_some() {
- return Err(serde::de::Error::duplicate_field("bare"));
- }
- table_reference_enum__ = map_.next_value::<::std::option::Option<_>>()?.map(owned_table_reference::TableReferenceEnum::Bare)
-;
- }
- GeneratedField::Partial => {
- if table_reference_enum__.is_some() {
- return Err(serde::de::Error::duplicate_field("partial"));
- }
- table_reference_enum__ = map_.next_value::<::std::option::Option<_>>()?.map(owned_table_reference::TableReferenceEnum::Partial)
-;
- }
- GeneratedField::Full => {
- if table_reference_enum__.is_some() {
- return Err(serde::de::Error::duplicate_field("full"));
- }
- table_reference_enum__ = map_.next_value::<::std::option::Option<_>>()?.map(owned_table_reference::TableReferenceEnum::Full)
-;
- }
- }
- }
- Ok(OwnedTableReference {
- table_reference_enum: table_reference_enum__,
- })
- }
- }
- deserializer.deserialize_struct("datafusion.OwnedTableReference", FIELDS, GeneratedVisitor)
- }
-}
impl serde::Serialize for ParquetFormat {
#[allow(deprecated)]
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
@@ -26297,6 +26175,128 @@ impl<'de> serde::Deserialize<'de> for TableParquetOptions {
deserializer.deserialize_struct("datafusion.TableParquetOptions", FIELDS, GeneratedVisitor)
}
}
+impl serde::Serialize for TableReference {
+ #[allow(deprecated)]
+ fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
+ where
+ S: serde::Serializer,
+ {
+ use serde::ser::SerializeStruct;
+ let mut len = 0;
+ if self.table_reference_enum.is_some() {
+ len += 1;
+ }
+ let mut struct_ser = serializer.serialize_struct("datafusion.TableReference", len)?;
+ if let Some(v) = self.table_reference_enum.as_ref() {
+ match v {
+ table_reference::TableReferenceEnum::Bare(v) => {
+ struct_ser.serialize_field("bare", v)?;
+ }
+ table_reference::TableReferenceEnum::Partial(v) => {
+ struct_ser.serialize_field("partial", v)?;
+ }
+ table_reference::TableReferenceEnum::Full(v) => {
+ struct_ser.serialize_field("full", v)?;
+ }
+ }
+ }
+ struct_ser.end()
+ }
+}
+impl<'de> serde::Deserialize<'de> for TableReference {
+ #[allow(deprecated)]
+ fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
+ where
+ D: serde::Deserializer<'de>,
+ {
+ const FIELDS: &[&str] = &[
+ "bare",
+ "partial",
+ "full",
+ ];
+
+ #[allow(clippy::enum_variant_names)]
+ enum GeneratedField {
+ Bare,
+ Partial,
+ Full,
+ }
+ impl<'de> serde::Deserialize<'de> for GeneratedField {
+ fn deserialize<D>(deserializer: D) -> std::result::Result<GeneratedField, D::Error>
+ where
+ D: serde::Deserializer<'de>,
+ {
+ struct GeneratedVisitor;
+
+ impl<'de> serde::de::Visitor<'de> for GeneratedVisitor {
+ type Value = GeneratedField;
+
+ fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(formatter, "expected one of: {:?}", &FIELDS)
+ }
+
+ #[allow(unused_variables)]
+ fn visit_str<E>(self, value: &str) -> std::result::Result<GeneratedField, E>
+ where
+ E: serde::de::Error,
+ {
+ match value {
+ "bare" => Ok(GeneratedField::Bare),
+ "partial" => Ok(GeneratedField::Partial),
+ "full" => Ok(GeneratedField::Full),
+ _ => Err(serde::de::Error::unknown_field(value, FIELDS)),
+ }
+ }
+ }
+ deserializer.deserialize_identifier(GeneratedVisitor)
+ }
+ }
+ struct GeneratedVisitor;
+ impl<'de> serde::de::Visitor<'de> for GeneratedVisitor {
+ type Value = TableReference;
+
+ fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ formatter.write_str("struct datafusion.TableReference")
+ }
+
+ fn visit_map<V>(self, mut map_: V) -> std::result::Result<TableReference, V::Error>
+ where
+ V: serde::de::MapAccess<'de>,
+ {
+ let mut table_reference_enum__ = None;
+ while let Some(k) = map_.next_key()? {
+ match k {
+ GeneratedField::Bare => {
+ if table_reference_enum__.is_some() {
+ return Err(serde::de::Error::duplicate_field("bare"));
+ }
+ table_reference_enum__ = map_.next_value::<::std::option::Option<_>>()?.map(table_reference::TableReferenceEnum::Bare)
+;
+ }
+ GeneratedField::Partial => {
+ if table_reference_enum__.is_some() {
+ return Err(serde::de::Error::duplicate_field("partial"));
+ }
+ table_reference_enum__ = map_.next_value::<::std::option::Option<_>>()?.map(table_reference::TableReferenceEnum::Partial)
+;
+ }
+ GeneratedField::Full => {
+ if table_reference_enum__.is_some() {
+ return Err(serde::de::Error::duplicate_field("full"));
+ }
+ table_reference_enum__ = map_.next_value::<::std::option::Option<_>>()?.map(table_reference::TableReferenceEnum::Full)
+;
+ }
+ }
+ }
+ Ok(TableReference {
+ table_reference_enum: table_reference_enum__,
+ })
+ }
+ }
+ deserializer.deserialize_struct("datafusion.TableReference", FIELDS, GeneratedVisitor)
+ }
+}
impl serde::Serialize for TimeUnit {
#[allow(deprecated)]
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
diff --git a/datafusion/proto/src/generated/prost.rs b/datafusion/proto/src/generated/prost.rs
index ea13bac0f6..c94aa1f4ed 100644
--- a/datafusion/proto/src/generated/prost.rs
+++ b/datafusion/proto/src/generated/prost.rs
@@ -144,7 +144,7 @@ pub struct LogicalExprNodeCollection {
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ListingTableScanNode {
#[prost(message, optional, tag = "14")]
- pub table_name: ::core::option::Option<OwnedTableReference>,
+ pub table_name: ::core::option::Option<TableReference>,
#[prost(string, repeated, tag = "2")]
pub paths: ::prost::alloc::vec::Vec<::prost::alloc::string::String>,
#[prost(string, tag = "3")]
@@ -185,7 +185,7 @@ pub mod listing_table_scan_node {
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ViewTableScanNode {
#[prost(message, optional, tag = "6")]
- pub table_name: ::core::option::Option<OwnedTableReference>,
+ pub table_name: ::core::option::Option<TableReference>,
#[prost(message, optional, boxed, tag = "2")]
pub input: ::core::option::Option<::prost::alloc::boxed::Box<LogicalPlanNode>>,
#[prost(message, optional, tag = "3")]
@@ -200,7 +200,7 @@ pub struct ViewTableScanNode {
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CustomTableScanNode {
#[prost(message, optional, tag = "6")]
- pub table_name: ::core::option::Option<OwnedTableReference>,
+ pub table_name: ::core::option::Option<TableReference>,
#[prost(message, optional, tag = "2")]
pub projection: ::core::option::Option<ProjectionColumns>,
#[prost(message, optional, tag = "3")]
@@ -320,7 +320,7 @@ pub struct Constraints {
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CreateExternalTableNode {
#[prost(message, optional, tag = "12")]
- pub name: ::core::option::Option<OwnedTableReference>,
+ pub name: ::core::option::Option<TableReference>,
#[prost(string, tag = "2")]
pub location: ::prost::alloc::string::String,
#[prost(string, tag = "3")]
@@ -390,7 +390,7 @@ pub struct CreateCatalogNode {
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct DropViewNode {
#[prost(message, optional, tag = "1")]
- pub name: ::core::option::Option<OwnedTableReference>,
+ pub name: ::core::option::Option<TableReference>,
#[prost(bool, tag = "2")]
pub if_exists: bool,
#[prost(message, optional, tag = "3")]
@@ -400,7 +400,7 @@ pub struct DropViewNode {
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CreateViewNode {
#[prost(message, optional, tag = "5")]
- pub name: ::core::option::Option<OwnedTableReference>,
+ pub name: ::core::option::Option<TableReference>,
#[prost(message, optional, boxed, tag = "2")]
pub input: ::core::option::Option<::prost::alloc::boxed::Box<LogicalPlanNode>>,
#[prost(bool, tag = "3")]
@@ -563,7 +563,7 @@ pub struct SubqueryAliasNode {
#[prost(message, optional, boxed, tag = "1")]
pub input: ::core::option::Option<::prost::alloc::boxed::Box<LogicalPlanNode>>,
#[prost(message, optional, tag = "3")]
- pub alias: ::core::option::Option<OwnedTableReference>,
+ pub alias: ::core::option::Option<TableReference>,
}
/// logical expressions
#[allow(clippy::derive_partial_eq_without_eq)]
@@ -803,7 +803,7 @@ pub struct AliasNode {
#[prost(string, tag = "2")]
pub alias: ::prost::alloc::string::String,
#[prost(message, repeated, tag = "3")]
- pub relation: ::prost::alloc::vec::Vec<OwnedTableReference>,
+ pub relation: ::prost::alloc::vec::Vec<TableReference>,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
@@ -1551,14 +1551,14 @@ pub struct FullTableReference {
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
-pub struct OwnedTableReference {
- #[prost(oneof = "owned_table_reference::TableReferenceEnum", tags = "1, 2, 3")]
+pub struct TableReference {
+ #[prost(oneof = "table_reference::TableReferenceEnum", tags = "1, 2, 3")]
pub table_reference_enum: ::core::option::Option<
- owned_table_reference::TableReferenceEnum,
+ table_reference::TableReferenceEnum,
>,
}
-/// Nested message and enum types in `OwnedTableReference`.
-pub mod owned_table_reference {
+/// Nested message and enum types in `TableReference`.
+pub mod table_reference {
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum TableReferenceEnum {
diff --git a/datafusion/proto/src/logical_plan/from_proto.rs b/datafusion/proto/src/logical_plan/from_proto.rs
index 30d01cc758..96b3b5942e 100644
--- a/datafusion/proto/src/logical_plan/from_proto.rs
+++ b/datafusion/proto/src/logical_plan/from_proto.rs
@@ -30,8 +30,8 @@ use arrow::{
use datafusion::execution::registry::FunctionRegistry;
use datafusion_common::{
arrow_datafusion_err, internal_err, plan_datafusion_err, Column, Constraint,
- Constraints, DFSchema, DFSchemaRef, DataFusionError, OwnedTableReference, Result,
- ScalarValue,
+ Constraints, DFSchema, DFSchemaRef, DataFusionError, Result, ScalarValue,
+ TableReference,
};
use datafusion_expr::expr::Unnest;
use datafusion_expr::expr::{Alias, Placeholder};
@@ -170,20 +170,19 @@ impl TryFrom<&protobuf::DfSchema> for DFSchema {
fn try_from(df_schema: &protobuf::DfSchema) -> Result<Self, Self::Error> {
let df_fields = df_schema.columns.clone();
- let qualifiers_and_fields: Vec<(Option<OwnedTableReference>, Arc<Field>)> =
- df_fields
- .iter()
- .map(|df_field| {
- let field: Field = df_field.field.as_ref().required("field")?;
- Ok((
- df_field
- .qualifier
- .as_ref()
- .map(|q| q.relation.clone().into()),
- Arc::new(field),
- ))
- })
- .collect::<Result<Vec<_>, Error>>()?;
+ let qualifiers_and_fields: Vec<(Option<TableReference>, Arc<Field>)> = df_fields
+ .iter()
+ .map(|df_field| {
+ let field: Field = df_field.field.as_ref().required("field")?;
+ Ok((
+ df_field
+ .qualifier
+ .as_ref()
+ .map(|q| q.relation.clone().into()),
+ Arc::new(field),
+ ))
+ })
+ .collect::<Result<Vec<_>, Error>>()?;
Ok(DFSchema::new_with_metadata(
qualifiers_and_fields,
@@ -211,28 +210,28 @@ impl From<protobuf::WindowFrameUnits> for WindowFrameUnits {
}
}
-impl TryFrom<protobuf::OwnedTableReference> for OwnedTableReference {
+impl TryFrom<protobuf::TableReference> for TableReference {
type Error = Error;
- fn try_from(value: protobuf::OwnedTableReference) -> Result<Self, Self::Error> {
- use protobuf::owned_table_reference::TableReferenceEnum;
+ fn try_from(value: protobuf::TableReference) -> Result<Self, Self::Error> {
+ use protobuf::table_reference::TableReferenceEnum;
let table_reference_enum = value
.table_reference_enum
.ok_or_else(|| Error::required("table_reference_enum"))?;
match table_reference_enum {
TableReferenceEnum::Bare(protobuf::BareTableReference { table }) => {
- Ok(OwnedTableReference::bare(table))
+ Ok(TableReference::bare(table))
}
TableReferenceEnum::Partial(protobuf::PartialTableReference {
schema,
table,
- }) => Ok(OwnedTableReference::partial(schema, table)),
+ }) => Ok(TableReference::partial(schema, table)),
TableReferenceEnum::Full(protobuf::FullTableReference {
catalog,
schema,
table,
- }) => Ok(OwnedTableReference::full(catalog, schema, table)),
+ }) => Ok(TableReference::full(catalog, schema, table)),
}
}
}
@@ -1089,7 +1088,7 @@ pub fn parse_expr(
alias
.relation
.first()
- .map(|r| OwnedTableReference::try_from(r.clone()))
+ .map(|r| TableReference::try_from(r.clone()))
.transpose()?,
alias.alias.clone(),
))),
diff --git a/datafusion/proto/src/logical_plan/mod.rs b/datafusion/proto/src/logical_plan/mod.rs
index 9b3b677e3c..cccfb0c273 100644
--- a/datafusion/proto/src/logical_plan/mod.rs
+++ b/datafusion/proto/src/logical_plan/mod.rs
@@ -46,7 +46,7 @@ use datafusion::{
};
use datafusion_common::{
context, internal_err, not_impl_err, parsers::CompressionTypeVariant,
- plan_datafusion_err, DataFusionError, OwnedTableReference, Result,
+ plan_datafusion_err, DataFusionError, Result, TableReference,
};
use datafusion_expr::{
dml,
@@ -181,10 +181,10 @@ macro_rules! into_logical_plan {
}};
}
-fn from_owned_table_reference(
- table_ref: Option<&protobuf::OwnedTableReference>,
+fn from_table_reference(
+ table_ref: Option<&protobuf::TableReference>,
error_context: &str,
-) -> Result<OwnedTableReference> {
+) -> Result<TableReference> {
let table_ref = table_ref.ok_or_else(|| {
DataFusionError::Internal(format!(
"Protobuf deserialization error, {error_context} was missing required field name."
@@ -407,10 +407,8 @@ impl AsLogicalPlan for LogicalPlanNode {
.get_file_statistic_cache(),
);
- let table_name = from_owned_table_reference(
- scan.table_name.as_ref(),
- "ListingTableScan",
- )?;
+ let table_name =
+ from_table_reference(scan.table_name.as_ref(), "ListingTableScan")?;
LogicalPlanBuilder::scan_with_filters(
table_name,
@@ -445,7 +443,7 @@ impl AsLogicalPlan for LogicalPlanNode {
)?;
let table_name =
- from_owned_table_reference(scan.table_name.as_ref(), "CustomScan")?;
+ from_table_reference(scan.table_name.as_ref(), "CustomScan")?;
LogicalPlanBuilder::scan_with_filters(
table_name,
@@ -553,7 +551,7 @@ impl AsLogicalPlan for LogicalPlanNode {
Ok(LogicalPlan::Ddl(DdlStatement::CreateExternalTable(CreateExternalTable {
schema: pb_schema.try_into()?,
- name: from_owned_table_reference(create_extern_table.name.as_ref(), "CreateExternalTable")?,
+ name: from_table_reference(create_extern_table.name.as_ref(), "CreateExternalTable")?,
location: create_extern_table.location.clone(),
file_type: create_extern_table.file_type.clone(),
has_header: create_extern_table.has_header,
@@ -586,10 +584,7 @@ impl AsLogicalPlan for LogicalPlanNode {
};
Ok(LogicalPlan::Ddl(DdlStatement::CreateView(CreateView {
- name: from_owned_table_reference(
- create_view.name.as_ref(),
- "CreateView",
- )?,
+ name: from_table_reference(create_view.name.as_ref(), "CreateView")?,
input: Arc::new(plan),
or_replace: create_view.or_replace,
definition,
@@ -642,7 +637,7 @@ impl AsLogicalPlan for LogicalPlanNode {
LogicalPlanType::SubqueryAlias(aliased_relation) => {
let input: LogicalPlan =
into_logical_plan!(aliased_relation.input, ctx, extension_codec)?;
- let alias = from_owned_table_reference(
+ let alias = from_table_reference(
aliased_relation.alias.as_ref(),
"SubqueryAlias",
)?;
@@ -819,7 +814,7 @@ impl AsLogicalPlan for LogicalPlanNode {
let provider = ViewTable::try_new(input, definition)?;
let table_name =
- from_owned_table_reference(scan.table_name.as_ref(), "ViewScan")?;
+ from_table_reference(scan.table_name.as_ref(), "ViewScan")?;
LogicalPlanBuilder::scan(
table_name,
@@ -842,7 +837,7 @@ impl AsLogicalPlan for LogicalPlanNode {
}
LogicalPlanType::DropView(dropview) => Ok(datafusion_expr::LogicalPlan::Ddl(
datafusion_expr::DdlStatement::DropView(DropView {
- name: from_owned_table_reference(dropview.name.as_ref(), "DropView")?,
+ name: from_table_reference(dropview.name.as_ref(), "DropView")?,
if_exists: dropview.if_exists,
schema: Arc::new(convert_required!(dropview.schema)?),
}),
@@ -1235,7 +1230,7 @@ impl AsLogicalPlan for LogicalPlanNode {
logical_plan_type: Some(LogicalPlanType::SubqueryAlias(Box::new(
protobuf::SubqueryAliasNode {
input: Some(Box::new(input)),
- alias: Some(alias.to_owned_reference().into()),
+ alias: Some((*alias).clone().into()),
},
))),
})
diff --git a/datafusion/proto/src/logical_plan/to_proto.rs b/datafusion/proto/src/logical_plan/to_proto.rs
index 4382ee0ff0..a10edb3932 100644
--- a/datafusion/proto/src/logical_plan/to_proto.rs
+++ b/datafusion/proto/src/logical_plan/to_proto.rs
@@ -45,8 +45,7 @@ use arrow::{
record_batch::RecordBatch,
};
use datafusion_common::{
- Column, Constraint, Constraints, DFSchema, DFSchemaRef, OwnedTableReference,
- ScalarValue,
+ Column, Constraint, Constraints, DFSchema, DFSchemaRef, ScalarValue, TableReference,
};
use datafusion_expr::expr::{
self, AggregateFunctionDefinition, Alias, Between, BinaryExpr, Cast, GetFieldAccess,
@@ -1455,22 +1454,22 @@ impl From<&IntervalUnit> for protobuf::IntervalUnit {
}
}
-impl From<OwnedTableReference> for protobuf::OwnedTableReference {
- fn from(t: OwnedTableReference) -> Self {
- use protobuf::owned_table_reference::TableReferenceEnum;
+impl From<TableReference> for protobuf::TableReference {
+ fn from(t: TableReference) -> Self {
+ use protobuf::table_reference::TableReferenceEnum;
let table_reference_enum = match t {
- OwnedTableReference::Bare { table } => {
+ TableReference::Bare { table } => {
TableReferenceEnum::Bare(protobuf::BareTableReference {
table: table.to_string(),
})
}
- OwnedTableReference::Partial { schema, table } => {
+ TableReference::Partial { schema, table } => {
TableReferenceEnum::Partial(protobuf::PartialTableReference {
schema: schema.to_string(),
table: table.to_string(),
})
}
- OwnedTableReference::Full {
+ TableReference::Full {
catalog,
schema,
table,
@@ -1481,7 +1480,7 @@ impl From<OwnedTableReference> for protobuf::OwnedTableReference {
}),
};
- protobuf::OwnedTableReference {
+ protobuf::TableReference {
table_reference_enum: Some(table_reference_enum),
}
}
diff --git a/datafusion/sql/src/expr/identifier.rs b/datafusion/sql/src/expr/identifier.rs
index 1d386b21a1..713ad6f72c 100644
--- a/datafusion/sql/src/expr/identifier.rs
+++ b/datafusion/sql/src/expr/identifier.rs
@@ -18,8 +18,8 @@
use crate::planner::{ContextProvider, PlannerContext, SqlToRel};
use arrow_schema::Field;
use datafusion_common::{
- internal_err, plan_datafusion_err, Column, DFSchema, DataFusionError,
- OwnedTableReference, Result, TableReference,
+ internal_err, plan_datafusion_err, Column, DFSchema, DataFusionError, Result,
+ TableReference,
};
use datafusion_expr::{Case, Expr};
use sqlparser::ast::{Expr as SQLExpr, Ident};
@@ -173,8 +173,6 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
// safe unwrap as s can never be empty or exceed the bounds
let (relation, column_name) =
form_identifier(s).unwrap();
- let relation =
- relation.map(|r| r.to_owned_reference());
Ok(Expr::Column(Column::new(relation, column_name)))
}
}
@@ -182,7 +180,6 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
let s = &ids[0..ids.len()];
// safe unwrap as s can never be empty or exceed the bounds
let (relation, column_name) = form_identifier(s).unwrap();
- let relation = relation.map(|r| r.to_owned_reference());
Ok(Expr::Column(Column::new(relation, column_name)))
}
}
@@ -273,7 +270,7 @@ fn search_dfschema<'ids, 'schema>(
schema: &'schema DFSchema,
) -> Option<(
&'schema Field,
- Option<&'schema OwnedTableReference>,
+ Option<&'schema TableReference>,
&'ids [String],
)> {
generate_schema_search_terms(ids).find_map(|(qualifier, column, nested_names)| {
diff --git a/datafusion/sql/src/planner.rs b/datafusion/sql/src/planner.rs
index d2182962b9..ebd48b78a9 100644
--- a/datafusion/sql/src/planner.rs
+++ b/datafusion/sql/src/planner.rs
@@ -31,11 +31,11 @@ use sqlparser::ast::{ColumnDef as SQLColumnDef, ColumnOption};
use sqlparser::ast::{DataType as SQLDataType, Ident, ObjectName, TableAlias};
use datafusion_common::config::ConfigOptions;
+use datafusion_common::TableReference;
use datafusion_common::{
not_impl_err, plan_err, unqualified_field_not_found, DFSchema, DataFusionError,
Result,
};
-use datafusion_common::{OwnedTableReference, TableReference};
use datafusion_expr::logical_plan::{LogicalPlan, LogicalPlanBuilder};
use datafusion_expr::utils::find_column_exprs;
use datafusion_expr::TableSource;
@@ -483,7 +483,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
pub(crate) fn object_name_to_table_reference(
&self,
object_name: ObjectName,
- ) -> Result<OwnedTableReference> {
+ ) -> Result<TableReference> {
object_name_to_table_reference(
object_name,
self.options.enable_ident_normalization,
@@ -491,7 +491,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
}
}
-/// Create a [`OwnedTableReference`] after normalizing the specified ObjectName
+/// Create a [`TableReference`] after normalizing the specified ObjectName
///
/// Examples
/// ```text
@@ -504,17 +504,17 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
pub fn object_name_to_table_reference(
object_name: ObjectName,
enable_normalization: bool,
-) -> Result<OwnedTableReference> {
+) -> Result<TableReference> {
// use destructure to make it clear no fields on ObjectName are ignored
let ObjectName(idents) = object_name;
idents_to_table_reference(idents, enable_normalization)
}
-/// Create a [`OwnedTableReference`] after normalizing the specified identifier
+/// Create a [`TableReference`] after normalizing the specified identifier
pub(crate) fn idents_to_table_reference(
idents: Vec<Ident>,
enable_normalization: bool,
-) -> Result<OwnedTableReference> {
+) -> Result<TableReference> {
struct IdentTaker(Vec<Ident>);
/// take the next identifier from the back of idents, panic'ing if
/// there are none left
@@ -530,18 +530,18 @@ pub(crate) fn idents_to_table_reference(
match taker.0.len() {
1 => {
let table = taker.take(enable_normalization);
- Ok(OwnedTableReference::bare(table))
+ Ok(TableReference::bare(table))
}
2 => {
let table = taker.take(enable_normalization);
let schema = taker.take(enable_normalization);
- Ok(OwnedTableReference::partial(schema, table))
+ Ok(TableReference::partial(schema, table))
}
3 => {
let table = taker.take(enable_normalization);
let schema = taker.take(enable_normalization);
let catalog = taker.take(enable_normalization);
- Ok(OwnedTableReference::full(catalog, schema, table))
+ Ok(TableReference::full(catalog, schema, table))
}
_ => plan_err!("Unsupported compound identifier '{:?}'", taker.0),
}
diff --git a/datafusion/sql/src/statement.rs b/datafusion/sql/src/statement.rs
index 69d1b71e4f..b8c9172621 100644
--- a/datafusion/sql/src/statement.rs
+++ b/datafusion/sql/src/statement.rs
@@ -34,8 +34,8 @@ use datafusion_common::parsers::CompressionTypeVariant;
use datafusion_common::{
exec_err, not_impl_err, plan_datafusion_err, plan_err, schema_err,
unqualified_field_not_found, Column, Constraints, DFSchema, DFSchemaRef,
- DataFusionError, FileType, OwnedTableReference, Result, ScalarValue, SchemaError,
- SchemaReference, TableReference, ToDFSchema,
+ DataFusionError, FileType, Result, ScalarValue, SchemaError, SchemaReference,
+ TableReference, ToDFSchema,
};
use datafusion_expr::dml::CopyTo;
use datafusion_expr::expr_rewriter::normalize_col_with_schemas_and_ambiguity_check;
@@ -994,7 +994,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
self.build_order_by(order_exprs, &df_schema, &mut planner_context)?;
// External tables do not support schemas at the moment, so the name is just a table name
- let name = OwnedTableReference::bare(name);
+ let name = TableReference::bare(name);
let constraints =
Constraints::new_from_table_constraints(&all_constraints, &df_schema)?;
Ok(LogicalPlan::Ddl(DdlStatement::CreateExternalTable(