Skip to main content

catalog/system_schema/information_schema/
loaders.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//! Metadata loaders used by information schema scans.
16
17use std::collections::{BTreeSet, HashMap};
18use std::sync::Arc;
19
20use common_catalog::consts::MITO_ENGINE;
21use common_error::ext::BoxedError;
22use common_meta::cache::{FlowInfoCache, ViewInfoCache, load_shared_flow_infos};
23use common_meta::key::FlowId;
24use common_meta::key::flow::flow_info::{FlowInfoManager, FlowInfoValue};
25use common_meta::key::table_route::PhysicalTableRouteValue;
26use common_meta::key::view_info::ViewInfoValue;
27use partition::manager::PartitionRuleManager;
28use snafu::{OptionExt, ResultExt};
29use store_api::storage::TableId;
30use table::TableRef;
31use table::metadata::TableInfoRef;
32
33use crate::CatalogManager;
34use crate::error::{
35    FindRegionRoutesSnafu, FlowInfoNotFoundSnafu, GetViewCacheSnafu, InternalSnafu, Result,
36};
37
38/// Reads one batch of named flows, preserving the order of the name scan.
39pub(crate) struct FlowInfoLoader<'a> {
40    cache: Option<&'a FlowInfoCache>,
41    manager: &'a FlowInfoManager,
42    catalog: &'a str,
43}
44
45impl<'a> FlowInfoLoader<'a> {
46    pub(crate) fn new(
47        cache: Option<&'a FlowInfoCache>,
48        manager: &'a FlowInfoManager,
49        catalog: &'a str,
50    ) -> Self {
51        Self {
52            cache,
53            manager,
54            catalog,
55        }
56    }
57
58    pub(crate) async fn load(
59        &self,
60        entries: Vec<(String, FlowId)>,
61    ) -> Result<Vec<(FlowId, Arc<FlowInfoValue>)>> {
62        let ids: Vec<_> = entries.iter().map(|(_, id)| *id).collect();
63        let values = if let Some(cache) = self.cache {
64            cache.get_many(&ids).await
65        } else {
66            load_shared_flow_infos(self.manager, &ids)
67                .await
68                .map(|values| ids.iter().map(|id| values.get(id).cloned()).collect())
69        }
70        .map_err(BoxedError::new)
71        .context(InternalSnafu)?;
72        entries
73            .into_iter()
74            .zip(values)
75            .map(|((name, id), value)| {
76                let info = value.context(FlowInfoNotFoundSnafu {
77                    catalog_name: self.catalog,
78                    flow_name: name,
79                })?;
80                Ok((id, info))
81            })
82            .collect::<Result<Vec<_>>>()
83    }
84}
85
86pub(crate) async fn load_source_table_names(
87    catalog_manager: &dyn CatalogManager,
88    flows: &[(FlowId, Arc<FlowInfoValue>)],
89) -> Result<HashMap<TableId, String>> {
90    let source_ids: BTreeSet<_> = flows
91        .iter()
92        .flat_map(|(_, info)| info.source_table_ids().iter().copied())
93        .collect();
94    let source_ids: Vec<_> = source_ids.into_iter().collect();
95    let mut names = HashMap::new();
96    for ids in source_ids.chunks(128) {
97        let infos = catalog_manager.table_infos_by_ids(ids).await?;
98        names.extend(
99            ids.iter()
100                .copied()
101                .zip(infos)
102                .filter_map(|(id, info)| Some((id, info?.full_table_name()))),
103        );
104    }
105    Ok(names)
106}
107
108pub(crate) async fn load_view_definitions(
109    cache: &ViewInfoCache,
110    tables: Vec<TableInfoRef>,
111) -> Result<impl Iterator<Item = (TableInfoRef, Option<Arc<ViewInfoValue>>)> + use<>> {
112    let ids = tables
113        .iter()
114        .map(|info| info.table_id())
115        .collect::<Vec<_>>();
116    let definitions = cache.get_many(&ids).await.context(GetViewCacheSnafu)?;
117    Ok(tables.into_iter().zip(definitions))
118}
119
120pub(crate) async fn load_table_routes(
121    manager: Option<&PartitionRuleManager>,
122    tables: &[TableRef],
123) -> Result<HashMap<TableId, Arc<PhysicalTableRouteValue>>> {
124    let Some(manager) = manager else {
125        return Ok(HashMap::new());
126    };
127    let ids = tables
128        .iter()
129        .map(|table| table.table_info())
130        .filter(|info| info.meta.engine == MITO_ENGINE || info.is_physical_table())
131        .map(|info| info.table_id())
132        .collect::<Vec<_>>();
133    manager
134        .batch_cached_physical_table_routes(&ids)
135        .await
136        .context(FindRegionRoutesSnafu)
137}