Skip to main content

datafusion_catalog/memory/
schema.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
18//! [`MemorySchemaProvider`]: In-memory implementations of [`SchemaProvider`].
19
20use crate::{SchemaProvider, TableProvider};
21use async_trait::async_trait;
22use dashmap::DashMap;
23use datafusion_common::{DataFusionError, exec_err};
24use std::sync::Arc;
25
26/// Simple in-memory implementation of a schema.
27#[derive(Debug)]
28pub struct MemorySchemaProvider {
29    tables: DashMap<String, Arc<dyn TableProvider>>,
30}
31
32impl MemorySchemaProvider {
33    /// Instantiates a new MemorySchemaProvider with an empty collection of tables.
34    pub fn new() -> Self {
35        Self {
36            tables: DashMap::new(),
37        }
38    }
39}
40
41impl Default for MemorySchemaProvider {
42    fn default() -> Self {
43        Self::new()
44    }
45}
46
47#[async_trait]
48impl SchemaProvider for MemorySchemaProvider {
49    fn table_names(&self) -> Vec<String> {
50        self.tables
51            .iter()
52            .map(|table| table.key().clone())
53            .collect()
54    }
55
56    async fn table(
57        &self,
58        name: &str,
59    ) -> datafusion_common::Result<Option<Arc<dyn TableProvider>>, DataFusionError> {
60        Ok(self.tables.get(name).map(|table| Arc::clone(table.value())))
61    }
62
63    fn register_table(
64        &self,
65        name: String,
66        table: Arc<dyn TableProvider>,
67    ) -> datafusion_common::Result<Option<Arc<dyn TableProvider>>> {
68        if self.table_exist(name.as_str()) {
69            return exec_err!("The table {name} already exists");
70        }
71        Ok(self.tables.insert(name, table))
72    }
73
74    fn deregister_table(
75        &self,
76        name: &str,
77    ) -> datafusion_common::Result<Option<Arc<dyn TableProvider>>> {
78        Ok(self.tables.remove(name).map(|(_, table)| table))
79    }
80
81    fn table_exist(&self, name: &str) -> bool {
82        self.tables.contains_key(name)
83    }
84}