Skip to main content

common_meta/cache/table/
table_schema.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Cache for table id to schema name mapping.
16
17use std::sync::Arc;
18
19use moka::future::Cache;
20use snafu::OptionExt;
21use store_api::storage::TableId;
22
23use crate::cache::{CacheContainer, Initializer};
24use crate::error;
25use crate::instruction::CacheIdent;
26use crate::key::schema_name::SchemaName;
27use crate::key::table_info::TableInfoManager;
28use crate::kv_backend::KvBackendRef;
29
30pub type TableSchemaCache = CacheContainer<TableId, Arc<SchemaName>, CacheIdent>;
31pub type TableSchemaCacheRef = Arc<TableSchemaCache>;
32
33/// Constructs a [TableSchemaCache].
34pub fn new_table_schema_cache(
35    name: String,
36    cache: Cache<(usize, TableId), Arc<SchemaName>>,
37    kv_backend: KvBackendRef,
38) -> TableSchemaCache {
39    let table_info_manager = TableInfoManager::new(kv_backend);
40    let init = init_factory(table_info_manager);
41
42    // The table-to-schema mapping is retained across targeted invalidations.
43    CacheContainer::new(name, cache, init, |_| None)
44}
45
46fn init_factory(table_info_manager: TableInfoManager) -> Initializer<TableId, Arc<SchemaName>> {
47    Arc::new(move |table_id| {
48        let table_info_manager = table_info_manager.clone();
49        Box::pin(async move {
50            let raw_table_info = table_info_manager
51                .get(*table_id)
52                .await?
53                .context(error::ValueNotExistSnafu)?
54                .into_inner()
55                .table_info;
56
57            Ok(Some(Arc::new(SchemaName {
58                catalog_name: raw_table_info.catalog_name,
59                schema_name: raw_table_info.schema_name,
60            })))
61        })
62    })
63}