Skip to main content

datafusion_session/
catalog.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use std::any::Any;
6use std::fmt::Debug;
7use std::sync::Arc;
8
9pub use crate::schema::SchemaProvider;
10use crate::session::Session;
11use async_trait::async_trait;
12use datafusion_common::Result;
13use datafusion_common::not_impl_err;
14use datafusion_expr::CreateExternalCatalog;
15
16/// A catalog list that contains no catalogs.
17///
18/// [`Session`] implementations that do not provide catalog
19/// access can return this list explicitly.
20#[derive(Debug, Default)]
21pub struct EmptyCatalogProviderList;
22
23impl CatalogProviderList for EmptyCatalogProviderList {
24    fn register_catalog(
25        &self,
26        _name: String,
27        _catalog: Arc<dyn CatalogProvider>,
28    ) -> Option<Arc<dyn CatalogProvider>> {
29        None
30    }
31
32    fn catalog_names(&self) -> Vec<String> {
33        vec![]
34    }
35
36    fn catalog(&self, _name: &str) -> Option<Arc<dyn CatalogProvider>> {
37        None
38    }
39
40    fn deregister_catalog(
41        &self,
42        _name: &str,
43        _cascade: bool,
44    ) -> Result<Option<Arc<dyn CatalogProvider>>> {
45        Ok(None)
46    }
47}
48
49/// Represents a catalog, comprising a number of named schemas.
50///
51/// # Catalog Overview
52///
53/// To plan and execute queries, DataFusion needs a "Catalog" that provides
54/// metadata such as which schemas and tables exist, their columns and data
55/// types, and how to access the data.
56///
57/// The Catalog API consists:
58/// * [`CatalogProviderList`]: a collection of `CatalogProvider`s
59/// * [`CatalogProvider`]: a collection of `SchemaProvider`s (sometimes called a "database" in other systems)
60/// * [`SchemaProvider`]:  a collection of `TableProvider`s (often called a "schema" in other systems)
61/// * [`TableProvider`]:  individual tables
62///
63/// # Implementing Catalogs
64///
65/// To implement a catalog, you implement at least one of the [`CatalogProviderList`],
66/// [`CatalogProvider`] and [`SchemaProvider`] traits and register them
67/// appropriately in the `SessionContext`.
68///
69/// DataFusion comes with a simple in-memory catalog implementation,
70/// `MemoryCatalogProvider`, that is used by default and has no persistence.
71/// DataFusion does not include more complex Catalog implementations because
72/// catalog management is a key design choice for most data systems, and thus
73/// it is unlikely that any general-purpose catalog implementation will work
74/// well across many use cases.
75///
76/// # Implementing "Remote" catalogs
77///
78/// See [`remote_catalog`] for an end to end example of how to implement a
79/// remote catalog.
80///
81/// Sometimes catalog information is stored remotely and requires a network call
82/// to retrieve. For example, the [Delta Lake] table format stores table
83/// metadata in files on S3 that must be first downloaded to discover what
84/// schemas and tables exist.
85///
86/// [Delta Lake]: https://delta.io/
87/// [`remote_catalog`]: https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/data_io/remote_catalog.rs
88///
89/// The [`CatalogProvider`] can support this use case, but it takes some care.
90/// The planning APIs in DataFusion are not `async` and thus network IO can not
91/// be performed "lazily" / "on demand" during query planning. The rationale for
92/// this design is that using remote procedure calls for all catalog accesses
93/// required for query planning would likely result in multiple network calls
94/// per plan, resulting in very poor planning performance.
95///
96/// To implement [`CatalogProvider`] and [`SchemaProvider`] for remote catalogs,
97/// you need to provide an in memory snapshot of the required metadata. Most
98/// systems typically either already have this information cached locally or can
99/// batch access to the remote catalog to retrieve multiple schemas and tables
100/// in a single network call.
101///
102/// Note that [`SchemaProvider::table`] **is** an `async` function in order to
103/// simplify implementing simple [`SchemaProvider`]s. For many table formats it
104/// is easy to list all available tables but there is additional non trivial
105/// access required to read table details (e.g. statistics).
106///
107/// The pattern that DataFusion itself uses to plan SQL queries is to walk over
108/// the query to find all table references, performing required remote catalog
109/// lookups in parallel, storing the results in a cached snapshot, and then plans
110/// the query using that snapshot.
111///
112/// # Example Catalog Implementations
113///
114/// Here are some examples of how to implement custom catalogs:
115///
116/// * [`datafusion-cli`]: [`DynamicFileCatalogProvider`] catalog provider
117///   that treats files and directories on a filesystem as tables.
118///
119/// * The [`catalog.rs`]:  a simple directory based catalog.
120///
121/// * [delta-rs]:  [`UnityCatalogProvider`] implementation that can
122///   read from Delta Lake tables
123///
124/// [`datafusion-cli`]: https://datafusion.apache.org/user-guide/cli/index.html
125/// [`DynamicFileCatalogProvider`]: https://github.com/apache/datafusion/blob/31b9b48b08592b7d293f46e75707aad7dadd7cbc/datafusion-cli/src/catalog.rs#L75
126/// [`catalog.rs`]: https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/data_io/catalog.rs
127/// [delta-rs]: https://github.com/delta-io/delta-rs
128/// [`UnityCatalogProvider`]: https://github.com/delta-io/delta-rs/blob/951436ecec476ce65b5ed3b58b50fb0846ca7b91/crates/deltalake-core/src/data_catalog/unity/datafusion.rs#L111-L123
129///
130/// [`TableProvider`]: crate::TableProvider
131pub trait CatalogProvider: Any + Debug + Sync + Send {
132    /// Retrieves the list of available schema names in this catalog.
133    fn schema_names(&self) -> Vec<String>;
134
135    /// Retrieves a specific schema from the catalog by name, provided it exists.
136    fn schema(&self, name: &str) -> Option<Arc<dyn SchemaProvider>>;
137
138    /// Adds a new schema to this catalog.
139    ///
140    /// If a schema of the same name existed before, it is replaced in
141    /// the catalog and returned.
142    ///
143    /// By default returns a "Not Implemented" error
144    fn register_schema(
145        &self,
146        name: &str,
147        schema: Arc<dyn SchemaProvider>,
148    ) -> Result<Option<Arc<dyn SchemaProvider>>> {
149        // use variables to avoid unused variable warnings
150        let _ = name;
151        let _ = schema;
152        not_impl_err!("Registering new schemas is not supported")
153    }
154
155    /// Removes a schema from this catalog. Implementations of this method should return
156    /// errors if the schema exists but cannot be dropped. For example, in DataFusion's
157    /// default in-memory catalog, `MemoryCatalogProvider`, a non-empty schema
158    /// will only be successfully dropped when `cascade` is true.
159    /// This is equivalent to how DROP SCHEMA works in PostgreSQL.
160    ///
161    /// Implementations of this method should return None if schema with `name`
162    /// does not exist.
163    ///
164    /// By default returns a "Not Implemented" error
165    fn deregister_schema(
166        &self,
167        _name: &str,
168        _cascade: bool,
169    ) -> Result<Option<Arc<dyn SchemaProvider>>> {
170        not_impl_err!("Deregistering new schemas is not supported")
171    }
172
173    /// Called when a catalog is being dropped. Implementations can use this hook
174    /// to prevent a catalog from being dropped if it is not empty.
175    ///
176    /// By default returns a "Not Implemented" error
177    fn prepare_deregister_catalog(&self, _cascade: bool) -> Result<()> {
178        not_impl_err!("Deregistering all schemas is not supported")
179    }
180}
181
182impl dyn CatalogProvider {
183    /// Returns `true` if the catalog provider is of type `T`.
184    ///
185    /// Prefer this over `downcast_ref::<T>().is_some()`. Works correctly when
186    /// called on `Arc<dyn CatalogProvider>` via auto-deref.
187    pub fn is<T: CatalogProvider>(&self) -> bool {
188        (self as &dyn Any).is::<T>()
189    }
190
191    /// Attempts to downcast this catalog provider to a concrete type `T`,
192    /// returning `None` if the provider is not of that type.
193    ///
194    /// Works correctly when called on `Arc<dyn CatalogProvider>` via auto-deref,
195    /// unlike `(&arc as &dyn Any).downcast_ref::<T>()` which would attempt to
196    /// downcast the `Arc` itself.
197    pub fn downcast_ref<T: CatalogProvider>(&self) -> Option<&T> {
198        (self as &dyn Any).downcast_ref()
199    }
200}
201
202/// Represent a list of named [`CatalogProvider`]s.
203///
204/// Please see the documentation on [`CatalogProvider`] for details of
205/// implementing a custom catalog.
206pub trait CatalogProviderList: Any + Debug + Sync + Send {
207    /// Adds a new catalog to this catalog list
208    /// If a catalog of the same name existed before, it is replaced in the list and returned.
209    fn register_catalog(
210        &self,
211        name: String,
212        catalog: Arc<dyn CatalogProvider>,
213    ) -> Option<Arc<dyn CatalogProvider>>;
214
215    /// Removes a catalog from this list, returning it if it existed.
216    ///
217    /// Implementations of this method should return `Ok(None)` if no catalog
218    /// with `name` exists.
219    ///
220    /// If `cascade` is `false`, implementations should return an error if the
221    /// catalog is not empty.
222    ///
223    /// By default returns a "Not Implemented" error
224    fn deregister_catalog(
225        &self,
226        name: &str,
227        cascade: bool,
228    ) -> Result<Option<Arc<dyn CatalogProvider>>> {
229        let _ = (name, cascade);
230        not_impl_err!("Deregistering catalogs is not supported")
231    }
232
233    /// Retrieves the list of available catalog names
234    fn catalog_names(&self) -> Vec<String>;
235
236    /// Retrieves a specific catalog by name, provided it exists.
237    fn catalog(&self, name: &str) -> Option<Arc<dyn CatalogProvider>>;
238}
239
240impl dyn CatalogProviderList {
241    /// Returns `true` if the catalog provider list is of type `T`.
242    ///
243    /// Prefer this over `downcast_ref::<T>().is_some()`. Works correctly when
244    /// called on `Arc<dyn CatalogProviderList>` via auto-deref.
245    pub fn is<T: CatalogProviderList>(&self) -> bool {
246        (self as &dyn Any).is::<T>()
247    }
248
249    /// Attempts to downcast this catalog provider list to a concrete type `T`,
250    /// returning `None` if the provider list is not of that type.
251    ///
252    /// Works correctly when called on `Arc<dyn CatalogProviderList>` via
253    /// auto-deref, unlike `(&arc as &dyn Any).downcast_ref::<T>()` which would
254    /// attempt to downcast the `Arc` itself.
255    pub fn downcast_ref<T: CatalogProviderList>(&self) -> Option<&T> {
256        (self as &dyn Any).downcast_ref()
257    }
258}
259
260/// A factory which creates [`CatalogProvider`]s at runtime given a URL.
261#[async_trait]
262pub trait CatalogProviderFactory: Debug + Sync + Send {
263    /// Create a [`CatalogProvider`] using the given `cmd`
264    async fn create(
265        &self,
266        state: &dyn Session,
267        cmd: &CreateExternalCatalog,
268    ) -> Result<Arc<dyn CatalogProvider>>;
269}
270
271#[cfg(test)]
272mod tests {
273    use super::{CatalogProviderList, EmptyCatalogProviderList};
274
275    #[test]
276    fn empty_catalog_provider_list_has_no_catalogs() {
277        let catalogs = EmptyCatalogProviderList;
278        assert!(catalogs.catalog_names().is_empty());
279        assert!(catalogs.catalog("missing").is_none());
280    }
281}