Skip to main content

datafusion_cli/
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::sync::{Arc, Weak};
6
7use crate::object_storage::{AwsOptions, GcpOptions, get_object_store};
8
9use datafusion::catalog::{CatalogProvider, CatalogProviderList, SchemaProvider};
10
11use datafusion::common::plan_datafusion_err;
12use datafusion::datasource::TableProvider;
13use datafusion::datasource::listing::ListingTableUrl;
14use datafusion::error::Result;
15use datafusion::execution::context::SessionState;
16use datafusion::execution::session_state::SessionStateBuilder;
17
18use async_trait::async_trait;
19use dirs::home_dir;
20use parking_lot::RwLock;
21
22/// Wraps another catalog, automatically register require object stores for the file locations
23#[derive(Debug)]
24pub struct DynamicObjectStoreCatalog {
25    inner: Arc<dyn CatalogProviderList>,
26    state: Weak<RwLock<SessionState>>,
27}
28
29impl DynamicObjectStoreCatalog {
30    pub fn new(
31        inner: Arc<dyn CatalogProviderList>,
32        state: Weak<RwLock<SessionState>>,
33    ) -> Self {
34        Self { inner, state }
35    }
36}
37
38impl CatalogProviderList for DynamicObjectStoreCatalog {
39    fn register_catalog(
40        &self,
41        name: String,
42        catalog: Arc<dyn CatalogProvider>,
43    ) -> Option<Arc<dyn CatalogProvider>> {
44        self.inner.register_catalog(name, catalog)
45    }
46
47    fn deregister_catalog(
48        &self,
49        name: &str,
50        cascade: bool,
51    ) -> Result<Option<Arc<dyn CatalogProvider>>> {
52        self.inner.deregister_catalog(name, cascade)
53    }
54
55    fn catalog_names(&self) -> Vec<String> {
56        self.inner.catalog_names()
57    }
58
59    fn catalog(&self, name: &str) -> Option<Arc<dyn CatalogProvider>> {
60        let state = self.state.clone();
61        self.inner.catalog(name).map(|catalog| {
62            Arc::new(DynamicObjectStoreCatalogProvider::new(catalog, state)) as _
63        })
64    }
65}
66
67/// Wraps another catalog provider
68#[derive(Debug)]
69struct DynamicObjectStoreCatalogProvider {
70    inner: Arc<dyn CatalogProvider>,
71    state: Weak<RwLock<SessionState>>,
72}
73
74impl DynamicObjectStoreCatalogProvider {
75    pub fn new(
76        inner: Arc<dyn CatalogProvider>,
77        state: Weak<RwLock<SessionState>>,
78    ) -> Self {
79        Self { inner, state }
80    }
81}
82
83impl CatalogProvider for DynamicObjectStoreCatalogProvider {
84    fn schema_names(&self) -> Vec<String> {
85        self.inner.schema_names()
86    }
87
88    fn schema(&self, name: &str) -> Option<Arc<dyn SchemaProvider>> {
89        let state = self.state.clone();
90        self.inner.schema(name).map(|schema| {
91            Arc::new(DynamicObjectStoreSchemaProvider::new(schema, state)) as _
92        })
93    }
94
95    fn register_schema(
96        &self,
97        name: &str,
98        schema: Arc<dyn SchemaProvider>,
99    ) -> Result<Option<Arc<dyn SchemaProvider>>> {
100        self.inner.register_schema(name, schema)
101    }
102}
103
104/// Wraps another schema provider. [DynamicObjectStoreSchemaProvider] is responsible for registering the required
105/// object stores for the file locations.
106#[derive(Debug)]
107struct DynamicObjectStoreSchemaProvider {
108    inner: Arc<dyn SchemaProvider>,
109    state: Weak<RwLock<SessionState>>,
110}
111
112impl DynamicObjectStoreSchemaProvider {
113    pub fn new(
114        inner: Arc<dyn SchemaProvider>,
115        state: Weak<RwLock<SessionState>>,
116    ) -> Self {
117        Self { inner, state }
118    }
119}
120
121#[async_trait]
122impl SchemaProvider for DynamicObjectStoreSchemaProvider {
123    fn table_names(&self) -> Vec<String> {
124        self.inner.table_names()
125    }
126
127    fn register_table(
128        &self,
129        name: String,
130        table: Arc<dyn TableProvider>,
131    ) -> Result<Option<Arc<dyn TableProvider>>> {
132        self.inner.register_table(name, table)
133    }
134
135    async fn table(&self, name: &str) -> Result<Option<Arc<dyn TableProvider>>> {
136        let inner_table = self.inner.table(name).await;
137        if inner_table.is_ok()
138            && let Some(inner_table) = inner_table?
139        {
140            return Ok(Some(inner_table));
141        }
142
143        // if the inner schema provider didn't have a table by
144        // that name, try to treat it as a listing table
145        let mut state = self
146            .state
147            .upgrade()
148            .ok_or_else(|| plan_datafusion_err!("locking error"))?
149            .read()
150            .clone();
151        let mut builder = SessionStateBuilder::from(state.clone());
152        let optimized_name = substitute_tilde(name.to_owned());
153        let table_url = ListingTableUrl::parse(optimized_name.as_str())?;
154        let scheme = table_url.scheme();
155        let url = table_url.as_ref();
156
157        // If the store is already registered for this URL then `get_store`
158        // will return `Ok` which means we don't need to register it again. However,
159        // if `get_store` returns an `Err` then it means the corresponding store is
160        // not registered yet and we need to register it
161        match state.runtime_env().object_store_registry.get_store(url) {
162            Ok(_) => { /*Nothing to do here, store for this URL is already registered*/ }
163            Err(_) => {
164                // Register the store for this URL. Here we don't have access
165                // to any command options so the only choice is to use an empty collection
166                match scheme {
167                    "s3" | "oss" | "cos" => {
168                        if let Some(table_options) = builder.table_options() {
169                            table_options.extensions.insert(AwsOptions::default())
170                        }
171                    }
172                    "gs" | "gcs" => {
173                        if let Some(table_options) = builder.table_options() {
174                            table_options.extensions.insert(GcpOptions::default())
175                        }
176                    }
177                    _ => {}
178                }
179                state = builder.build();
180                let store = get_object_store(
181                    &state,
182                    table_url.scheme(),
183                    url,
184                    &state.default_table_options(),
185                    false,
186                )
187                .await?;
188                state.runtime_env().register_object_store(url, store);
189            }
190        }
191        self.inner.table(name).await
192    }
193
194    fn deregister_table(&self, name: &str) -> Result<Option<Arc<dyn TableProvider>>> {
195        self.inner.deregister_table(name)
196    }
197
198    fn table_exist(&self, name: &str) -> bool {
199        self.inner.table_exist(name)
200    }
201}
202
203pub fn substitute_tilde(cur: String) -> String {
204    if let Some(usr_dir_path) = home_dir()
205        && let Some(usr_dir) = usr_dir_path.to_str()
206        && cur.starts_with('~')
207        && !usr_dir.is_empty()
208    {
209        return cur.replacen('~', usr_dir, 1);
210    }
211    cur
212}
213#[cfg(test)]
214mod tests {
215    use std::{env, vec};
216
217    use super::*;
218
219    use datafusion::catalog::SchemaProvider;
220    use datafusion::prelude::SessionContext;
221
222    fn setup_context() -> (SessionContext, Arc<dyn SchemaProvider>) {
223        let ctx = SessionContext::new();
224        ctx.register_catalog_list(Arc::new(DynamicObjectStoreCatalog::new(
225            ctx.state().catalog_list().clone(),
226            ctx.state_weak_ref(),
227        )));
228
229        let provider = &DynamicObjectStoreCatalog::new(
230            ctx.state().catalog_list().clone(),
231            ctx.state_weak_ref(),
232        ) as &dyn CatalogProviderList;
233        let catalog = provider
234            .catalog(provider.catalog_names().first().unwrap())
235            .unwrap();
236        let schema = catalog
237            .schema(catalog.schema_names().first().unwrap())
238            .unwrap();
239        (ctx, schema)
240    }
241
242    #[tokio::test]
243    async fn query_http_location_test() -> Result<()> {
244        // This is a unit test so not expecting a connection or a file to be
245        // available
246        let domain = "example.com";
247        let location = format!("http://{domain}/file.parquet");
248
249        let (ctx, schema) = setup_context();
250
251        // That's a non registered table so expecting None here
252        let table = schema.table(&location).await?;
253        assert!(table.is_none());
254
255        // It should still create an object store for the location in the SessionState
256        let store = ctx
257            .runtime_env()
258            .object_store(ListingTableUrl::parse(location)?)?;
259
260        assert_eq!(format!("{store}"), "HttpStore");
261
262        // The store must be configured for this domain
263        let expected_domain = format!("Domain(\"{domain}\")");
264        assert!(format!("{store:?}").contains(&expected_domain));
265
266        Ok(())
267    }
268
269    #[tokio::test]
270    async fn query_s3_location_test() -> Result<()> {
271        let aws_envs = vec![
272            "AWS_ENDPOINT",
273            "AWS_ACCESS_KEY_ID",
274            "AWS_SECRET_ACCESS_KEY",
275            "AWS_ALLOW_HTTP",
276        ];
277        for aws_env in aws_envs {
278            if env::var(aws_env).is_err() {
279                eprint!("aws envs not set, skipping s3 test");
280                return Ok(());
281            }
282        }
283
284        let bucket = "examples3bucket";
285        let location = format!("s3://{bucket}/file.parquet");
286
287        let (ctx, schema) = setup_context();
288
289        let table = schema.table(&location).await?;
290        assert!(table.is_none());
291
292        let store = ctx
293            .runtime_env()
294            .object_store(ListingTableUrl::parse(location)?)?;
295        assert_eq!(format!("{store}"), format!("AmazonS3({bucket})"));
296
297        // The store must be configured for this domain
298        let expected_bucket = format!("bucket: \"{bucket}\"");
299        assert!(format!("{store:?}").contains(&expected_bucket));
300
301        Ok(())
302    }
303
304    #[tokio::test]
305    async fn query_gs_location_test() -> Result<()> {
306        let bucket = "examplegsbucket";
307        let location = format!("gs://{bucket}/file.parquet");
308
309        let (ctx, schema) = setup_context();
310
311        let table = schema.table(&location).await?;
312        assert!(table.is_none());
313
314        let store = ctx
315            .runtime_env()
316            .object_store(ListingTableUrl::parse(location)?)?;
317        assert_eq!(format!("{store}"), format!("GoogleCloudStorage({bucket})"));
318
319        // The store must be configured for this domain
320        let expected_bucket = format!("bucket_name_encoded: \"{bucket}\"");
321        assert!(format!("{store:?}").contains(&expected_bucket));
322
323        Ok(())
324    }
325
326    #[tokio::test]
327    async fn query_invalid_location_test() {
328        let location = "ts://file.parquet";
329        let (_ctx, schema) = setup_context();
330
331        assert!(schema.table(location).await.is_err());
332    }
333
334    #[cfg(not(target_os = "windows"))]
335    #[test]
336    fn test_substitute_tilde() {
337        use std::{env, path::PathBuf};
338        let original_home = home_dir();
339        let test_home_path = if cfg!(windows) {
340            "C:\\Users\\user"
341        } else {
342            "/home/user"
343        };
344        unsafe {
345            env::set_var(
346                if cfg!(windows) { "USERPROFILE" } else { "HOME" },
347                test_home_path,
348            );
349        }
350        let input = "~/Code/datafusion/benchmarks/data/tpch_sf1/part/part-0.parquet";
351        let expected = PathBuf::from(test_home_path)
352            .join("Code")
353            .join("datafusion")
354            .join("benchmarks")
355            .join("data")
356            .join("tpch_sf1")
357            .join("part")
358            .join("part-0.parquet")
359            .to_string_lossy()
360            .to_string();
361        let actual = substitute_tilde(input.to_string());
362        assert_eq!(actual, expected);
363        unsafe {
364            match original_home {
365                Some(home_path) => env::set_var(
366                    if cfg!(windows) { "USERPROFILE" } else { "HOME" },
367                    home_path.to_str().unwrap(),
368                ),
369                None => {
370                    env::remove_var(if cfg!(windows) { "USERPROFILE" } else { "HOME" })
371                }
372            }
373        }
374    }
375}