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