Skip to main content

catalog/system_schema/
information_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
15mod cluster_info;
16pub mod columns;
17mod compaction_tasks;
18pub mod flow_statistics;
19pub mod flows;
20mod information_memory_table;
21pub mod key_column_usage;
22mod loaders;
23mod partitions;
24mod procedure_info;
25pub mod process_list;
26#[cfg(feature = "enterprise")]
27mod recycle_bin;
28mod region_info;
29pub mod region_peers;
30mod region_statistics;
31pub mod schemata;
32mod ssts;
33pub mod statistics;
34mod table_constraints;
35mod table_names;
36mod table_semantics;
37pub mod tables;
38mod views;
39
40#[cfg(all(test, feature = "enterprise"))]
41mod recycle_bin_test;
42
43use std::collections::{HashMap, HashSet};
44use std::sync::{Arc, Weak};
45
46use common_catalog::consts::{self, DEFAULT_CATALOG_NAME, INFORMATION_SCHEMA_NAME};
47use common_error::ext::ErrorExt;
48use common_meta::cluster::NodeInfo;
49use common_meta::datanode::RegionStat;
50use common_meta::key::flow::FlowMetadataManager;
51use common_meta::key::flow::flow_state::FlowStat;
52use common_meta::kv_backend::KvBackendRef;
53use common_procedure::ProcedureInfo;
54use common_recordbatch::SendableRecordBatchStream;
55use datafusion::error::DataFusionError;
56use datafusion::logical_expr::LogicalPlan;
57use datafusion::physical_plan::ExecutionPlan;
58use datatypes::schema::SchemaRef;
59use lazy_static::lazy_static;
60use paste::paste;
61use process_list::InformationSchemaProcessList;
62use region_info::InformationSchemaRegionInfo;
63use store_api::compaction_task::CompactionTaskEntry;
64use store_api::metric_engine_consts::{
65    MEMTABLE_PARTITION_TREE_PRIMARY_KEY_ENCODING, PRIMARY_KEY_ENCODING,
66};
67use store_api::region_info::RegionInfoEntry;
68use store_api::sst_entry::{ManifestSstEntry, PuffinIndexMetaEntry, StorageSstEntry};
69use store_api::storage::ScanRequest;
70use table::TableRef;
71use table::requests::{SEMANTIC_TABLE_SCOPE, TableOptions};
72pub use table_names::*;
73use views::InformationSchemaViews;
74
75use self::columns::InformationSchemaColumns;
76use crate::CatalogManager;
77use crate::error::Error;
78use crate::process_manager::ProcessManagerRef;
79use crate::system_schema::information_schema::cluster_info::InformationSchemaClusterInfo;
80use crate::system_schema::information_schema::compaction_tasks::InformationSchemaCompactionTasks;
81use crate::system_schema::information_schema::flow_statistics::InformationSchemaFlowStatistics;
82use crate::system_schema::information_schema::flows::InformationSchemaFlows;
83use crate::system_schema::information_schema::information_memory_table::get_schema_columns;
84use crate::system_schema::information_schema::key_column_usage::InformationSchemaKeyColumnUsage;
85use crate::system_schema::information_schema::partitions::InformationSchemaPartitions;
86#[cfg(feature = "enterprise")]
87use crate::system_schema::information_schema::recycle_bin::InformationSchemaRecycleBin;
88use crate::system_schema::information_schema::region_peers::InformationSchemaRegionPeers;
89use crate::system_schema::information_schema::schemata::InformationSchemaSchemata;
90use crate::system_schema::information_schema::ssts::{
91    InformationSchemaSstsIndexMeta, InformationSchemaSstsManifest, InformationSchemaSstsStorage,
92};
93use crate::system_schema::information_schema::statistics::InformationSchemaStatistics;
94use crate::system_schema::information_schema::table_constraints::InformationSchemaTableConstraints;
95use crate::system_schema::information_schema::table_semantics::InformationSchemaTableSemantics;
96use crate::system_schema::information_schema::tables::InformationSchemaTables;
97use crate::system_schema::memory_table::MemoryTable;
98pub(crate) use crate::system_schema::predicate::Predicates;
99use crate::system_schema::{SystemSchemaProvider, SystemTable, build_system_table};
100
101const DENSE_PRIMARY_KEY_ENCODING: &str = "dense";
102const SPARSE_PRIMARY_KEY_ENCODING: &str = "sparse";
103
104pub(crate) fn primary_key_encoding_index_type(options: &HashMap<String, String>) -> &'static str {
105    options
106        .get(PRIMARY_KEY_ENCODING)
107        .or_else(|| options.get(MEMTABLE_PARTITION_TREE_PRIMARY_KEY_ENCODING))
108        .map(|value| {
109            if value.eq_ignore_ascii_case(SPARSE_PRIMARY_KEY_ENCODING) {
110                SPARSE_PRIMARY_KEY_ENCODING
111            } else {
112                DENSE_PRIMARY_KEY_ENCODING
113            }
114        })
115        .unwrap_or(DENSE_PRIMARY_KEY_ENCODING)
116}
117
118lazy_static! {
119    // Memory tables in `information_schema`.
120    static ref MEMORY_TABLES: &'static [&'static str] = &[
121        ENGINES,
122        COLUMN_PRIVILEGES,
123        COLUMN_STATISTICS,
124        CHARACTER_SETS,
125        COLLATIONS,
126        COLLATION_CHARACTER_SET_APPLICABILITY,
127        CHECK_CONSTRAINTS,
128        EVENTS,
129        FILES,
130        OPTIMIZER_TRACE,
131        PARAMETERS,
132        PROFILING,
133        REFERENTIAL_CONSTRAINTS,
134        ROUTINES,
135        SCHEMA_PRIVILEGES,
136        TABLE_PRIVILEGES,
137        GLOBAL_STATUS,
138        SESSION_STATUS,
139        PLUGINS,
140        USER_PRIVILEGES,
141        PROCESSLIST,
142    ];
143}
144
145macro_rules! setup_memory_table {
146    ($name: expr, $scope: ident) => {
147        paste! {
148            {
149                let (schema, columns) = get_schema_columns($name);
150                Some(Arc::new(MemoryTable::new(
151                    consts::[<INFORMATION_SCHEMA_ $name  _TABLE_ID>],
152                    $name,
153                    schema,
154                    columns,
155                    InformationSchemaTableScope::$scope
156                )) as _)
157            }
158        }
159    };
160}
161
162pub struct MakeInformationTableRequest {
163    pub catalog_name: String,
164    pub catalog_manager: Weak<dyn CatalogManager>,
165    pub kv_backend: KvBackendRef,
166}
167
168/// The visibility guaranteed by an information-schema table provider.
169#[derive(Debug, Clone, Copy, PartialEq, Eq)]
170pub enum InformationSchemaTableScope {
171    /// Every query is filtered to the catalog supplied when constructing the provider.
172    Catalog,
173    /// Catalog-independent data that is safe for authenticated non-admin users to read.
174    PublicGlobal,
175    /// Shared data without a non-admin visibility guarantee, including compatibility stubs.
176    Global,
177}
178
179impl InformationSchemaTableScope {
180    pub const fn as_str(self) -> &'static str {
181        match self {
182            Self::Catalog => "catalog",
183            Self::PublicGlobal => "public_global",
184            Self::Global => "global",
185        }
186    }
187}
188
189/// A factory trait for making information schema tables.
190///
191/// This trait allows for extensibility of the information schema by providing
192/// a way to dynamically create custom information schema tables.
193pub trait InformationSchemaTableFactory {
194    /// Creates a table whose scope is declared by its [`InformationTable`] implementation.
195    fn make_information_table(&self, req: MakeInformationTableRequest) -> InformationTableRef;
196}
197
198pub type InformationSchemaTableFactoryRef = Arc<dyn InformationSchemaTableFactory + Send + Sync>;
199
200/// The `information_schema` tables info provider.
201pub struct InformationSchemaProvider {
202    catalog_name: String,
203    catalog_manager: Weak<dyn CatalogManager>,
204    process_manager: Option<ProcessManagerRef>,
205    flow_metadata_manager: Arc<FlowMetadataManager>,
206    tables: HashMap<String, TableRef>,
207    kv_backend: KvBackendRef,
208    extra_table_factories: HashMap<String, InformationSchemaTableFactoryRef>,
209}
210
211impl SystemSchemaProvider for InformationSchemaProvider {
212    fn tables(&self) -> &HashMap<String, TableRef> {
213        assert!(!self.tables.is_empty());
214
215        &self.tables
216    }
217}
218
219impl InformationSchemaProvider {
220    fn information_table(&self, name: &str) -> Option<InformationTableRef> {
221        if let Some(factory) = self.extra_table_factories.get(name) {
222            let req = MakeInformationTableRequest {
223                catalog_name: self.catalog_name.clone(),
224                catalog_manager: self.catalog_manager.clone(),
225                kv_backend: self.kv_backend.clone(),
226            };
227            return Some(factory.make_information_table(req));
228        }
229
230        match name.to_ascii_lowercase().as_str() {
231            TABLES => Some(Arc::new(InformationSchemaTables::new(
232                self.catalog_name.clone(),
233                self.catalog_manager.clone(),
234            )) as _),
235            COLUMNS => Some(Arc::new(InformationSchemaColumns::new(
236                self.catalog_name.clone(),
237                self.catalog_manager.clone(),
238            )) as _),
239            ENGINES => setup_memory_table!(ENGINES, PublicGlobal),
240            COLUMN_PRIVILEGES => setup_memory_table!(COLUMN_PRIVILEGES, Global),
241            COLUMN_STATISTICS => setup_memory_table!(COLUMN_STATISTICS, Global),
242            BUILD_INFO => setup_memory_table!(BUILD_INFO, PublicGlobal),
243            CHARACTER_SETS => setup_memory_table!(CHARACTER_SETS, PublicGlobal),
244            COLLATIONS => setup_memory_table!(COLLATIONS, PublicGlobal),
245            COLLATION_CHARACTER_SET_APPLICABILITY => {
246                setup_memory_table!(COLLATION_CHARACTER_SET_APPLICABILITY, PublicGlobal)
247            }
248            CHECK_CONSTRAINTS => setup_memory_table!(CHECK_CONSTRAINTS, Global),
249            EVENTS => setup_memory_table!(EVENTS, Global),
250            FILES => setup_memory_table!(FILES, Global),
251            OPTIMIZER_TRACE => setup_memory_table!(OPTIMIZER_TRACE, Global),
252            PARAMETERS => setup_memory_table!(PARAMETERS, Global),
253            PROFILING => setup_memory_table!(PROFILING, Global),
254            REFERENTIAL_CONSTRAINTS => setup_memory_table!(REFERENTIAL_CONSTRAINTS, Global),
255            ROUTINES => setup_memory_table!(ROUTINES, Global),
256            SCHEMA_PRIVILEGES => setup_memory_table!(SCHEMA_PRIVILEGES, Global),
257            TABLE_PRIVILEGES => setup_memory_table!(TABLE_PRIVILEGES, Global),
258            GLOBAL_STATUS => setup_memory_table!(GLOBAL_STATUS, Global),
259            SESSION_STATUS => setup_memory_table!(SESSION_STATUS, Global),
260            PLUGINS => setup_memory_table!(PLUGINS, Global),
261            USER_PRIVILEGES => setup_memory_table!(USER_PRIVILEGES, Global),
262            PROCESSLIST => setup_memory_table!(PROCESSLIST, Global),
263            KEY_COLUMN_USAGE => Some(Arc::new(InformationSchemaKeyColumnUsage::new(
264                self.catalog_name.clone(),
265                self.catalog_manager.clone(),
266            )) as _),
267            SCHEMATA => Some(Arc::new(InformationSchemaSchemata::new(
268                self.catalog_name.clone(),
269                self.catalog_manager.clone(),
270            )) as _),
271            PARTITIONS => Some(Arc::new(InformationSchemaPartitions::new(
272                self.catalog_name.clone(),
273                self.catalog_manager.clone(),
274            )) as _),
275            REGION_PEERS => Some(Arc::new(InformationSchemaRegionPeers::new(
276                self.catalog_name.clone(),
277                self.catalog_manager.clone(),
278            )) as _),
279            TABLE_CONSTRAINTS => Some(Arc::new(InformationSchemaTableConstraints::new(
280                self.catalog_name.clone(),
281                self.catalog_manager.clone(),
282            )) as _),
283            STATISTICS => Some(Arc::new(InformationSchemaStatistics::new(
284                self.catalog_name.clone(),
285                self.catalog_manager.clone(),
286            )) as _),
287            CLUSTER_INFO => Some(Arc::new(InformationSchemaClusterInfo::new(
288                self.catalog_manager.clone(),
289            )) as _),
290            VIEWS => Some(Arc::new(InformationSchemaViews::new(
291                self.catalog_name.clone(),
292                self.catalog_manager.clone(),
293            )) as _),
294            FLOWS => Some(Arc::new(InformationSchemaFlows::new(
295                self.catalog_name.clone(),
296                self.catalog_manager.clone(),
297                self.flow_metadata_manager.clone(),
298            )) as _),
299            FLOW_STATISTICS => Some(Arc::new(InformationSchemaFlowStatistics::new(
300                self.catalog_name.clone(),
301                self.catalog_manager.clone(),
302                self.flow_metadata_manager.clone(),
303            )) as _),
304            PROCEDURE_INFO => Some(
305                Arc::new(procedure_info::InformationSchemaProcedureInfo::new(
306                    self.catalog_manager.clone(),
307                )) as _,
308            ),
309            #[cfg(feature = "enterprise")]
310            RECYCLE_BIN => Some(Arc::new(InformationSchemaRecycleBin::new(
311                self.catalog_name.clone(),
312                self.catalog_manager.clone(),
313            )) as _),
314            REGION_STATISTICS => Some(Arc::new(
315                region_statistics::InformationSchemaRegionStatistics::new(
316                    self.catalog_manager.clone(),
317                ),
318            ) as _),
319            COMPACTION_TASKS => Some(Arc::new(InformationSchemaCompactionTasks::new(
320                self.catalog_manager.clone(),
321            )) as _),
322            REGION_INFO => Some(Arc::new(InformationSchemaRegionInfo::new(
323                self.catalog_manager.clone(),
324            )) as _),
325            PROCESS_LIST => self
326                .process_manager
327                .as_ref()
328                .map(|p| Arc::new(InformationSchemaProcessList::new(p.clone())) as _),
329            SSTS_MANIFEST => Some(Arc::new(InformationSchemaSstsManifest::new(
330                self.catalog_manager.clone(),
331            )) as _),
332            SSTS_STORAGE => Some(Arc::new(InformationSchemaSstsStorage::new(
333                self.catalog_manager.clone(),
334            )) as _),
335            SSTS_INDEX_META => Some(Arc::new(InformationSchemaSstsIndexMeta::new(
336                self.catalog_manager.clone(),
337            )) as _),
338            TABLE_SEMANTICS => Some(Arc::new(InformationSchemaTableSemantics::new(
339                self.catalog_name.clone(),
340                self.catalog_manager.clone(),
341            )) as _),
342            _ => None,
343        }
344    }
345}
346
347impl InformationSchemaProvider {
348    pub fn new(
349        catalog_name: String,
350        catalog_manager: Weak<dyn CatalogManager>,
351        flow_metadata_manager: Arc<FlowMetadataManager>,
352        process_manager: Option<ProcessManagerRef>,
353        kv_backend: KvBackendRef,
354    ) -> Self {
355        let mut provider = Self {
356            catalog_name,
357            catalog_manager,
358            flow_metadata_manager,
359            process_manager,
360            tables: HashMap::new(),
361            kv_backend,
362            extra_table_factories: HashMap::new(),
363        };
364
365        provider.build_tables();
366
367        provider
368    }
369
370    pub(crate) fn with_extra_table_factories(
371        mut self,
372        factories: HashMap<String, InformationSchemaTableFactoryRef>,
373    ) -> Self {
374        self.extra_table_factories = factories;
375        self.build_tables();
376        self
377    }
378
379    fn build_tables(&mut self) {
380        let mut table_names = HashSet::new();
381
382        // SECURITY NOTE:
383        // Carefully consider the tables that may expose sensitive cluster configurations,
384        // authentication details, and other critical information.
385        // Only put these tables under `greptime` catalog to prevent info leak.
386        if self.catalog_name == DEFAULT_CATALOG_NAME {
387            table_names.extend([
388                REGION_PEERS,
389                CLUSTER_INFO,
390                PROCEDURE_INFO,
391                REGION_STATISTICS,
392                COMPACTION_TASKS,
393                REGION_INFO,
394                SSTS_MANIFEST,
395                SSTS_STORAGE,
396                SSTS_INDEX_META,
397            ]);
398        }
399
400        table_names.extend([
401            BUILD_INFO,
402            TABLES,
403            VIEWS,
404            SCHEMATA,
405            COLUMNS,
406            KEY_COLUMN_USAGE,
407            TABLE_CONSTRAINTS,
408            STATISTICS,
409            FLOWS,
410            FLOW_STATISTICS,
411            #[cfg(feature = "enterprise")]
412            RECYCLE_BIN,
413            TABLE_SEMANTICS,
414            PARTITIONS,
415        ]);
416        if self.process_manager.is_some() {
417            table_names.insert(PROCESS_LIST);
418        }
419        table_names.extend(MEMORY_TABLES.iter().copied());
420        table_names.extend(self.extra_table_factories.keys().map(String::as_str));
421        self.tables = table_names
422            .into_iter()
423            .map(|name| {
424                let table = self.information_table(name).expect(name);
425                let options = TableOptions {
426                    extra_options: HashMap::from([(
427                        SEMANTIC_TABLE_SCOPE.to_string(),
428                        table.scope().as_str().to_string(),
429                    )]),
430                    ..Default::default()
431                };
432                let table = build_system_table(
433                    self.catalog_name.clone(),
434                    INFORMATION_SCHEMA_NAME,
435                    table,
436                    options,
437                );
438                (name.to_string(), table)
439            })
440            .collect();
441    }
442}
443
444/// An information-schema table with an explicit visibility guarantee.
445pub trait InformationTable: SystemTable {
446    /// Returns the visibility guaranteed by this table's query implementation.
447    fn scope(&self) -> InformationSchemaTableScope;
448}
449
450pub type InformationTableRef = Arc<dyn InformationTable + Send + Sync>;
451
452pub type InformationExtensionRef = Arc<dyn InformationExtension<Error = Error> + Send + Sync>;
453
454/// The `InformationExtension` trait provides the extension methods for the `information_schema` tables.
455#[async_trait::async_trait]
456pub trait InformationExtension {
457    type Error: ErrorExt;
458
459    /// Gets the nodes information.
460    async fn nodes(&self) -> std::result::Result<Vec<NodeInfo>, Self::Error>;
461
462    /// Gets the procedures information.
463    async fn procedures(&self) -> std::result::Result<Vec<(String, ProcedureInfo)>, Self::Error>;
464
465    /// Gets the region statistics.
466    async fn region_stats(&self) -> std::result::Result<Vec<RegionStat>, Self::Error>;
467
468    /// Get the flow statistics. If no flownode is available, return `None`.
469    async fn flow_stats(&self) -> std::result::Result<Option<FlowStat>, Self::Error>;
470
471    /// Inspects the datanode.
472    async fn inspect_datanode(
473        &self,
474        request: DatanodeInspectRequest,
475    ) -> std::result::Result<SendableRecordBatchStream, Self::Error>;
476
477    /// Whether this extension can execute an inspection query on every datanode.
478    fn supports_inspect_query_plan(&self) -> bool {
479        false
480    }
481
482    /// Builds a plan that executes an inspection query independently on each datanode.
483    /// The caller supplies a plan over reserved inspection tables and retains any
484    /// required global aggregation. The returned schema is the query output schema.
485    fn inspect_datanode_query_plan(
486        &self,
487        _plan: LogicalPlan,
488    ) -> std::result::Result<Option<Arc<dyn ExecutionPlan>>, Self::Error> {
489        Ok(None)
490    }
491
492    /// Builds a physical plan for datanode inspect if the extension can expose
493    /// the distributed fan-in semantics to DataFusion.
494    fn inspect_datanode_plan(
495        &self,
496        _request: DatanodeInspectRequest,
497        _schema: SchemaRef,
498    ) -> std::result::Result<Option<Arc<dyn ExecutionPlan>>, Self::Error> {
499        Ok(None)
500    }
501}
502
503/// The request to inspect the datanode.
504#[derive(Debug, Clone, PartialEq)]
505pub struct DatanodeInspectRequest {
506    /// Kind to fetch from datanode.
507    pub kind: DatanodeInspectKind,
508
509    /// Pushdown scan configuration (projection/predicate/limit) for the returned stream.
510    /// This allows server-side filtering to reduce I/O and network costs.
511    pub scan: ScanRequest,
512}
513
514/// The kind of the datanode inspect request.
515#[derive(Debug, Clone, Copy, PartialEq, Eq)]
516pub enum DatanodeInspectKind {
517    /// Live compaction cycles.
518    CompactionTasks,
519    /// List SST entries recorded in manifest
520    SstManifest,
521    /// List SST entries discovered in storage layer
522    SstStorage,
523    /// List index metadata collected from manifest
524    SstIndexMeta,
525    /// List region runtime and manifest info
526    RegionInfo,
527}
528
529impl DatanodeInspectRequest {
530    /// Builds a logical plan for the datanode inspect request.
531    pub fn build_plan(self) -> std::result::Result<LogicalPlan, DataFusionError> {
532        match self.kind {
533            DatanodeInspectKind::CompactionTasks => CompactionTaskEntry::build_plan(self.scan),
534            DatanodeInspectKind::SstManifest => ManifestSstEntry::build_plan(self.scan),
535            DatanodeInspectKind::SstStorage => StorageSstEntry::build_plan(self.scan),
536            DatanodeInspectKind::SstIndexMeta => PuffinIndexMetaEntry::build_plan(self.scan),
537            DatanodeInspectKind::RegionInfo => RegionInfoEntry::build_plan(self.scan),
538        }
539    }
540}
541pub struct NoopInformationExtension;
542
543#[async_trait::async_trait]
544impl InformationExtension for NoopInformationExtension {
545    type Error = Error;
546
547    async fn nodes(&self) -> std::result::Result<Vec<NodeInfo>, Self::Error> {
548        Ok(vec![])
549    }
550
551    async fn procedures(&self) -> std::result::Result<Vec<(String, ProcedureInfo)>, Self::Error> {
552        Ok(vec![])
553    }
554
555    async fn region_stats(&self) -> std::result::Result<Vec<RegionStat>, Self::Error> {
556        Ok(vec![])
557    }
558
559    async fn flow_stats(&self) -> std::result::Result<Option<FlowStat>, Self::Error> {
560        Ok(None)
561    }
562
563    async fn inspect_datanode(
564        &self,
565        _request: DatanodeInspectRequest,
566    ) -> std::result::Result<SendableRecordBatchStream, Self::Error> {
567        Ok(common_recordbatch::RecordBatches::empty().as_stream())
568    }
569}
570
571#[cfg(test)]
572mod tests {
573    use cache::{build_fundamental_cache_registry, with_default_composite_cache_registry};
574    use common_meta::cache::{CacheRegistryBuilder, LayeredCacheRegistryBuilder};
575    use common_meta::ddl::test_util::create_table::test_create_table_task;
576    use common_meta::key::schema_name::SchemaNameKey;
577    use common_meta::key::table_route::TableRouteValue;
578    use common_meta::kv_backend::memory::MemoryKvBackend;
579    use common_meta::kv_backend::txn::TxnService;
580    use common_meta::wal_provider::RegionWalOptions;
581    use datatypes::schema::Schema;
582    use futures_util::TryStreamExt;
583    use store_api::region_info::RegionInfoEntry;
584    use store_api::storage::TableId;
585
586    use super::*;
587    use crate::error::Result;
588    use crate::information_schema::NoopInformationExtension;
589    use crate::kvbackend::KvBackendCatalogManagerBuilder;
590    use crate::memory::MemoryCatalogManager;
591    use crate::process_manager::ProcessManager;
592
593    struct ScopedFactory {
594        name: &'static str,
595        scope: InformationSchemaTableScope,
596    }
597
598    impl InformationSchemaTableFactory for ScopedFactory {
599        fn make_information_table(&self, _req: MakeInformationTableRequest) -> InformationTableRef {
600            Arc::new(ScopedTable {
601                name: self.name,
602                scope: self.scope,
603            })
604        }
605    }
606
607    struct ScopedTable {
608        name: &'static str,
609        scope: InformationSchemaTableScope,
610    }
611
612    impl InformationTable for ScopedTable {
613        fn scope(&self) -> InformationSchemaTableScope {
614            self.scope
615        }
616    }
617
618    impl SystemTable for ScopedTable {
619        fn table_id(&self) -> TableId {
620            999
621        }
622
623        fn table_name(&self) -> &'static str {
624            self.name
625        }
626
627        fn schema(&self) -> SchemaRef {
628            Arc::new(Schema::new(vec![]))
629        }
630
631        fn to_stream(&self, _request: ScanRequest) -> Result<SendableRecordBatchStream> {
632            Ok(common_recordbatch::RecordBatches::empty().as_stream())
633        }
634    }
635
636    #[test]
637    fn every_registered_information_schema_table_has_scope() {
638        use InformationSchemaTableScope::{Catalog, Global, PublicGlobal};
639
640        let manager: Arc<dyn CatalogManager> = MemoryCatalogManager::new();
641        let backend = Arc::new(MemoryKvBackend::default());
642        let factories: HashMap<_, InformationSchemaTableFactoryRef> = [
643            ("future_catalog_table", Catalog),
644            ("future_global_table", Global),
645            ("future_public_table", PublicGlobal),
646            (BUILD_INFO, Global),
647        ]
648        .into_iter()
649        .map(|(name, scope)| {
650            (
651                name.to_string(),
652                Arc::new(ScopedFactory { name, scope }) as _,
653            )
654        })
655        .collect();
656        let catalog_tables = [
657            TABLES,
658            VIEWS,
659            SCHEMATA,
660            COLUMNS,
661            KEY_COLUMN_USAGE,
662            TABLE_CONSTRAINTS,
663            STATISTICS,
664            FLOWS,
665            FLOW_STATISTICS,
666            TABLE_SEMANTICS,
667            PARTITIONS,
668            REGION_PEERS,
669            #[cfg(feature = "enterprise")]
670            RECYCLE_BIN,
671            "future_catalog_table",
672        ];
673        let public_global_tables = [
674            ENGINES,
675            CHARACTER_SETS,
676            COLLATIONS,
677            COLLATION_CHARACTER_SET_APPLICABILITY,
678            "future_public_table",
679        ];
680
681        for (catalog, with_process_manager) in [
682            (DEFAULT_CATALOG_NAME, true),
683            (DEFAULT_CATALOG_NAME, false),
684            ("tenant", true),
685            ("tenant", false),
686        ] {
687            let provider = InformationSchemaProvider::new(
688                catalog.to_string(),
689                Arc::downgrade(&manager),
690                Arc::new(FlowMetadataManager::new(backend.clone())),
691                with_process_manager.then(|| Arc::new(ProcessManager::new(String::new(), None))),
692                backend.clone(),
693            );
694            for name in [
695                BUILD_INFO,
696                ENGINES,
697                CHARACTER_SETS,
698                COLLATIONS,
699                COLLATION_CHARACTER_SET_APPLICABILITY,
700            ] {
701                assert_eq!(
702                    provider
703                        .table(name)
704                        .unwrap()
705                        .table_info()
706                        .meta
707                        .options
708                        .extra_options
709                        .get(SEMANTIC_TABLE_SCOPE)
710                        .map(String::as_str),
711                    Some(PublicGlobal.as_str()),
712                    "{catalog}.{name}"
713                );
714            }
715            // An extension replacing a built-in supplies the replacement table's scope.
716            let provider = provider.with_extra_table_factories(factories.clone());
717            let expected_count =
718                45 + usize::from(with_process_manager) + usize::from(cfg!(feature = "enterprise"))
719                    - if catalog == DEFAULT_CATALOG_NAME {
720                        0
721                    } else {
722                        9
723                    };
724            assert_eq!(provider.tables().len(), expected_count);
725            for (name, table) in provider.tables() {
726                let scope = if catalog_tables.contains(&name.as_str()) {
727                    Catalog
728                } else if public_global_tables.contains(&name.as_str()) {
729                    PublicGlobal
730                } else {
731                    Global
732                };
733                assert_eq!(
734                    table
735                        .table_info()
736                        .meta
737                        .options
738                        .extra_options
739                        .get(SEMANTIC_TABLE_SCOPE)
740                        .map(String::as_str),
741                    Some(scope.as_str()),
742                    "{catalog}.{name}"
743                );
744            }
745            assert_eq!(
746                provider.table(REGION_PEERS).is_some(),
747                catalog == DEFAULT_CATALOG_NAME
748            );
749            assert_eq!(provider.table(PROCESS_LIST).is_some(), with_process_manager);
750            if let Some(table) = provider.table(PROCESS_LIST) {
751                assert!(table.schema().column_schema_by_name("catalog").is_some());
752            }
753        }
754    }
755
756    #[tokio::test]
757    async fn newly_accessible_information_schema_tables_filter_catalogs() {
758        let backend = Arc::new(MemoryKvBackend::default());
759        let caches = LayeredCacheRegistryBuilder::default()
760            .add_cache_registry(CacheRegistryBuilder::default().build())
761            .add_cache_registry(build_fundamental_cache_registry(backend.clone()));
762        let manager = KvBackendCatalogManagerBuilder::new(
763            Arc::new(NoopInformationExtension),
764            backend.clone(),
765            Arc::new(
766                with_default_composite_cache_registry(caches)
767                    .unwrap()
768                    .build(),
769            ),
770        )
771        .build();
772        let metadata = manager.table_metadata_manager_ref();
773        let flow_metadata = FlowMetadataManager::new(backend.clone());
774        for (catalog, name, id) in [
775            ("tenant_a", "visible_a", 1024),
776            ("tenant_b", "visible_b", 1025),
777        ] {
778            metadata
779                .schema_manager()
780                .create(SchemaNameKey::new(catalog, "public"), None, false)
781                .await
782                .unwrap();
783            let mut info = test_create_table_task(name, id).table_info;
784            info.catalog_name = catalog.to_string();
785            info.meta
786                .options
787                .extra_options
788                .insert(SEMANTIC_TABLE_SCOPE.to_string(), "catalog".to_string());
789            metadata
790                .create_table_metadata(
791                    info,
792                    TableRouteValue::physical(vec![]),
793                    RegionWalOptions::default(),
794                )
795                .await
796                .unwrap();
797            let (txn, _) = flow_metadata
798                .flow_name_manager()
799                .build_create_txn(catalog, name, id)
800                .unwrap();
801            backend.txn(txn).await.unwrap();
802        }
803
804        for (catalog, visible, hidden) in [
805            ("tenant_a", "visible_a", "visible_b"),
806            ("tenant_b", "visible_b", "visible_a"),
807        ] {
808            for name in [TABLE_SEMANTICS, STATISTICS, FLOW_STATISTICS] {
809                let table = manager
810                    .table(catalog, INFORMATION_SCHEMA_NAME, name, None)
811                    .await
812                    .unwrap()
813                    .unwrap();
814                let batches = table
815                    .scan_to_stream(ScanRequest::default())
816                    .await
817                    .unwrap()
818                    .try_collect::<Vec<_>>()
819                    .await
820                    .unwrap();
821                let output = batches
822                    .iter()
823                    .map(|batch| batch.pretty_print())
824                    .collect::<Vec<_>>()
825                    .join("\n");
826                assert!(output.contains(visible), "{catalog}.{name}: {output}");
827                assert!(!output.contains(hidden), "{catalog}.{name}: {output}");
828            }
829        }
830        assert!(
831            !manager
832                .information_schema_provider()
833                .tables()
834                .contains_key("visible_a")
835        );
836    }
837
838    #[test]
839    fn test_compaction_tasks_build_plan() {
840        let request = DatanodeInspectRequest {
841            kind: DatanodeInspectKind::CompactionTasks,
842            scan: ScanRequest {
843                projection: Some(vec![0]),
844                filters: vec![
845                    datafusion::logical_expr::col("state")
846                        .eq(datafusion::logical_expr::lit("running")),
847                ],
848                limit: Some(1),
849                ..Default::default()
850            },
851        };
852        let plan = request.build_plan().unwrap();
853        assert_eq!(plan.schema().fields().len(), 1);
854        assert!(
855            plan.display_indent()
856                .to_string()
857                .contains("__compaction_tasks")
858        );
859    }
860
861    #[test]
862    fn test_datanode_inspect_region_info_build_plan() {
863        let plan = DatanodeInspectRequest {
864            kind: DatanodeInspectKind::RegionInfo,
865            scan: ScanRequest::default(),
866        }
867        .build_plan()
868        .unwrap();
869
870        let LogicalPlan::TableScan(scan) = plan else {
871            panic!("expected table scan");
872        };
873        assert_eq!(
874            scan.table_name.to_string(),
875            RegionInfoEntry::reserved_table_name_for_inspection()
876        );
877    }
878}