diff --git a/datafusion-cli/src/catalog.rs b/datafusion-cli/src/catalog.rs index fb13ccddc3d00..f38659635e2f0 100644 --- a/datafusion-cli/src/catalog.rs +++ b/datafusion-cli/src/catalog.rs @@ -81,15 +81,15 @@ impl DynamicObjectStoreCatalogProvider { } impl CatalogProvider for DynamicObjectStoreCatalogProvider { - fn schema_names(&self) -> Vec { + fn schema_names(&self) -> Result> { self.inner.schema_names() } - fn schema(&self, name: &str) -> Option> { + fn schema(&self, name: &str) -> Result>> { let state = self.state.clone(); - self.inner.schema(name).map(|schema| { + Ok(self.inner.schema(name)?.map(|schema| { Arc::new(DynamicObjectStoreSchemaProvider::new(schema, state)) as _ - }) + })) } fn register_schema( @@ -120,7 +120,7 @@ impl DynamicObjectStoreSchemaProvider { #[async_trait] impl SchemaProvider for DynamicObjectStoreSchemaProvider { - fn table_names(&self) -> Vec { + fn table_names(&self) -> Result> { self.inner.table_names() } @@ -195,7 +195,7 @@ impl SchemaProvider for DynamicObjectStoreSchemaProvider { self.inner.deregister_table(name) } - fn table_exist(&self, name: &str) -> bool { + fn table_exist(&self, name: &str) -> Result { self.inner.table_exist(name) } } @@ -230,12 +230,22 @@ mod tests { ctx.state().catalog_list().clone(), ctx.state_weak_ref(), ) as &dyn CatalogProviderList; + let catalog_name = provider + .catalog_names() + .first() + .expect("default catalog should exist") + .clone(); let catalog = provider - .catalog(provider.catalog_names().first().unwrap()) - .unwrap(); + .catalog(&catalog_name) + .expect("default catalog should be retrievable"); + let schema_names = catalog + .schema_names() + .expect("schema names lookup should succeed"); + let schema_name = schema_names.first().expect("default schema should exist"); let schema = catalog - .schema(catalog.schema_names().first().unwrap()) - .unwrap(); + .schema(schema_name) + .expect("schema lookup should succeed") + .expect("default schema should be retrievable"); (ctx, schema) } diff --git a/datafusion-examples/examples/data_io/catalog.rs b/datafusion-examples/examples/data_io/catalog.rs index e3fa18a53dada..23f5077c0a730 100644 --- a/datafusion-examples/examples/data_io/catalog.rs +++ b/datafusion-examples/examples/data_io/catalog.rs @@ -165,9 +165,9 @@ impl DirSchema { #[async_trait] impl SchemaProvider for DirSchema { - fn table_names(&self) -> Vec { + fn table_names(&self) -> Result> { let tables = self.tables.read().unwrap(); - tables.keys().cloned().collect::>() + Ok(tables.keys().cloned().collect::>()) } async fn table(&self, name: &str) -> Result>> { @@ -175,9 +175,9 @@ impl SchemaProvider for DirSchema { Ok(tables.get(name).cloned()) } - fn table_exist(&self, name: &str) -> bool { + fn table_exist(&self, name: &str) -> Result { let tables = self.tables.read().unwrap(); - tables.contains_key(name) + Ok(tables.contains_key(name)) } fn register_table( @@ -224,20 +224,14 @@ impl CatalogProvider for DirCatalog { Ok(Some(schema)) } - fn schema_names(&self) -> Vec { + fn schema_names(&self) -> Result> { let schemas = self.schemas.read().unwrap(); - schemas.keys().cloned().collect() + Ok(schemas.keys().cloned().collect()) } - fn schema(&self, name: &str) -> Option> { + fn schema(&self, name: &str) -> Result>> { let schemas = self.schemas.read().unwrap(); - let maybe_schema = schemas.get(name); - if let Some(schema) = maybe_schema { - let schema = schema.clone() as Arc; - Some(schema) - } else { - None - } + Ok(schemas.get(name).cloned()) } } diff --git a/datafusion-examples/examples/flight/sql_server.rs b/datafusion-examples/examples/flight/sql_server.rs index 276770b1a906e..c7930058ba7ed 100644 --- a/datafusion-examples/examples/flight/sql_server.rs +++ b/datafusion-examples/examples/flight/sql_server.rs @@ -150,7 +150,7 @@ impl FlightSqlServiceImpl { } } - async fn tables(&self, ctx: Arc) -> RecordBatch { + async fn tables(&self, ctx: Arc) -> Result { let schema = Arc::new(Schema::new(vec![ Field::new("catalog_name", DataType::Utf8, true), Field::new("db_schema_name", DataType::Utf8, true), @@ -163,12 +163,32 @@ impl FlightSqlServiceImpl { let mut names = vec![]; let mut types = vec![]; for catalog in ctx.catalog_names() { - let catalog_provider = ctx.catalog(&catalog).unwrap(); - for schema in catalog_provider.schema_names() { - let schema_provider = catalog_provider.schema(&schema).unwrap(); - for table in schema_provider.table_names() { - let table_provider = - schema_provider.table(&table).await.unwrap().unwrap(); + let catalog_provider = ctx.catalog(&catalog).ok_or_else(|| { + Status::internal(format!("Catalog not found: {catalog}")) + })?; + for schema in catalog_provider.schema_names().map_err(|e| { + Status::internal(format!("Error looking up schema names: {e}")) + })? { + let schema_provider = catalog_provider + .schema(&schema) + .map_err(|e| { + Status::internal(format!("Error looking up schema: {e}")) + })? + .ok_or_else(|| { + Status::internal(format!("Schema not found: {schema}")) + })?; + for table in schema_provider.table_names().map_err(|e| { + Status::internal(format!("Error looking up table names: {e}")) + })? { + let table_provider = schema_provider + .table(&table) + .await + .map_err(|e| { + Status::internal(format!("Error looking up table: {e}")) + })? + .ok_or_else(|| { + Status::internal(format!("Table not found: {table}")) + })?; catalogs.push(catalog.clone()); schemas.push(schema.clone()); names.push(table.clone()); @@ -184,7 +204,7 @@ impl FlightSqlServiceImpl { .map(|i| Arc::new(StringArray::from(i)) as ArrayRef) .collect::>(), ) - .unwrap() + .map_err(|e| Status::internal(format!("Error constructing record batch: {e}"))) } fn remove_plan(&self, handle: &str) -> Result<(), Status> { @@ -327,7 +347,7 @@ impl FlightSqlService for FlightSqlServiceImpl { ) -> Result, Status> { info!("get_flight_info_tables"); let ctx = self.get_ctx(&request)?; - let data = self.tables(ctx).await; + let data = self.tables(ctx).await?; let schema = data.schema(); let uuid = Uuid::new_v4().hyphenated().to_string(); diff --git a/datafusion-examples/examples/udf/table_list_udtf.rs b/datafusion-examples/examples/udf/table_list_udtf.rs index 73ba67d810bfa..0a66ffb461a32 100644 --- a/datafusion-examples/examples/udf/table_list_udtf.rs +++ b/datafusion-examples/examples/udf/table_list_udtf.rs @@ -78,11 +78,11 @@ impl TableFunctionImpl for TableListUdtf { let Some(catalog) = catalog_list.catalog(&catalog_name) else { continue; }; - for schema_name in catalog.schema_names() { - let Some(schema) = catalog.schema(&schema_name) else { + for schema_name in catalog.schema_names()? { + let Some(schema) = catalog.schema(&schema_name)? else { continue; }; - for table_name in schema.table_names() { + for table_name in schema.table_names()? { let Some(provider) = block_in_place(|| { Handle::current().block_on(schema.table(&table_name)) })? diff --git a/datafusion/catalog/src/async.rs b/datafusion/catalog/src/async.rs index 8dff8596c8369..1d1a9861dfba8 100644 --- a/datafusion/catalog/src/async.rs +++ b/datafusion/catalog/src/async.rs @@ -24,8 +24,8 @@ impl SchemaProvider for ResolvedSchemaProvider { self.owner_name.as_deref() } - fn table_names(&self) -> Vec { - self.cached_tables.keys().cloned().collect() + fn table_names(&self) -> Result> { + Ok(self.cached_tables.keys().cloned().collect()) } async fn table(&self, name: &str) -> Result>> { @@ -48,8 +48,8 @@ impl SchemaProvider for ResolvedSchemaProvider { ) } - fn table_exist(&self, name: &str) -> bool { - self.cached_tables.contains_key(name) + fn table_exist(&self, name: &str) -> Result { + Ok(self.cached_tables.contains_key(name)) } } @@ -98,12 +98,12 @@ struct ResolvedCatalogProvider { cached_schemas: HashMap>, } impl CatalogProvider for ResolvedCatalogProvider { - fn schema_names(&self) -> Vec { - self.cached_schemas.keys().cloned().collect() + fn schema_names(&self) -> Result> { + Ok(self.cached_schemas.keys().cloned().collect()) } - fn schema(&self, name: &str) -> Option> { - self.cached_schemas.get(name).cloned() + fn schema(&self, name: &str) -> Result>> { + Ok(self.cached_schemas.get(name).cloned()) } } @@ -579,12 +579,19 @@ mod tests { ); for schema_ref in found_schemas { - let schema = cached_provider.schema(schema_ref); + let schema = cached_provider + .schema(schema_ref) + .expect("schema lookup should succeed"); assert!(schema.is_some()); } for schema_ref in not_found_schemas { - assert!(cached_provider.schema(schema_ref).is_none()); + assert!( + cached_provider + .schema(schema_ref) + .expect("schema lookup should succeed") + .is_none() + ); } } @@ -716,7 +723,8 @@ mod tests { .unwrap(); let schema = catalog .schema(table_ref.schema().unwrap_or(MOCK_SCHEMA)) - .unwrap(); + .expect("schema lookup should succeed") + .expect("default schema should exist"); assert!(schema.table(table_ref.table()).await.unwrap().is_some()); } } diff --git a/datafusion/catalog/src/dynamic_file/catalog.rs b/datafusion/catalog/src/dynamic_file/catalog.rs index 689c2d6c0d4f1..ed9619f43b916 100644 --- a/datafusion/catalog/src/dynamic_file/catalog.rs +++ b/datafusion/catalog/src/dynamic_file/catalog.rs @@ -77,17 +77,20 @@ impl DynamicFileCatalogProvider { } impl CatalogProvider for DynamicFileCatalogProvider { - fn schema_names(&self) -> Vec { + fn schema_names(&self) -> datafusion_common::Result> { self.inner.schema_names() } - fn schema(&self, name: &str) -> Option> { - self.inner.schema(name).map(|schema| { + fn schema( + &self, + name: &str, + ) -> datafusion_common::Result>> { + Ok(self.inner.schema(name)?.map(|schema| { Arc::new(DynamicFileSchemaProvider::new( schema, Arc::clone(&self.factory), )) as _ - }) + })) } fn register_schema( @@ -123,7 +126,7 @@ impl DynamicFileSchemaProvider { #[async_trait] impl SchemaProvider for DynamicFileSchemaProvider { - fn table_names(&self) -> Vec { + fn table_names(&self) -> datafusion_common::Result> { self.inner.table_names() } @@ -153,7 +156,7 @@ impl SchemaProvider for DynamicFileSchemaProvider { self.inner.deregister_table(name) } - fn table_exist(&self, name: &str) -> bool { + fn table_exist(&self, name: &str) -> datafusion_common::Result { self.inner.table_exist(name) } } diff --git a/datafusion/catalog/src/information_schema.rs b/datafusion/catalog/src/information_schema.rs index bd92a72c4f24c..c0ff40e4fce1e 100644 --- a/datafusion/catalog/src/information_schema.rs +++ b/datafusion/catalog/src/information_schema.rs @@ -219,7 +219,7 @@ impl InformationSchemaProvider { self.table(&table_ref.table).await? } else { catalog - .schema(&table_ref.schema) + .schema(&table_ref.schema)? .ok_or_else(not_found)? .table(&table_ref.table) .await? @@ -468,11 +468,11 @@ impl InformationSchemaConfig { catalog_name: &str, catalog: &dyn CatalogProvider, ) -> Result<(), DataFusionError> { - for schema_name in catalog.schema_names() { + for schema_name in catalog.schema_names()? { if schema_name != INFORMATION_SCHEMA { // schema name may not exist in the catalog, so we need to check - if let Some(schema) = catalog.schema(&schema_name) { - for table_name in schema.table_names() { + if let Some(schema) = catalog.schema(&schema_name)? { + for table_name in schema.table_names()? { if let Some(table_type) = schema.table_type(&table_name).await? { builder.add_table( catalog_name, @@ -504,7 +504,7 @@ impl InformationSchemaConfig { builder: &mut InformationSchemataBuilder, ) -> Result<(), DataFusionError> { for (catalog_name, catalog) in self.catalogs()? { - Self::add_schemata(builder, &catalog_name, catalog.as_ref()); + Self::add_schemata(builder, &catalog_name, catalog.as_ref())?; } Ok(()) } @@ -513,15 +513,16 @@ impl InformationSchemaConfig { builder: &mut InformationSchemataBuilder, catalog_name: &str, catalog: &dyn CatalogProvider, - ) { - for schema_name in catalog.schema_names() { + ) -> Result<(), DataFusionError> { + for schema_name in catalog.schema_names()? { if schema_name != INFORMATION_SCHEMA - && let Some(schema) = catalog.schema(&schema_name) + && let Some(schema) = catalog.schema(&schema_name)? { let schema_owner = schema.owner_name(); builder.add_schemata(catalog_name, &schema_name, schema_owner); } } + Ok(()) } async fn make_views( @@ -539,11 +540,11 @@ impl InformationSchemaConfig { catalog_name: &str, catalog: &dyn CatalogProvider, ) -> Result<(), DataFusionError> { - for schema_name in catalog.schema_names() { + for schema_name in catalog.schema_names()? { if schema_name != INFORMATION_SCHEMA { // schema name may not exist in the catalog, so we need to check - if let Some(schema) = catalog.schema(&schema_name) { - for table_name in schema.table_names() { + if let Some(schema) = catalog.schema(&schema_name)? { + for table_name in schema.table_names()? { if let Some(table) = schema.table(&table_name).await? { builder.add_view( catalog_name, @@ -575,11 +576,11 @@ impl InformationSchemaConfig { catalog_name: &str, catalog: &dyn CatalogProvider, ) -> Result<(), DataFusionError> { - for schema_name in catalog.schema_names() { + for schema_name in catalog.schema_names()? { if schema_name != INFORMATION_SCHEMA { // schema name may not exist in the catalog, so we need to check - if let Some(schema) = catalog.schema(&schema_name) { - for table_name in schema.table_names() { + if let Some(schema) = catalog.schema(&schema_name)? { + for table_name in schema.table_names()? { if let Some(table) = schema.table(&table_name).await? { for (field_position, field) in table.schema().fields().iter().enumerate() @@ -927,11 +928,11 @@ fn remove_native_type_prefix(native_type: &NativeType) -> String { #[async_trait] impl SchemaProvider for InformationSchemaProvider { - fn table_names(&self) -> Vec { - INFORMATION_SCHEMA_TABLES + fn table_names(&self) -> Result> { + Ok(INFORMATION_SCHEMA_TABLES .iter() .map(|t| (*t).to_string()) - .collect() + .collect()) } async fn table( @@ -941,8 +942,8 @@ impl SchemaProvider for InformationSchemaProvider { self.config.get_table(name) } - fn table_exist(&self, name: &str) -> bool { - INFORMATION_SCHEMA_TABLES.contains(&name.to_ascii_lowercase().as_str()) + fn table_exist(&self, name: &str) -> Result { + Ok(INFORMATION_SCHEMA_TABLES.contains(&name.to_ascii_lowercase().as_str())) } } @@ -1339,11 +1340,11 @@ mod tests { ) } - fn table_names(&self) -> Vec { - vec!["atable".to_string()] + fn table_names(&self) -> Result> { + Ok(vec!["atable".to_string()]) } - fn table_exist(&self, _: &str) -> bool { + fn table_exist(&self, _: &str) -> Result { unimplemented!("not required for these tests") } } @@ -1367,12 +1368,12 @@ mod tests { } impl CatalogProvider for Fixture { - fn schema_names(&self) -> Vec { - vec!["aschema".to_string()] + fn schema_names(&self) -> Result> { + Ok(vec!["aschema".to_string()]) } - fn schema(&self, _: &str) -> Option> { - Some(Arc::new(Self)) + fn schema(&self, _: &str) -> Result>> { + Ok(Some(Arc::new(Self))) } } } diff --git a/datafusion/catalog/src/listing_schema.rs b/datafusion/catalog/src/listing_schema.rs index 14bb4dc145a5b..bc42705a25a49 100644 --- a/datafusion/catalog/src/listing_schema.rs +++ b/datafusion/catalog/src/listing_schema.rs @@ -105,7 +105,7 @@ impl ListingSchemaProvider { .to_string() .ok_or_else(|| internal_datafusion_err!("Cannot parse file name!"))?; - if !self.table_exist(table_name) { + if !self.table_exist(table_name)? { let table_url = format!("{}/{}", self.authority, table_path); let name = TableReference::bare(table_name); @@ -132,13 +132,14 @@ impl ListingSchemaProvider { #[async_trait] impl SchemaProvider for ListingSchemaProvider { - fn table_names(&self) -> Vec { - self.tables + fn table_names(&self) -> datafusion_common::Result> { + Ok(self + .tables .lock() .expect("Can't lock tables") .keys() .map(|it| it.to_string()) - .collect() + .collect()) } async fn table( @@ -172,11 +173,12 @@ impl SchemaProvider for ListingSchemaProvider { Ok(self.tables.lock().expect("Can't lock tables").remove(name)) } - fn table_exist(&self, name: &str) -> bool { - self.tables + fn table_exist(&self, name: &str) -> datafusion_common::Result { + Ok(self + .tables .lock() .expect("Can't lock tables") - .contains_key(name) + .contains_key(name)) } } diff --git a/datafusion/catalog/src/memory/catalog.rs b/datafusion/catalog/src/memory/catalog.rs index 091f62faf5b9c..a8e102fb0ba93 100644 --- a/datafusion/catalog/src/memory/catalog.rs +++ b/datafusion/catalog/src/memory/catalog.rs @@ -90,12 +90,12 @@ impl Default for MemoryCatalogProvider { } impl CatalogProvider for MemoryCatalogProvider { - fn schema_names(&self) -> Vec { - self.schemas.iter().map(|s| s.key().clone()).collect() + fn schema_names(&self) -> Result> { + Ok(self.schemas.iter().map(|s| s.key().clone()).collect()) } - fn schema(&self, name: &str) -> Option> { - self.schemas.get(name).map(|s| Arc::clone(s.value())) + fn schema(&self, name: &str) -> Result>> { + Ok(self.schemas.get(name).map(|s| Arc::clone(s.value()))) } fn register_schema( @@ -111,29 +111,27 @@ impl CatalogProvider for MemoryCatalogProvider { name: &str, cascade: bool, ) -> Result>> { - if let Some(schema) = self.schema(name) { - let table_names = schema.table_names(); - match (table_names.is_empty(), cascade) { - (true, _) | (false, true) => { - let (_, removed) = self.schemas.remove(name).unwrap(); - Ok(Some(removed)) - } - (false, false) => exec_err!( + let Some(schema) = self.schema(name)? else { + return Ok(None); + }; + if !cascade { + let table_names = schema.table_names()?; + if !table_names.is_empty() { + return exec_err!( "Cannot drop schema {} containing tables: {}", name, itertools::join(table_names.iter(), ", ") - ), + ); } - } else { - Ok(None) } + Ok(self.schemas.remove(name).map(|(_, removed)| removed)) } fn prepare_deregister_catalog(&self, cascade: bool) -> Result<()> { if !cascade && !self.schemas.is_empty() { return exec_err!( "Cannot drop catalog containing schemas: {}", - itertools::join(self.schema_names().iter(), ", ") + itertools::join(self.schema_names()?.iter(), ", ") ); } diff --git a/datafusion/catalog/src/memory/schema.rs b/datafusion/catalog/src/memory/schema.rs index 2c081f84a8167..1e7f0e0d11968 100644 --- a/datafusion/catalog/src/memory/schema.rs +++ b/datafusion/catalog/src/memory/schema.rs @@ -33,11 +33,12 @@ impl Default for MemorySchemaProvider { #[async_trait] impl SchemaProvider for MemorySchemaProvider { - fn table_names(&self) -> Vec { - self.tables + fn table_names(&self) -> datafusion_common::Result> { + Ok(self + .tables .iter() .map(|table| table.key().clone()) - .collect() + .collect()) } async fn table( @@ -52,7 +53,7 @@ impl SchemaProvider for MemorySchemaProvider { name: String, table: Arc, ) -> datafusion_common::Result>> { - if self.table_exist(name.as_str()) { + if self.table_exist(name.as_str())? { return exec_err!("The table {name} already exists"); } Ok(self.tables.insert(name, table)) @@ -65,7 +66,7 @@ impl SchemaProvider for MemorySchemaProvider { Ok(self.tables.remove(name).map(|(_, table)| table)) } - fn table_exist(&self, name: &str) -> bool { - self.tables.contains_key(name) + fn table_exist(&self, name: &str) -> datafusion_common::Result { + Ok(self.tables.contains_key(name)) } } diff --git a/datafusion/core/src/execution/context/mod.rs b/datafusion/core/src/execution/context/mod.rs index b008542b47329..aabe9a3062dad 100644 --- a/datafusion/core/src/execution/context/mod.rs +++ b/datafusion/core/src/execution/context/mod.rs @@ -306,9 +306,9 @@ impl SessionContext { let cat = self .catalog(cat_name.as_str()) .ok_or_else(|| internal_datafusion_err!("Catalog not found!"))?; - for schema_name in cat.schema_names() { + for schema_name in cat.schema_names()? { let schema = cat - .schema(schema_name.as_str()) + .schema(schema_name.as_str())? .ok_or_else(|| internal_datafusion_err!("Schema not found!"))?; let lister = schema.downcast_ref::(); if let Some(lister) = lister { @@ -1015,7 +1015,7 @@ impl SessionContext { } _ => return exec_err!("Unable to parse catalog from {schema_name}"), }; - let schema = catalog.schema(schema_name); + let schema = catalog.schema(schema_name)?; match (if_not_exists, schema) { (true, Some(_)) => self.return_empty_dataframe(), @@ -1097,13 +1097,13 @@ impl SessionContext { let DropTable { name, if_exists, .. } = cmd; - let result = self + let dropped = self .find_and_deregister(name.clone(), TableType::Base) - .await; - match (result, if_exists) { - (Ok(true), _) => self.return_empty_dataframe(), - (_, true) => self.return_empty_dataframe(), - (_, _) => exec_err!("Table '{name}' doesn't exist."), + .await?; + if dropped || if_exists { + self.return_empty_dataframe() + } else { + exec_err!("Table '{name}' doesn't exist.") } } @@ -1111,13 +1111,13 @@ impl SessionContext { let DropView { name, if_exists, .. } = cmd; - let result = self + let dropped = self .find_and_deregister(name.clone(), TableType::View) - .await; - match (result, if_exists) { - (Ok(true), _) => self.return_empty_dataframe(), - (_, true) => self.return_empty_dataframe(), - (_, _) => exec_err!("View '{name}' doesn't exist."), + .await?; + if dropped || if_exists { + self.return_empty_dataframe() + } else { + exec_err!("View '{name}' doesn't exist.") } } @@ -1523,10 +1523,10 @@ impl SessionContext { let maybe_schema = { let state = self.state.read(); let resolved = state.resolve_table_ref(table_ref.clone()); - state - .catalog_list() - .catalog(&resolved.catalog) - .and_then(|c| c.schema(&resolved.schema)) + match state.catalog_list().catalog(&resolved.catalog) { + Some(catalog) => catalog.schema(&resolved.schema)?, + None => None, + } }; if let Some(schema) = maybe_schema @@ -2043,11 +2043,10 @@ impl SessionContext { let table_ref: TableReference = table_ref.into(); let table = table_ref.table(); let table_ref = table_ref.clone(); - Ok(self - .state + self.state .read() .schema_for_ref(table_ref)? - .table_exist(table)) + .table_exist(table) } /// Retrieves a [`DataFrame`] representing a table previously diff --git a/datafusion/core/src/execution/session_state.rs b/datafusion/core/src/execution/session_state.rs index bbb62a295f2b0..0fce6e7115ea6 100644 --- a/datafusion/core/src/execution/session_state.rs +++ b/datafusion/core/src/execution/session_state.rs @@ -35,7 +35,7 @@ use datafusion_common::display::{PlanType, StringifiedPlan, ToStringifiedPlan}; use datafusion_common::tree_node::TreeNode; use datafusion_common::{ DFSchema, DataFusionError, ResolvedTableReference, TableReference, config_err, - exec_err, plan_datafusion_err, plan_err, + exec_err, plan_datafusion_err, }; use datafusion_execution::TaskContext; use datafusion_execution::config::SessionConfig; @@ -407,20 +407,44 @@ impl SessionState { /// Retrieve the [`SchemaProvider`] for a specific [`TableReference`], if it /// exists. + /// + /// Returns an error if the catalog or schema does not exist, or if the + /// catalog provider fails to look up the schema. pub fn schema_for_ref( &self, table_ref: impl Into, ) -> datafusion_common::Result> { let resolved_ref = self.resolve_table_ref(table_ref); - let catalog_name = resolved_ref.catalog.as_ref(); + let catalog = self.resolve_catalog(resolved_ref.catalog.as_ref())?; + self.schema_in_catalog(&catalog, &resolved_ref)? + .ok_or_else(|| { + plan_datafusion_err!("failed to resolve schema: {}", resolved_ref.schema) + }) + } + + /// Like [`Self::schema_for_ref`], but returns `Ok(None)` when the catalog + /// or schema does not exist. An `Err` means a provider failed to answer. + fn try_schema_for_ref( + &self, + resolved_ref: &ResolvedTableReference, + ) -> datafusion_common::Result>> { + match self.inner.catalog_list.catalog(&resolved_ref.catalog) { + Some(catalog) => self.schema_in_catalog(&catalog, resolved_ref), + None => Ok(None), + } + } + /// Look up `resolved_ref.schema` in `catalog`, handling the special + /// `information_schema` schema. + fn schema_in_catalog( + &self, + catalog: &Arc, + resolved_ref: &ResolvedTableReference, + ) -> datafusion_common::Result>> { // Special case handling for `information_schema`. if *resolved_ref.schema == *INFORMATION_SCHEMA && self.inner.config.information_schema() { - // Resolve catalog to ensure it exists - let _ = self.resolve_catalog(catalog_name)?; - // Create the global information schema let information_schema_provider = InformationSchemaProvider::new(Arc::clone(self.catalog_list())) @@ -435,20 +459,15 @@ impl SessionState { let information_schema_provider = if self.config().partition_information_schema() { information_schema_provider - .with_catalog_filter(Some(catalog_name.to_string())) + .with_catalog_filter(Some(resolved_ref.catalog.to_string())) } else { information_schema_provider }; - return Ok(Arc::new(information_schema_provider)); + return Ok(Some(Arc::new(information_schema_provider))); } - let catalog = self.resolve_catalog(catalog_name)?; - let Some(schema) = catalog.schema(&resolved_ref.schema) else { - return plan_err!("failed to resolve schema: {}", resolved_ref.schema); - }; - - Ok(schema) + catalog.schema(&resolved_ref.schema) } fn resolve_catalog( @@ -687,7 +706,7 @@ impl SessionState { let resolved = self.resolve_table_ref(reference); if let Entry::Vacant(v) = provider.tables.entry(resolved) { let resolved = v.key(); - if let Ok(schema) = self.schema_for_ref(resolved.clone()) + if let Some(schema) = self.try_schema_for_ref(resolved)? && let Some(table) = schema.table(&resolved.table).await? { v.insert(provider_as_source(table)); @@ -2872,20 +2891,24 @@ mod tests { let is_exist = session_state .catalog_list() .catalog(default_catalog.as_str()) - .unwrap() + .expect("default catalog should exist") .schema(default_schema.as_str()) - .unwrap() - .table_exist("employee"); + .expect("schema lookup should succeed") + .expect("default schema should exist") + .table_exist("employee") + .expect("table existence lookup should succeed"); assert!(is_exist); let new_state = SessionStateBuilder::new_from_existing(session_state).build(); assert!( new_state .catalog_list() .catalog(default_catalog.as_str()) - .unwrap() + .expect("default catalog should exist") .schema(default_schema.as_str()) - .unwrap() + .expect("schema lookup should succeed") + .expect("default schema should exist") .table_exist("employee") + .expect("table existence lookup should succeed") ); // if `with_create_default_catalog_and_schema` is disabled, the new one shouldn't create default catalog and schema diff --git a/datafusion/core/tests/catalog/failing_provider.rs b/datafusion/core/tests/catalog/failing_provider.rs new file mode 100644 index 0000000000000..5caf03e42896d --- /dev/null +++ b/datafusion/core/tests/catalog/failing_provider.rs @@ -0,0 +1,209 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership +// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements + +//! Tests that catalog and schema lookup failures are reported as errors, +//! and are not confused with a missing schema or table. + +use std::sync::Arc; + +use async_trait::async_trait; +use datafusion::catalog::{CatalogProvider, SchemaProvider, TableProvider}; +use datafusion::prelude::{SessionConfig, SessionContext}; +use datafusion_catalog::memory::{MemoryCatalogProvider, MemorySchemaProvider}; +use datafusion_common::{Result, exec_err}; + +const LOOKUP_FAILURE: &str = "remote catalog unavailable"; + +/// A catalog whose `broken` schema cannot be looked up. Other schemas are +/// served from an in-memory catalog. +#[derive(Debug, Default)] +struct FlakyCatalogProvider { + inner: MemoryCatalogProvider, +} + +impl CatalogProvider for FlakyCatalogProvider { + fn schema_names(&self) -> Result> { + self.inner.schema_names() + } + + fn schema(&self, name: &str) -> Result>> { + if name == "broken" { + return exec_err!("{LOOKUP_FAILURE}"); + } + self.inner.schema(name) + } + + fn register_schema( + &self, + name: &str, + schema: Arc, + ) -> Result>> { + self.inner.register_schema(name, schema) + } +} + +/// A schema that cannot list its tables or check if a table exists. +#[derive(Debug)] +struct UnlistableSchemaProvider; + +#[async_trait] +impl SchemaProvider for UnlistableSchemaProvider { + fn table_names(&self) -> Result> { + exec_err!("{LOOKUP_FAILURE}") + } + + async fn table(&self, _name: &str) -> Result>> { + Ok(None) + } + + fn table_exist(&self, _name: &str) -> Result { + exec_err!("{LOOKUP_FAILURE}") + } +} + +fn ctx_with_flaky_catalog() -> SessionContext { + let ctx = SessionContext::new(); + let catalog = FlakyCatalogProvider::default(); + catalog + .register_schema("public", Arc::new(MemorySchemaProvider::new())) + .unwrap(); + ctx.register_catalog("flaky", Arc::new(catalog)); + ctx +} + +async fn sql_error(ctx: &SessionContext, sql: &str) -> String { + match ctx.sql(sql).await { + Ok(df) => match df.collect().await { + Ok(_) => panic!("expected `{sql}` to fail"), + Err(e) => e.strip_backtrace(), + }, + Err(e) => e.strip_backtrace(), + } +} + +#[tokio::test] +async fn select_reports_schema_lookup_failure() { + let ctx = ctx_with_flaky_catalog(); + let err = sql_error(&ctx, "SELECT * FROM flaky.broken.t").await; + assert!(err.contains(LOOKUP_FAILURE), "unexpected error: {err}"); +} + +#[tokio::test] +async fn select_reports_missing_schema_and_table() { + let ctx = ctx_with_flaky_catalog(); + for sql in [ + "SELECT * FROM flaky.missing.t", + "SELECT * FROM flaky.public.missing", + "SELECT * FROM missing.public.t", + ] { + let err = sql_error(&ctx, sql).await; + assert!( + err.contains("not found"), + "unexpected error for `{sql}`: {err}" + ); + assert!(!err.contains(LOOKUP_FAILURE), "unexpected error: {err}"); + } +} + +#[tokio::test] +async fn drop_reports_schema_lookup_failure() { + let ctx = ctx_with_flaky_catalog(); + for sql in [ + "DROP TABLE flaky.broken.t", + "DROP TABLE IF EXISTS flaky.broken.t", + "DROP VIEW flaky.broken.v", + "DROP VIEW IF EXISTS flaky.broken.v", + ] { + let err = sql_error(&ctx, sql).await; + assert!( + err.contains(LOOKUP_FAILURE), + "unexpected error for `{sql}`: {err}" + ); + } +} + +#[tokio::test] +async fn drop_missing_table_and_view() -> Result<()> { + let ctx = ctx_with_flaky_catalog(); + + for (sql, expected) in [ + ( + "DROP TABLE flaky.missing.t", + "Table 'flaky.missing.t' doesn't exist.", + ), + ( + "DROP TABLE flaky.public.t", + "Table 'flaky.public.t' doesn't exist.", + ), + ( + "DROP VIEW flaky.missing.v", + "View 'flaky.missing.v' doesn't exist.", + ), + ( + "DROP VIEW flaky.public.v", + "View 'flaky.public.v' doesn't exist.", + ), + ] { + let err = sql_error(&ctx, sql).await; + assert!( + err.contains(expected), + "unexpected error for `{sql}`: {err}" + ); + } + + for sql in [ + "DROP TABLE IF EXISTS flaky.missing.t", + "DROP TABLE IF EXISTS flaky.public.t", + "DROP VIEW IF EXISTS flaky.missing.v", + "DROP VIEW IF EXISTS flaky.public.v", + ] { + ctx.sql(sql).await?.collect().await?; + } + Ok(()) +} + +#[tokio::test] +async fn information_schema_tables_reports_unlistable_schema() -> Result<()> { + let config = SessionConfig::new() + .with_information_schema(true) + .set_bool("datafusion.catalog.partition_information_schema", false); + let ctx = SessionContext::new_with_config(config); + ctx.sql("CREATE TABLE healthy AS VALUES (1)") + .await? + .collect() + .await?; + + let catalog = FlakyCatalogProvider::default(); + catalog.register_schema("unlistable", Arc::new(UnlistableSchemaProvider))?; + ctx.register_catalog("flaky", Arc::new(catalog)); + + let err = sql_error(&ctx, "SELECT * FROM information_schema.tables").await; + assert!(err.contains(LOOKUP_FAILURE), "unexpected error: {err}"); + Ok(()) +} + +#[test] +fn memory_catalog_drop_schema_that_cannot_list_tables() { + let catalog = MemoryCatalogProvider::new(); + catalog + .register_schema("unlistable", Arc::new(UnlistableSchemaProvider)) + .unwrap(); + + let err = catalog + .deregister_schema("unlistable", false) + .expect_err("non-cascading drop should need the table list"); + assert!( + err.to_string().contains(LOOKUP_FAILURE), + "unexpected error: {err}" + ); + assert!(catalog.schema("unlistable").unwrap().is_some()); + + assert!( + catalog + .deregister_schema("unlistable", true) + .unwrap() + .is_some() + ); + assert!(catalog.schema("unlistable").unwrap().is_none()); +} diff --git a/datafusion/core/tests/catalog/memory.rs b/datafusion/core/tests/catalog/memory.rs index b5f9fe2077e62..33ff66c263a88 100644 --- a/datafusion/core/tests/catalog/memory.rs +++ b/datafusion/core/tests/catalog/memory.rs @@ -69,11 +69,14 @@ fn default_register_schema_not_supported() { #[derive(Debug)] struct TestProvider {} impl CatalogProvider for TestProvider { - fn schema_names(&self) -> Vec { + fn schema_names(&self) -> datafusion_common::Result> { unimplemented!() } - fn schema(&self, _name: &str) -> Option> { + fn schema( + &self, + _name: &str, + ) -> datafusion_common::Result>> { unimplemented!() } } @@ -94,7 +97,11 @@ fn default_register_schema_not_supported() { async fn test_mem_provider() { let provider = MemorySchemaProvider::new(); let table_name = "test_table_exist"; - assert!(!provider.table_exist(table_name)); + assert!( + !provider + .table_exist(table_name) + .expect("table existence lookup should succeed") + ); assert!(provider.deregister_table(table_name).unwrap().is_none()); let test_table = EmptyTable::new(Arc::new(Schema::empty())); // register table successfully @@ -104,7 +111,11 @@ async fn test_mem_provider() { .unwrap() .is_none() ); - assert!(provider.table_exist(table_name)); + assert!( + provider + .table_exist(table_name) + .expect("table existence lookup should succeed") + ); let other_table = EmptyTable::new(Arc::new(Schema::empty())); let result = provider.register_table(table_name.to_string(), Arc::new(other_table)); assert!(result.is_err(), "The table test_table_exist already exists"); diff --git a/datafusion/core/tests/catalog/mod.rs b/datafusion/core/tests/catalog/mod.rs index 604eaf41f3ae8..7e3e867b6c0f4 100644 --- a/datafusion/core/tests/catalog/mod.rs +++ b/datafusion/core/tests/catalog/mod.rs @@ -2,4 +2,5 @@ // SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership // SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements +mod failing_provider; mod memory; diff --git a/datafusion/core/tests/sql/create_drop.rs b/datafusion/core/tests/sql/create_drop.rs index 7a9ca2c9618ad..e8deba512ff78 100644 --- a/datafusion/core/tests/sql/create_drop.rs +++ b/datafusion/core/tests/sql/create_drop.rs @@ -40,11 +40,13 @@ async fn create_custom_table() -> Result<()> { .into(); let sql = "CREATE EXTERNAL TABLE dt STORED AS DELTATABLE LOCATION 's3://bucket/schema/table';"; - ctx.sql(sql).await.unwrap(); + ctx.sql(sql).await?; - let cat = ctx.catalog("datafusion").unwrap(); - let schema = cat.schema("public").unwrap(); - let exists = schema.table_exist("dt"); + let cat = ctx + .catalog("datafusion") + .expect("default catalog should exist"); + let schema = cat.schema("public")?.expect("default schema should exist"); + let exists = schema.table_exist("dt")?; assert!(exists, "Table should have been created!"); Ok(()) @@ -59,15 +61,21 @@ async fn create_external_table_with_ddl() -> Result<()> { .into(); let sql = "CREATE EXTERNAL TABLE dt (a_id integer, a_str string, a_bool boolean) STORED AS MOCKTABLE LOCATION 'mockprotocol://path/to/table';"; - ctx.sql(sql).await.unwrap(); + ctx.sql(sql).await?; - let cat = ctx.catalog("datafusion").unwrap(); - let schema = cat.schema("public").unwrap(); + let cat = ctx + .catalog("datafusion") + .expect("default catalog should exist"); + let schema = cat.schema("public")?.expect("default schema should exist"); - let exists = schema.table_exist("dt"); + let exists = schema.table_exist("dt")?; assert!(exists, "Table should have been created!"); - let table_schema = schema.table("dt").await.unwrap().unwrap().schema(); + let table_schema = schema + .table("dt") + .await? + .expect("created table should be retrievable") + .schema(); assert_eq!(3, table_schema.fields().len()); @@ -83,19 +91,21 @@ async fn create_drop_table() -> Result<()> { let ctx = SessionContext::new(); let sql = "CREATE TABLE dt (a_id integer, a_str string, a_bool boolean);"; - ctx.sql(sql).await.unwrap(); + ctx.sql(sql).await?; - let cat = ctx.catalog("datafusion").unwrap(); - let schema = cat.schema("public").unwrap(); + let cat = ctx + .catalog("datafusion") + .expect("default catalog should exist"); + let schema = cat.schema("public")?.expect("default schema should exist"); - let exists = schema.table_exist("dt"); + let exists = schema.table_exist("dt")?; assert!(exists, "Table should have been created!"); // Drop the table let sql = "DROP TABLE dt;"; - ctx.sql(sql).await.unwrap(); + ctx.sql(sql).await?; - let exists = schema.table_exist("dt"); + let exists = schema.table_exist("dt")?; assert!(!exists, "Table should have been dropped!"); Ok(()) diff --git a/datafusion/ffi/integration-tests/tests/cases/catalog.rs b/datafusion/ffi/integration-tests/tests/cases/catalog.rs index d024a7f4c0aaa..7a65fd9594a09 100644 --- a/datafusion/ffi/integration-tests/tests/cases/catalog.rs +++ b/datafusion/ffi/integration-tests/tests/cases/catalog.rs @@ -29,6 +29,29 @@ mod tests { Ok(()) } + /// Exercises the `Result`-returning catalog and schema lookups across the + /// cdylib boundary. + #[tokio::test] + async fn test_catalog_schema_lookups() -> datafusion_common::Result<()> { + let module = get_module()?; + let (_ctx, codec) = crate::utils::ctx_and_codec(); + + let ffi_catalog = (module.create_catalog)(codec); + let foreign_catalog: Arc = (&ffi_catalog).into(); + + assert_eq!(foreign_catalog.schema_names()?, vec!["apple".to_string()]); + assert!(foreign_catalog.schema("nope")?.is_none()); + + let schema = foreign_catalog + .schema("apple")? + .expect("fixture catalog should contain schema apple"); + assert_eq!(schema.table_names()?, vec!["purchases".to_string()]); + assert!(schema.table_exist("purchases")?); + assert!(!schema.table_exist("nope")?); + + Ok(()) + } + #[tokio::test] async fn test_catalog_list() -> datafusion_common::Result<()> { let module = get_module()?; diff --git a/datafusion/ffi/src/catalog_provider.rs b/datafusion/ffi/src/catalog_provider.rs index 655fabbf2ee55..cd811fb418fbb 100644 --- a/datafusion/ffi/src/catalog_provider.rs +++ b/datafusion/ffi/src/catalog_provider.rs @@ -24,12 +24,12 @@ use crate::{df_result, sresult_return}; #[repr(C)] #[derive(Debug)] pub struct FFI_CatalogProvider { - pub schema_names: unsafe extern "C" fn(provider: &Self) -> SVec, + pub schema_names: unsafe extern "C" fn(provider: &Self) -> FFI_Result>, pub schema: unsafe extern "C" fn( provider: &Self, name: SString, - ) -> FFI_Option, + ) -> FFI_Result>, pub register_schema: unsafe extern "C" fn( @@ -93,28 +93,30 @@ impl FFI_CatalogProvider { unsafe extern "C" fn schema_names_fn_wrapper( provider: &FFI_CatalogProvider, -) -> SVec { +) -> FFI_Result> { unsafe { - let names = provider.inner().schema_names(); - names.into_iter().map(|s| s.into()).collect() + let names = sresult_return!(provider.inner().schema_names()); + FFI_Result::Ok(names.into_iter().map(|s| s.into()).collect()) } } unsafe extern "C" fn schema_fn_wrapper( provider: &FFI_CatalogProvider, name: SString, -) -> FFI_Option { +) -> FFI_Result> { unsafe { - let maybe_schema = provider.inner().schema(name.as_str()); - maybe_schema - .map(|schema| { - FFI_SchemaProvider::new_with_ffi_codec( - schema, - provider.runtime(), - provider.logical_codec.clone(), - ) - }) - .into() + let maybe_schema = sresult_return!(provider.inner().schema(name.as_str())); + FFI_Result::Ok( + maybe_schema + .map(|schema| { + FFI_SchemaProvider::new_with_ffi_codec( + schema, + provider.runtime(), + provider.logical_codec.clone(), + ) + }) + .into(), + ) } } @@ -285,23 +287,23 @@ impl Clone for FFI_CatalogProvider { } impl CatalogProvider for ForeignCatalogProvider { - fn schema_names(&self) -> Vec { + fn schema_names(&self) -> Result> { unsafe { - (self.0.schema_names)(&self.0) + Ok(df_result!((self.0.schema_names)(&self.0))? .into_iter() .map(|s| s.into()) - .collect() + .collect()) } } - fn schema(&self, name: &str) -> Option> { + fn schema(&self, name: &str) -> Result>> { unsafe { let maybe_provider: Option = - (self.0.schema)(&self.0, name.into()).into(); + df_result!((self.0.schema)(&self.0, name.into()))?.into(); - maybe_provider.map(|provider| { + Ok(maybe_provider.map(|provider| { Arc::new(ForeignSchemaProvider(provider)) as Arc - }) + })) } } @@ -347,9 +349,37 @@ impl CatalogProvider for ForeignCatalogProvider { #[cfg(test)] mod tests { use datafusion::catalog::{MemoryCatalogProvider, MemorySchemaProvider}; + use datafusion_common::DataFusionError; use super::*; + #[derive(Debug)] + struct FailingCatalogProvider; + + impl CatalogProvider for FailingCatalogProvider { + fn schema_names(&self) -> Result> { + Err(DataFusionError::Internal( + "schema_names failure from provider".to_string(), + )) + } + + fn schema(&self, _name: &str) -> Result>> { + Err(DataFusionError::Internal( + "schema failure from provider".to_string(), + )) + } + } + + fn assert_ffi_error_contains(err: DataFusionError, expected: &str) { + let DataFusionError::Ffi(message) = err else { + panic!("expected FFI error, got {err:?}"); + }; + assert!( + message.contains(expected), + "expected error message to contain '{expected}', got '{message}'" + ); + } + #[test] fn test_round_trip_ffi_catalog_provider() { let prior_schema = Arc::new(MemorySchemaProvider::new()); @@ -370,7 +400,9 @@ mod tests { let foreign_catalog: Arc = (&ffi_catalog).into(); - let prior_schema_names = foreign_catalog.schema_names(); + let prior_schema_names = foreign_catalog + .schema_names() + .expect("schema names lookup should succeed"); assert_eq!(prior_schema_names.len(), 1); assert_eq!(prior_schema_names[0], "prior_schema"); @@ -379,31 +411,78 @@ mod tests { .register_schema("prior_schema", Arc::new(MemorySchemaProvider::new())) .expect("Unable to register schema"); assert!(returned_schema.is_some()); - assert_eq!(foreign_catalog.schema_names().len(), 1); + assert_eq!( + foreign_catalog + .schema_names() + .expect("schema names lookup should succeed") + .len(), + 1 + ); // Add a new schema name let returned_schema = foreign_catalog .register_schema("second_schema", Arc::new(MemorySchemaProvider::new())) .expect("Unable to register schema"); assert!(returned_schema.is_none()); - assert_eq!(foreign_catalog.schema_names().len(), 2); + assert_eq!( + foreign_catalog + .schema_names() + .expect("schema names lookup should succeed") + .len(), + 2 + ); // Remove a schema let returned_schema = foreign_catalog .deregister_schema("prior_schema", false) .expect("Unable to deregister schema"); assert!(returned_schema.is_some()); - assert_eq!(foreign_catalog.schema_names().len(), 1); + assert_eq!( + foreign_catalog + .schema_names() + .expect("schema names lookup should succeed") + .len(), + 1 + ); // Retrieve non-existent schema - let returned_schema = foreign_catalog.schema("prior_schema"); + let returned_schema = foreign_catalog + .schema("prior_schema") + .expect("schema lookup should succeed"); assert!(returned_schema.is_none()); // Retrieve valid schema - let returned_schema = foreign_catalog.schema("second_schema"); + let returned_schema = foreign_catalog + .schema("second_schema") + .expect("schema lookup should succeed"); assert!(returned_schema.is_some()); } + #[test] + fn test_ffi_catalog_provider_propagates_failures() { + let (_ctx, task_ctx_provider) = crate::util::tests::test_session_and_ctx(); + + let mut ffi_catalog = FFI_CatalogProvider::new( + Arc::new(FailingCatalogProvider), + None, + task_ctx_provider, + None, + ); + ffi_catalog.library_marker_id = crate::mock_foreign_marker_id; + + let foreign_catalog: Arc = (&ffi_catalog).into(); + + let schema_names_err = foreign_catalog + .schema_names() + .expect_err("schema_names failure should cross FFI boundary"); + assert_ffi_error_contains(schema_names_err, "schema_names failure from provider"); + + let schema_err = foreign_catalog + .schema("failing_schema") + .expect_err("schema failure should cross FFI boundary"); + assert_ffi_error_contains(schema_err, "schema failure from provider"); + } + #[test] fn test_ffi_catalog_provider_local_bypass() { let catalog = Arc::new(MemoryCatalogProvider::new()); diff --git a/datafusion/ffi/src/schema_provider.rs b/datafusion/ffi/src/schema_provider.rs index f32260dd4ab65..4df297dcc3ab7 100644 --- a/datafusion/ffi/src/schema_provider.rs +++ b/datafusion/ffi/src/schema_provider.rs @@ -28,7 +28,7 @@ use crate::{df_result, sresult_return}; pub struct FFI_SchemaProvider { pub owner_name: FFI_Option, - pub table_names: unsafe extern "C" fn(provider: &Self) -> SVec, + pub table_names: unsafe extern "C" fn(provider: &Self) -> FFI_Result>, pub table: unsafe extern "C" fn( provider: &Self, @@ -50,7 +50,8 @@ pub struct FFI_SchemaProvider { name: SString, ) -> FFI_Result>, - pub table_exist: unsafe extern "C" fn(provider: &Self, name: SString) -> bool, + pub table_exist: + unsafe extern "C" fn(provider: &Self, name: SString) -> FFI_Result, pub logical_codec: FFI_LogicalExtensionCodec, @@ -100,12 +101,12 @@ impl FFI_SchemaProvider { unsafe extern "C" fn table_names_fn_wrapper( provider: &FFI_SchemaProvider, -) -> SVec { +) -> FFI_Result> { unsafe { let provider = provider.inner(); - let table_names = provider.table_names(); - table_names.into_iter().map(|s| s.into()).collect() + let table_names = sresult_return!(provider.table_names()); + FFI_Result::Ok(table_names.into_iter().map(|s| s.into()).collect()) } } @@ -173,8 +174,10 @@ unsafe extern "C" fn deregister_table_fn_wrapper( unsafe extern "C" fn table_exist_fn_wrapper( provider: &FFI_SchemaProvider, name: SString, -) -> bool { - unsafe { provider.inner().table_exist(name.as_str()) } +) -> FFI_Result { + unsafe { + FFI_Result::Ok(sresult_return!(provider.inner().table_exist(name.as_str()))) + } } unsafe extern "C" fn release_fn_wrapper(provider: &mut FFI_SchemaProvider) { @@ -304,12 +307,12 @@ impl SchemaProvider for ForeignSchemaProvider { name.map(|s| s.as_str()) } - fn table_names(&self) -> Vec { + fn table_names(&self) -> Result> { unsafe { - (self.0.table_names)(&self.0) + Ok(df_result!((self.0.table_names)(&self.0))? .into_iter() .map(|s| s.into()) - .collect() + .collect()) } } @@ -362,8 +365,8 @@ impl SchemaProvider for ForeignSchemaProvider { } /// Returns true if table exist in the schema provider, false otherwise. - fn table_exist(&self, name: &str) -> bool { - unsafe { (self.0.table_exist)(&self.0, name.into()) } + fn table_exist(&self, name: &str) -> Result { + unsafe { df_result!((self.0.table_exist)(&self.0, name.into())) } } } @@ -379,6 +382,64 @@ mod tests { Arc::new(EmptyTable::new(Arc::new(Schema::empty()))) } + #[derive(Debug)] + struct FailingSchemaProvider; + + #[async_trait] + impl SchemaProvider for FailingSchemaProvider { + fn table_names(&self) -> Result> { + Err(DataFusionError::Internal( + "table_names failure from provider".to_string(), + )) + } + + async fn table(&self, _name: &str) -> Result>> { + Ok(None) + } + + fn table_exist(&self, _name: &str) -> Result { + Err(DataFusionError::Internal( + "table_exist failure from provider".to_string(), + )) + } + } + + fn assert_ffi_error_contains(err: DataFusionError, expected: &str) { + let DataFusionError::Ffi(message) = err else { + panic!("expected FFI error, got {err:?}"); + }; + assert!( + message.contains(expected), + "expected error message to contain '{expected}', got '{message}'" + ); + } + + #[test] + fn test_ffi_schema_provider_propagates_failures() { + let (_ctx, task_ctx_provider) = crate::util::tests::test_session_and_ctx(); + + let mut ffi_schema_provider = FFI_SchemaProvider::new( + Arc::new(FailingSchemaProvider), + None, + task_ctx_provider, + None, + ); + ffi_schema_provider.library_marker_id = crate::mock_foreign_marker_id; + + let foreign_schema_provider: Arc = + (&ffi_schema_provider).into(); + + let table_names_err = foreign_schema_provider + .table_names() + .expect_err("table_names failure should cross FFI boundary"); + assert_ffi_error_contains(table_names_err, "table_names failure from provider"); + + let table_exist_err = foreign_schema_provider + .table_exist("failing_table") + .expect_err("table_exist failure should cross FFI boundary"); + assert_ffi_error_contains(table_exist_err, "table_exist failure from provider"); + } + #[tokio::test] async fn test_round_trip_ffi_schema_provider() { let schema_provider = Arc::new(MemorySchemaProvider::new()); @@ -399,7 +460,9 @@ mod tests { let foreign_schema_provider: Arc = (&ffi_schema_provider).into(); - let prior_table_names = foreign_schema_provider.table_names(); + let prior_table_names = foreign_schema_provider + .table_names() + .expect("table names lookup should succeed"); assert_eq!(prior_table_names.len(), 1); assert_eq!(prior_table_names[0], "prior_table"); @@ -407,21 +470,39 @@ mod tests { let returned_schema = foreign_schema_provider .register_table("prior_table".to_string(), empty_table()); assert!(returned_schema.is_err()); - assert_eq!(foreign_schema_provider.table_names().len(), 1); + assert_eq!( + foreign_schema_provider + .table_names() + .expect("table names lookup should succeed") + .len(), + 1 + ); // Add a new table let returned_schema = foreign_schema_provider .register_table("second_table".to_string(), empty_table()) .expect("Unable to register table"); assert!(returned_schema.is_none()); - assert_eq!(foreign_schema_provider.table_names().len(), 2); + assert_eq!( + foreign_schema_provider + .table_names() + .expect("table names lookup should succeed") + .len(), + 2 + ); // Remove a table let returned_schema = foreign_schema_provider .deregister_table("prior_table") .expect("Unable to deregister table"); assert!(returned_schema.is_some()); - assert_eq!(foreign_schema_provider.table_names().len(), 1); + assert_eq!( + foreign_schema_provider + .table_names() + .expect("table names lookup should succeed") + .len(), + 1 + ); // Retrieve non-existent table let returned_schema = foreign_schema_provider @@ -429,7 +510,11 @@ mod tests { .await .expect("Unable to query table"); assert!(returned_schema.is_none()); - assert!(!foreign_schema_provider.table_exist("prior_table")); + assert!( + !foreign_schema_provider + .table_exist("prior_table") + .expect("table existence lookup should succeed") + ); // Retrieve valid table let returned_schema = foreign_schema_provider @@ -437,7 +522,11 @@ mod tests { .await .expect("Unable to query table"); assert!(returned_schema.is_some()); - assert!(foreign_schema_provider.table_exist("second_table")); + assert!( + foreign_schema_provider + .table_exist("second_table") + .expect("table existence lookup should succeed") + ); } #[test] diff --git a/datafusion/ffi/src/tests/async_provider.rs b/datafusion/ffi/src/tests/async_provider.rs index 6a2db2223963d..3cf642b875f48 100644 --- a/datafusion/ffi/src/tests/async_provider.rs +++ b/datafusion/ffi/src/tests/async_provider.rs @@ -133,7 +133,7 @@ impl TableProvider for AsyncTableProvider { let catalog = state.catalog_list().catalog("datafusion").ok_or_else(|| { datafusion_common::exec_datafusion_err!("missing datafusion catalog") })?; - let schema = catalog.schema("public").ok_or_else(|| { + let schema = catalog.schema("public")?.ok_or_else(|| { datafusion_common::exec_datafusion_err!("missing public schema") })?; if schema.table("external_table").await?.is_none() { diff --git a/datafusion/ffi/src/tests/catalog.rs b/datafusion/ffi/src/tests/catalog.rs index e9286ded2e9d9..a27aaa3acf20a 100644 --- a/datafusion/ffi/src/tests/catalog.rs +++ b/datafusion/ffi/src/tests/catalog.rs @@ -75,7 +75,7 @@ impl Default for FixedSchemaProvider { #[async_trait] impl SchemaProvider for FixedSchemaProvider { - fn table_names(&self) -> Vec { + fn table_names(&self) -> Result> { self.inner.table_names() } @@ -83,7 +83,7 @@ impl SchemaProvider for FixedSchemaProvider { self.inner.table(name).await } - fn table_exist(&self, name: &str) -> bool { + fn table_exist(&self, name: &str) -> Result { self.inner.table_exist(name) } @@ -124,11 +124,11 @@ impl Default for FixedCatalogProvider { } impl CatalogProvider for FixedCatalogProvider { - fn schema_names(&self) -> Vec { + fn schema_names(&self) -> Result> { self.inner.schema_names() } - fn schema(&self, name: &str) -> Option> { + fn schema(&self, name: &str) -> Result>> { self.inner.schema(name) } diff --git a/datafusion/session/src/catalog.rs b/datafusion/session/src/catalog.rs index 3075a85cd347a..c8fdd36a62b16 100644 --- a/datafusion/session/src/catalog.rs +++ b/datafusion/session/src/catalog.rs @@ -130,10 +130,19 @@ impl CatalogProviderList for EmptyCatalogProviderList { /// [`TableProvider`]: crate::TableProvider pub trait CatalogProvider: Any + Debug + Sync + Send { /// Retrieves the list of available schema names in this catalog. - fn schema_names(&self) -> Vec; + /// + /// `Ok(vec![])` means the catalog has no schemas. Return `Err` if the + /// provider could not list its schemas (for example, a remote catalog that + /// timed out), so callers do not mistake a failure for an empty catalog. + fn schema_names(&self) -> Result>; /// Retrieves a specific schema from the catalog by name, provided it exists. - fn schema(&self, name: &str) -> Option>; + /// + /// `Ok(None)` means the provider confirmed that the schema does not exist. + /// Return `Err` if the provider could not answer (for example, a remote + /// catalog that timed out), so callers do not mistake a failure for a + /// missing schema. + fn schema(&self, name: &str) -> Result>>; /// Adds a new schema to this catalog. /// diff --git a/datafusion/session/src/schema.rs b/datafusion/session/src/schema.rs index da6989c0b9356..0811c8b3e45ef 100644 --- a/datafusion/session/src/schema.rs +++ b/datafusion/session/src/schema.rs @@ -29,7 +29,11 @@ pub trait SchemaProvider: Any + Debug + Sync + Send { } /// Retrieves the list of available table names in this schema. - fn table_names(&self) -> Vec; + /// + /// `Ok(vec![])` means the schema has no tables. Return `Err` if the + /// provider could not list its tables (for example, a remote catalog that + /// timed out), so callers do not mistake a failure for an empty schema. + fn table_names(&self) -> Result>; /// Retrieves a specific table from the schema by name, if it exists, /// otherwise returns `None`. @@ -69,8 +73,13 @@ pub trait SchemaProvider: Any + Debug + Sync + Send { exec_err!("schema provider does not support deregistering tables") } - /// Returns true if table exist in the schema provider, false otherwise. - fn table_exist(&self, name: &str) -> bool; + /// Returns `Ok(true)` if the table exists in the schema provider. + /// + /// `Ok(false)` means the provider confirmed that the table does not exist. + /// Return `Err` if the provider could not answer (for example, a remote + /// catalog that timed out), so callers do not mistake a failure for a + /// missing table. + fn table_exist(&self, name: &str) -> Result; } impl dyn SchemaProvider { diff --git a/datafusion/sqllogictest/src/test_context.rs b/datafusion/sqllogictest/src/test_context.rs index 9fe8d77494585..4c2343c3f1262 100644 --- a/datafusion/sqllogictest/src/test_context.rs +++ b/datafusion/sqllogictest/src/test_context.rs @@ -309,8 +309,8 @@ struct StrictOrdersSchema { #[async_trait] impl SchemaProvider for StrictOrdersSchema { - fn table_names(&self) -> Vec { - vec!["orders".to_string()] + fn table_names(&self) -> Result> { + Ok(vec!["orders".to_string()]) } async fn table( @@ -326,8 +326,8 @@ impl SchemaProvider for StrictOrdersSchema { } } - fn table_exist(&self, name: &str) -> bool { - name == "orders" + fn table_exist(&self, name: &str) -> Result { + Ok(name == "orders") } } diff --git a/docs/source/library-user-guide/catalogs.md b/docs/source/library-user-guide/catalogs.md index 930d1e202bdaa..435a72bce44ec 100644 --- a/docs/source/library-user-guide/catalogs.md +++ b/docs/source/library-user-guide/catalogs.md @@ -61,11 +61,12 @@ use datafusion::common::{Result, exec_err}; #[async_trait] impl SchemaProvider for MemorySchemaProvider { - fn table_names(&self) -> Vec { - self.tables + fn table_names(&self) -> Result> { + Ok(self + .tables .iter() .map(|table| table.key().clone()) - .collect() + .collect()) } async fn table(&self, name: &str) -> Result>> { @@ -77,7 +78,7 @@ impl SchemaProvider for MemorySchemaProvider { name: String, table: Arc, ) -> Result>> { - if self.table_exist(name.as_str()) { + if self.table_exist(name.as_str())? { return exec_err!( "The table {name} already exists" ); @@ -89,8 +90,8 @@ impl SchemaProvider for MemorySchemaProvider { Ok(self.tables.remove(name).map(|(_, table)| table)) } - fn table_exist(&self, name: &str) -> bool { - self.tables.contains_key(name) + fn table_exist(&self, name: &str) -> Result { + Ok(self.tables.contains_key(name)) } } ``` @@ -114,11 +115,12 @@ Without getting into a `CatalogProvider` implementation, we can create a `Memory # # #[async_trait] # impl SchemaProvider for MemorySchemaProvider { -# fn table_names(&self) -> Vec { -# self.tables +# fn table_names(&self) -> Result> { +# Ok(self +# .tables # .iter() # .map(|table| table.key().clone()) -# .collect() +# .collect()) # } # # async fn table(&self, name: &str) -> Result>> { @@ -130,7 +132,7 @@ Without getting into a `CatalogProvider` implementation, we can create a `Memory # name: String, # table: Arc, # ) -> Result>> { -# if self.table_exist(name.as_str()) { +# if self.table_exist(name.as_str())? { # return exec_err!( # "The table {name} already exists" # ); @@ -142,8 +144,8 @@ Without getting into a `CatalogProvider` implementation, we can create a `Memory # Ok(self.tables.remove(name).map(|(_, table)| table)) # } # -# fn table_exist(&self, name: &str) -> bool { -# self.tables.contains_key(name) +# fn table_exist(&self, name: &str) -> Result { +# Ok(self.tables.contains_key(name)) # } # } @@ -198,8 +200,8 @@ impl SchemaProvider for Schema { # todo!(); } -# fn table_names(&self) -> Vec { todo!() } -# fn table_exist(&self, _: &str) -> bool { todo!() } +# fn table_names(&self) -> Result> { todo!() } +# fn table_exist(&self, _: &str) -> Result { todo!() } } ``` @@ -220,12 +222,12 @@ pub struct MemoryCatalogProvider { } impl CatalogProvider for MemoryCatalogProvider { - fn schema_names(&self) -> Vec { - self.schemas.iter().map(|s| s.key().clone()).collect() + fn schema_names(&self) -> Result> { + Ok(self.schemas.iter().map(|s| s.key().clone()).collect()) } - fn schema(&self, name: &str) -> Option> { - self.schemas.get(name).map(|s| s.value().clone()) + fn schema(&self, name: &str) -> Result>> { + Ok(self.schemas.get(name).map(|s| s.value().clone())) } fn register_schema( @@ -243,7 +245,7 @@ impl CatalogProvider for MemoryCatalogProvider { ) -> Result>> { /// `cascade` is not used here, but can be used to control whether /// to delete all tables in the schema or not. - if let Some(schema) = self.schema(name) { + if let Some(schema) = self.schema(name)? { let (_, removed) = self.schemas.remove(name).unwrap(); Ok(Some(removed)) } else { diff --git a/docs/source/library-user-guide/upgrading/index.md b/docs/source/library-user-guide/upgrading/index.md index 686d68bb58c2c..eb4fb7988cab4 100644 --- a/docs/source/library-user-guide/upgrading/index.md +++ b/docs/source/library-user-guide/upgrading/index.md @@ -394,6 +394,51 @@ Row values are unchanged, but schema inspection can differ: code that compares the resulting schema against a hand-written one with `nullable: true` for every field needs to be updated. +### `CatalogProvider` and `SchemaProvider` lookup methods now return `Result` + +The following methods could not report errors, so implementations backed by a +remote catalog had to return an empty list, `None`, or `false` when a request +failed. That was indistinguishable from "no schemas", "schema not found", or +"table not found". They now return `Result`: + +| Trait | Method | 56.0.0 | 57.0.0 | +| ----------------- | ---------------- | --------------------------------- | ----------------------------------------- | +| `CatalogProvider` | `schema_names()` | `Vec` | `Result>` | +| `CatalogProvider` | `schema()` | `Option>` | `Result>>` | +| `SchemaProvider` | `table_names()` | `Vec` | `Result>` | +| `SchemaProvider` | `table_exist()` | `bool` | `Result` | + +Implementations that cannot fail can wrap their existing return value in `Ok`: + +```rust +// 56.0.0 +fn table_exist(&self, name: &str) -> bool { + self.tables.contains_key(name) +} + +// 57.0.0 +fn table_exist(&self, name: &str) -> Result { + Ok(self.tables.contains_key(name)) +} +``` + +Callers need to handle the error, typically with `?`: + +```rust +// 56.0.0 +if let Some(schema) = catalog.schema("public") { + for table in schema.table_names() { /* ... */ } +} + +// 57.0.0 +if let Some(schema) = catalog.schema("public")? { + for table in schema.table_names()? { /* ... */ } +} +``` + +The FFI wrappers (`FFI_CatalogProvider` and `FFI_SchemaProvider`) carry these +errors across the FFI boundary instead of dropping them. + ## Past Upgrade Guides The upgrade guides for released versions can be found here: