Skip to main content

catalog/system_schema/
utils.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
15pub mod tables;
16
17use std::sync::{Arc, Weak};
18
19#[cfg(feature = "enterprise")]
20use common_meta::key::TableMetadataManagerRef;
21use common_query::logical_plan::is_lossless_substrait_type;
22use datafusion::common::DFSchema;
23use datafusion::common::tree_node::{TreeNode, TreeNodeRecursion};
24use datafusion::logical_expr::ExprSchemable;
25use datafusion::physical_plan::ExecutionPlan;
26use datatypes::schema::SchemaRef;
27use snafu::{OptionExt, ResultExt};
28use store_api::storage::ScanRequest;
29
30use crate::CatalogManager;
31use crate::error::{
32    GetInformationExtensionSnafu, ProjectSchemaSnafu, Result, UpgradeWeakCatalogManagerRefSnafu,
33};
34use crate::information_schema::{
35    DatanodeInspectKind, DatanodeInspectRequest, InformationExtensionRef,
36};
37use crate::kvbackend::KvBackendCatalogManager;
38use crate::system_schema::semantic_graph::EntityGraphProviderRef;
39
40/// Adapts incremental system-table output, including one schema-bearing batch for an empty scan.
41pub(crate) fn record_batch_stream(
42    schema: &SchemaRef,
43    batches: impl futures::Stream<Item = Result<common_recordbatch::RecordBatch>> + Send + 'static,
44) -> common_recordbatch::DfSendableRecordBatchStream {
45    use futures::TryStreamExt;
46
47    let schema = schema.clone();
48    let arrow_schema = schema.arrow_schema().clone();
49    let stream = async_stream::try_stream!({
50        let mut batches = std::pin::pin!(batches);
51        let mut emitted = false;
52        while let Some(batch) = batches.try_next().await? {
53            if batch.num_rows() > 0 {
54                emitted = true;
55                yield batch.into_df_record_batch();
56            }
57        }
58        if !emitted {
59            yield common_recordbatch::RecordBatch::new_empty(schema).into_df_record_batch();
60        }
61    });
62    Box::pin(datafusion::physical_plan::stream::RecordBatchStreamAdapter::new(arrow_schema, stream))
63}
64
65/// Projects an inspection table schema according to the scan request.
66pub(crate) fn projected_schema(schema: &SchemaRef, request: &ScanRequest) -> Result<SchemaRef> {
67    if let Some(p) = request.projection.as_deref() {
68        Ok(Arc::new(schema.try_project(p).context(ProjectSchemaSnafu)?))
69    } else {
70        Ok(schema.clone())
71    }
72}
73
74/// Builds a datanode inspection plan with the requested output schema.
75pub(crate) fn inspect_plan(
76    catalog_manager: &Weak<dyn CatalogManager>,
77    kind: DatanodeInspectKind,
78    schema: &SchemaRef,
79    request: ScanRequest,
80) -> Result<Option<Arc<dyn ExecutionPlan>>> {
81    let projected_schema = projected_schema(schema, &request)?;
82    let info_ext = information_extension(catalog_manager)?;
83    let req = inspect_request(kind, schema, request)?;
84
85    info_ext.inspect_datanode_plan(req, projected_schema)
86}
87
88/// System table predicates are inexact: the frontend keeps a residual filter. Dropping
89/// an unsafe remote filter preserves correctness only if no remote limit truncates it.
90pub(crate) fn inspect_request(
91    kind: DatanodeInspectKind,
92    schema: &SchemaRef,
93    mut scan: ScanRequest,
94) -> Result<DatanodeInspectRequest> {
95    let schema =
96        DFSchema::try_from(schema.arrow_schema().clone()).context(crate::error::DatafusionSnafu)?;
97    let filter_count = scan.filters.len();
98    scan.filters.retain(|filter| {
99        let mut supported = true;
100        let visited = filter.apply(|expr| {
101            if !expr
102                .get_type(&schema)
103                .is_ok_and(|data_type| is_lossless_substrait_type(&data_type))
104            {
105                supported = false;
106                return Ok(TreeNodeRecursion::Stop);
107            }
108            Ok(TreeNodeRecursion::Continue)
109        });
110        visited.is_ok() && supported
111    });
112    if scan.filters.len() != filter_count {
113        scan.limit = None;
114    }
115    Ok(DatanodeInspectRequest { kind, scan })
116}
117
118/// Try to get the entity-graph provider from a `[CatalogManager]` weak reference.
119/// Returns `None` when the manager is not the kv-backed one or the provider has
120/// not been injected yet (the computed graph tables then stream empty).
121pub fn entity_graph_provider(
122    catalog_manager: &Weak<dyn CatalogManager>,
123) -> Result<Option<EntityGraphProviderRef>> {
124    let catalog_manager = catalog_manager
125        .upgrade()
126        .context(UpgradeWeakCatalogManagerRefSnafu)?;
127
128    Ok(catalog_manager
129        .as_any()
130        .downcast_ref::<KvBackendCatalogManager>()
131        .and_then(|manager| manager.entity_graph_provider()))
132}
133
134/// Try to get the `[InformationExtension]` from `[CatalogManager]` weak reference.
135pub fn information_extension(
136    catalog_manager: &Weak<dyn CatalogManager>,
137) -> Result<InformationExtensionRef> {
138    let catalog_manager = catalog_manager
139        .upgrade()
140        .context(UpgradeWeakCatalogManagerRefSnafu)?;
141
142    let information_extension = catalog_manager
143        .as_any()
144        .downcast_ref::<KvBackendCatalogManager>()
145        .map(|manager| manager.information_extension())
146        .context(GetInformationExtensionSnafu)?;
147
148    Ok(information_extension)
149}
150
151/// Try to get the `[TableMetadataManagerRef]` from `[CatalogManager]` weak reference.
152#[cfg(feature = "enterprise")]
153pub fn table_meta_manager(
154    catalog_manager: &Weak<dyn CatalogManager>,
155) -> Result<Option<TableMetadataManagerRef>> {
156    let catalog_manager = catalog_manager
157        .upgrade()
158        .context(UpgradeWeakCatalogManagerRefSnafu)?;
159
160    Ok(catalog_manager
161        .as_any()
162        .downcast_ref::<KvBackendCatalogManager>()
163        .map(|manager| manager.table_metadata_manager_ref().clone()))
164}