Skip to main content

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