1use std::any::Any;
16use std::collections::{BTreeMap, BTreeSet, HashMap};
17use std::sync::{Arc, OnceLock, Weak};
18
19use async_stream::try_stream;
20use common_catalog::consts::{
21 DEFAULT_CATALOG_NAME, DEFAULT_PRIVATE_SCHEMA_NAME, DEFAULT_SCHEMA_NAME,
22 INFORMATION_SCHEMA_NAME, PG_CATALOG_NAME,
23};
24use common_error::ext::BoxedError;
25use common_meta::cache::{
26 LayeredCacheRegistryRef, TableInfoCacheRef, TableNameCacheRef, TableRoute, TableRouteCacheRef,
27 ViewInfoCacheRef,
28};
29use common_meta::key::TableMetadataManagerRef;
30use common_meta::key::catalog_name::CatalogNameKey;
31use common_meta::key::flow::FlowMetadataManager;
32use common_meta::key::schema_name::SchemaNameKey;
33use common_meta::key::table_info::TableInfoValue;
34use common_meta::key::table_name::TableNameKey;
35use common_meta::kv_backend::KvBackendRef;
36use common_procedure::ProcedureManagerRef;
37use futures_util::stream::BoxStream;
38use futures_util::{Stream, StreamExt, TryStreamExt};
39use itertools::Either;
40use moka::sync::Cache;
41use partition::manager::PartitionRuleManagerRef;
42use session::context::{Channel, QueryContext};
43use snafu::prelude::*;
44use store_api::metric_engine_consts::METRIC_ENGINE_NAME;
45use table::TableRef;
46use table::dist_table::DistTable;
47use table::metadata::{TableId, TableInfoRef};
48use table::table::PartitionRules;
49use table::table_name::TableName;
50
51use crate::CatalogManager;
52use crate::batch_scan::BatchScanner;
53use crate::error::{
54 CacheNotFoundSnafu, GetTableCacheSnafu, ListCatalogsSnafu, ListSchemasSnafu, ListTablesSnafu,
55 Result, TableMetadataManagerSnafu,
56};
57use crate::information_schema::{
58 InformationExtensionRef, InformationSchemaProvider, InformationSchemaTableFactoryRef,
59};
60use crate::kvbackend::TableCacheRef;
61use crate::process_manager::ProcessManagerRef;
62use crate::system_schema::SystemSchemaProvider;
63use crate::system_schema::numbers_table_provider::NumbersTableProvider;
64use crate::system_schema::pg_catalog::PGCatalogProvider;
65use crate::system_schema::semantic_graph::{EntityGraphProviderRef, SemanticGraphTableProvider};
66
67#[derive(Clone)]
73pub struct KvBackendCatalogManager {
74 pub(super) information_extension: InformationExtensionRef,
76 pub(super) entity_graph_provider: Arc<OnceLock<EntityGraphProviderRef>>,
82 pub(super) partition_manager: PartitionRuleManagerRef,
84 pub(super) table_metadata_manager: TableMetadataManagerRef,
86 pub(super) system_catalog: SystemCatalog,
88 pub(super) cache_registry: LayeredCacheRegistryRef,
90 pub(super) procedure_manager: Option<ProcedureManagerRef>,
92}
93
94pub(super) const CATALOG_CACHE_MAX_CAPACITY: u64 = 128;
95
96impl KvBackendCatalogManager {
97 pub fn information_schema_provider(&self) -> &InformationSchemaProvider {
99 &self.system_catalog.information_schema_provider
100 }
101
102 pub(crate) async fn schema_options(&self, catalog: &str) -> Result<BTreeMap<String, String>> {
103 let mut schemas = self
104 .table_metadata_manager
105 .schema_manager()
106 .schemas(catalog)
107 .map_ok(|(name, value)| (name, value.to_string()))
108 .try_collect::<BTreeMap<_, _>>()
109 .await
110 .map_err(BoxedError::new)
111 .context(ListSchemasSnafu { catalog })?;
112 for name in self.system_catalog.schema_names(None) {
113 schemas.entry(name).or_default();
114 }
115 Ok(schemas)
116 }
117
118 pub(crate) fn flow_info_cache(&self) -> Option<common_meta::cache::FlowInfoCacheRef> {
119 self.cache_registry.get()
120 }
121
122 pub fn view_info_cache(&self) -> Result<ViewInfoCacheRef> {
123 self.cache_registry.get().context(CacheNotFoundSnafu {
124 name: "view_info_cache",
125 })
126 }
127
128 pub fn information_extension(&self) -> InformationExtensionRef {
130 self.information_extension.clone()
131 }
132
133 pub fn entity_graph_provider(&self) -> Option<EntityGraphProviderRef> {
137 self.entity_graph_provider.get().cloned()
138 }
139
140 pub fn set_entity_graph_provider(&self, provider: EntityGraphProviderRef) {
143 let _ = self.entity_graph_provider.set(provider);
144 }
145
146 pub fn partition_manager(&self) -> PartitionRuleManagerRef {
147 self.partition_manager.clone()
148 }
149
150 pub fn table_metadata_manager_ref(&self) -> &TableMetadataManagerRef {
151 &self.table_metadata_manager
152 }
153
154 pub fn procedure_manager(&self) -> Option<ProcedureManagerRef> {
155 self.procedure_manager.clone()
156 }
157
158 async fn override_logical_table_partition_key_indices(
160 table_route_cache: &TableRouteCacheRef,
161 table_info_cache: &TableInfoCacheRef,
162 table: TableRef,
163 ) -> Result<TableRef> {
164 if table.table_info().meta.engine != METRIC_ENGINE_NAME {
166 return Ok(table);
167 }
168
169 if let Some(table_route_value) = table_route_cache
170 .get(table.table_info().table_id())
171 .await
172 .context(TableMetadataManagerSnafu)?
173 && let TableRoute::Logical(logical_route) = &*table_route_value
174 && let Some(physical_table_info) = table_info_cache
175 .get(logical_route.physical_table_id())
176 .await
177 .context(TableMetadataManagerSnafu)?
178 {
179 return Ok(Self::logical_table(
180 table.table_info(),
181 &physical_table_info,
182 ));
183 }
184 Ok(table)
185 }
186
187 async fn load_tables(
188 ids: Vec<TableId>,
189 infos: &TableInfoCacheRef,
190 routes: &TableRouteCacheRef,
191 ) -> Result<impl Iterator<Item = TableRef> + use<>> {
192 let tables: Vec<_> = infos
193 .get_many(&ids)
194 .await
195 .context(TableMetadataManagerSnafu)?
196 .into_iter()
197 .flatten()
198 .collect();
199 let metric_ids: Vec<_> = tables
200 .iter()
201 .filter(|info| info.meta.engine == METRIC_ENGINE_NAME)
202 .map(|info| info.table_id())
203 .collect();
204 let metric_routes = routes
205 .get_many(&metric_ids)
206 .await
207 .context(TableMetadataManagerSnafu)?;
208 let logical: HashMap<_, _> = metric_ids
209 .into_iter()
210 .zip(metric_routes)
211 .filter_map(|(id, route)| match route.as_deref()? {
212 TableRoute::Logical(route) => Some((id, route.physical_table_id())),
213 TableRoute::Physical(_) => None,
214 })
215 .collect();
216 let physical_ids: BTreeSet<_> = logical.values().copied().collect();
217 let physical_ids: Vec<_> = physical_ids.into_iter().collect();
218 let physical = infos
219 .get_many(&physical_ids)
220 .await
221 .context(TableMetadataManagerSnafu)?;
222 let physical: HashMap<_, _> = physical_ids
223 .into_iter()
224 .zip(physical)
225 .filter_map(|(id, info)| Some((id, info?)))
226 .collect();
227 Ok(tables.into_iter().map(move |info| {
228 if let Some(physical) = logical
229 .get(&info.table_id())
230 .and_then(|id| physical.get(id))
231 {
232 Self::logical_table(info, physical)
233 } else {
234 DistTable::table(info)
235 }
236 }))
237 }
238
239 fn logical_table(info: TableInfoRef, physical_table_info: &TableInfoRef) -> TableRef {
240 let mut new_table_info = info.as_ref().clone();
241
242 let mut phy_part_cols_not_in_logical_table = vec![];
243
244 new_table_info.meta.partition_key_indices = physical_table_info
246 .meta
247 .partition_key_indices
248 .iter()
249 .filter_map(|&physical_index| {
250 physical_table_info
252 .meta
253 .schema
254 .column_schemas()
255 .get(physical_index)
256 .and_then(|physical_column| {
257 let idx = new_table_info
259 .meta
260 .schema
261 .column_index_by_name(physical_column.name.as_str());
262 if idx.is_none() {
263 phy_part_cols_not_in_logical_table.push(physical_column.name.clone());
265 }
266
267 idx
268 })
269 })
270 .collect();
271
272 let partition_rules = if !phy_part_cols_not_in_logical_table.is_empty() {
273 Some(PartitionRules {
274 extra_phy_cols_not_in_logical_table: phy_part_cols_not_in_logical_table,
275 })
276 } else {
277 None
278 };
279
280 DistTable::table_partitioned(Arc::new(new_table_info), partition_rules)
281 }
282}
283
284#[async_trait::async_trait]
285impl CatalogManager for KvBackendCatalogManager {
286 fn as_any(&self) -> &dyn Any {
287 self
288 }
289
290 async fn catalog_names(&self) -> Result<Vec<String>> {
291 let stream = self
292 .table_metadata_manager
293 .catalog_manager()
294 .catalog_names();
295
296 let keys = stream
297 .try_collect::<Vec<_>>()
298 .await
299 .map_err(BoxedError::new)
300 .context(ListCatalogsSnafu)?;
301
302 Ok(keys)
303 }
304
305 async fn schema_names(
306 &self,
307 catalog: &str,
308 query_ctx: Option<&QueryContext>,
309 ) -> Result<Vec<String>> {
310 let stream = self
311 .table_metadata_manager
312 .schema_manager()
313 .schema_names(catalog);
314 let mut keys = stream
315 .try_collect::<BTreeSet<_>>()
316 .await
317 .map_err(BoxedError::new)
318 .context(ListSchemasSnafu { catalog })?;
319
320 keys.extend(self.system_catalog.schema_names(query_ctx));
321
322 Ok(keys.into_iter().collect())
323 }
324
325 async fn table_names(
326 &self,
327 catalog: &str,
328 schema: &str,
329 query_ctx: Option<&QueryContext>,
330 ) -> Result<Vec<String>> {
331 let mut tables = self
332 .table_metadata_manager
333 .table_name_manager()
334 .tables(catalog, schema)
335 .map_ok(|(table_name, _)| table_name)
336 .try_collect::<Vec<_>>()
337 .await
338 .map_err(BoxedError::new)
339 .context(ListTablesSnafu { catalog, schema })?;
340
341 tables.extend(self.system_catalog.table_names(schema, query_ctx));
342 Ok(tables)
343 }
344
345 async fn catalog_exists(&self, catalog: &str) -> Result<bool> {
346 self.table_metadata_manager
347 .catalog_manager()
348 .exists(CatalogNameKey::new(catalog))
349 .await
350 .context(TableMetadataManagerSnafu)
351 }
352
353 async fn schema_exists(
354 &self,
355 catalog: &str,
356 schema: &str,
357 query_ctx: Option<&QueryContext>,
358 ) -> Result<bool> {
359 if self.system_catalog.schema_exists(schema, query_ctx) {
360 return Ok(true);
361 }
362
363 self.table_metadata_manager
364 .schema_manager()
365 .exists(SchemaNameKey::new(catalog, schema))
366 .await
367 .context(TableMetadataManagerSnafu)
368 }
369
370 async fn table_exists(
371 &self,
372 catalog: &str,
373 schema: &str,
374 table: &str,
375 query_ctx: Option<&QueryContext>,
376 ) -> Result<bool> {
377 if self.system_catalog.table_exists(schema, table, query_ctx) {
378 return Ok(true);
379 }
380
381 let key = TableNameKey::new(catalog, schema, table);
382 self.table_metadata_manager
383 .table_name_manager()
384 .get(key)
385 .await
386 .context(TableMetadataManagerSnafu)
387 .map(|x| x.is_some())
388 }
389
390 async fn table(
391 &self,
392 catalog_name: &str,
393 schema_name: &str,
394 table_name: &str,
395 query_ctx: Option<&QueryContext>,
396 ) -> Result<Option<TableRef>> {
397 let channel = query_ctx.map_or(Channel::Unknown, |ctx| ctx.channel());
398 if let Some(table) =
399 self.system_catalog
400 .table(catalog_name, schema_name, table_name, query_ctx)
401 {
402 return Ok(Some(table));
403 }
404
405 let table_cache: TableCacheRef = self.cache_registry.get().context(CacheNotFoundSnafu {
406 name: "table_cache",
407 })?;
408
409 let table = table_cache
410 .get_by_ref(&TableName {
411 catalog_name: catalog_name.to_string(),
412 schema_name: schema_name.to_string(),
413 table_name: table_name.to_string(),
414 })
415 .await
416 .context(GetTableCacheSnafu)?;
417
418 if let Some(table) = table {
419 let table_route_cache: TableRouteCacheRef =
420 self.cache_registry.get().context(CacheNotFoundSnafu {
421 name: "table_route_cache",
422 })?;
423 let table_info_cache: TableInfoCacheRef =
424 self.cache_registry.get().context(CacheNotFoundSnafu {
425 name: "table_info_cache",
426 })?;
427 return Self::override_logical_table_partition_key_indices(
428 &table_route_cache,
429 &table_info_cache,
430 table,
431 )
432 .await
433 .map(Some);
434 }
435
436 if channel == Channel::Postgres {
437 if let Some(table) =
439 self.system_catalog
440 .table(catalog_name, PG_CATALOG_NAME, table_name, query_ctx)
441 {
442 return Ok(Some(table));
443 }
444 }
445
446 Ok(None)
447 }
448
449 async fn table_id(
450 &self,
451 catalog_name: &str,
452 schema_name: &str,
453 table_name: &str,
454 query_ctx: Option<&QueryContext>,
455 ) -> Result<Option<TableId>> {
456 let channel = query_ctx.map_or(Channel::Unknown, |ctx| ctx.channel());
457 if let Some(table) =
458 self.system_catalog
459 .table(catalog_name, schema_name, table_name, query_ctx)
460 {
461 return Ok(Some(table.table_info().table_id()));
462 }
463
464 let table_cache: TableNameCacheRef =
465 self.cache_registry.get().context(CacheNotFoundSnafu {
466 name: "table_name_cache",
467 })?;
468
469 let table = table_cache
470 .get_by_ref(&TableName {
471 catalog_name: catalog_name.to_string(),
472 schema_name: schema_name.to_string(),
473 table_name: table_name.to_string(),
474 })
475 .await
476 .context(GetTableCacheSnafu)?;
477
478 if let Some(table) = table {
479 return Ok(Some(table));
480 }
481
482 if channel == Channel::Postgres {
483 if let Some(table) =
485 self.system_catalog
486 .table(catalog_name, PG_CATALOG_NAME, table_name, query_ctx)
487 {
488 return Ok(Some(table.table_info().table_id()));
489 }
490 }
491
492 Ok(None)
493 }
494
495 async fn table_ids(&self, names: &[TableName]) -> Result<Vec<Option<TableId>>> {
496 let mut results = vec![None; names.len()];
497 let mut missing = Vec::new();
498 let mut positions = Vec::new();
499 for (index, name) in names.iter().enumerate() {
500 if let Some(table) = self.system_catalog.table(
501 &name.catalog_name,
502 &name.schema_name,
503 &name.table_name,
504 None,
505 ) {
506 results[index] = Some(table.table_info().table_id());
507 } else {
508 missing.push(name.clone());
509 positions.push(index);
510 }
511 }
512 if missing.is_empty() {
513 return Ok(results);
514 }
515 let cache: TableNameCacheRef = self.cache_registry.get().context(CacheNotFoundSnafu {
516 name: "table_name_cache",
517 })?;
518 for (index, value) in positions
519 .into_iter()
520 .zip(cache.get_many(&missing).await.context(GetTableCacheSnafu)?)
521 {
522 results[index] = value;
523 }
524 Ok(results)
525 }
526
527 async fn table_infos_by_ids(&self, ids: &[TableId]) -> Result<Vec<Option<TableInfoRef>>> {
528 if ids.is_empty() {
529 return Ok(Vec::new());
530 }
531 let cache: TableInfoCacheRef = self.cache_registry.get().context(CacheNotFoundSnafu {
532 name: "table_info_cache",
533 })?;
534 cache.get_many(ids).await.context(GetTableCacheSnafu)
535 }
536
537 async fn table_info_by_id(&self, table_id: TableId) -> Result<Option<TableInfoRef>> {
538 let table_info_cache: TableInfoCacheRef =
539 self.cache_registry.get().context(CacheNotFoundSnafu {
540 name: "table_info_cache",
541 })?;
542 table_info_cache
543 .get_by_ref(&table_id)
544 .await
545 .context(GetTableCacheSnafu)
546 }
547
548 async fn tables_by_ids(
549 &self,
550 catalog: &str,
551 schema: &str,
552 table_ids: &[TableId],
553 ) -> Result<Vec<TableRef>> {
554 let table_info_values = self
555 .table_metadata_manager
556 .table_info_manager()
557 .batch_get(table_ids)
558 .await
559 .context(TableMetadataManagerSnafu)?;
560
561 let tables = table_info_values
562 .into_values()
563 .filter(|t| t.table_info.catalog_name == catalog && t.table_info.schema_name == schema)
564 .map(build_table)
565 .collect::<Vec<_>>();
566
567 Ok(tables)
568 }
569
570 fn tables<'a>(
571 &'a self,
572 catalog: &'a str,
573 schema: &'a str,
574 query_ctx: Option<&'a QueryContext>,
575 ) -> BoxStream<'a, Result<TableRef>> {
576 try_stream! {
577 for table in self.system_tables(catalog, schema, query_ctx) {
578 yield table;
579 }
580 let (infos, routes) = self.table_caches()?;
581 let ids = self.user_table_ids(catalog, schema);
582 let batches =
583 BatchScanner::METADATA.scan(ids, |ids| Self::load_tables(ids, &infos, &routes));
584 let mut batches = std::pin::pin!(batches);
585 while let Some(batch) = batches.try_next().await? {
586 for table in batch {
587 yield table;
588 }
589 }
590 }
591 .boxed()
592 }
593}
594
595impl KvBackendCatalogManager {
596 fn system_tables<'a>(
597 &'a self,
598 catalog: &'a str,
599 schema: &'a str,
600 query_ctx: Option<&'a QueryContext>,
601 ) -> impl Iterator<Item = TableRef> + 'a {
602 self.system_catalog
603 .table_names(schema, query_ctx)
604 .into_iter()
605 .filter_map(move |name| self.system_catalog.table(catalog, schema, &name, query_ctx))
606 }
607
608 fn user_table_ids<'a>(
609 &'a self,
610 catalog: &'a str,
611 schema: &'a str,
612 ) -> impl Stream<Item = Result<TableId>> + 'a {
613 self.table_metadata_manager
614 .table_name_manager()
615 .tables(catalog, schema)
616 .map(move |entry| {
617 entry
618 .map(|(_, value)| value.table_id())
619 .map_err(BoxedError::new)
620 .context(ListTablesSnafu { catalog, schema })
621 })
622 }
623
624 fn table_caches(&self) -> Result<(TableInfoCacheRef, TableRouteCacheRef)> {
625 let routes = self.cache_registry.get().context(CacheNotFoundSnafu {
626 name: "table_route_cache",
627 })?;
628 let infos = self.cache_registry.get().context(CacheNotFoundSnafu {
629 name: "table_info_cache",
630 })?;
631 Ok((infos, routes))
632 }
633
634 pub(crate) fn sequential_table_batches<'a>(
636 &'a self,
637 catalog: &'a str,
638 schema: &'a str,
639 ) -> impl Stream<Item = Result<impl Iterator<Item = TableRef> + 'a>> + 'a {
640 const BATCH_SIZE: usize = 128;
641 try_stream! {
642 yield Either::Left(self.system_tables(catalog, schema, None));
643
644 let (infos, routes) = self.table_caches()?;
645 let mut batches = self.user_table_ids(catalog, schema).ready_chunks(BATCH_SIZE);
646 while let Some(batch) = batches.next().await {
647 let ids = batch.into_iter().collect::<Result<Vec<_>>>()?;
648 yield Either::Right(Self::load_tables(ids, &infos, &routes).await?);
649 }
650 }
651 }
652}
653
654fn build_table(table_info_value: TableInfoValue) -> TableRef {
655 let table_info = table_info_value.table_info;
656 DistTable::table(Arc::new(table_info))
657}
658
659#[derive(Clone)]
667pub(super) struct SystemCatalog {
668 pub(super) catalog_manager: Weak<KvBackendCatalogManager>,
669 pub(super) catalog_cache: Cache<String, Arc<InformationSchemaProvider>>,
670 pub(super) pg_catalog_cache: Cache<String, Arc<PGCatalogProvider>>,
671
672 pub(super) information_schema_provider: Arc<InformationSchemaProvider>,
674 pub(super) pg_catalog_provider: Arc<PGCatalogProvider>,
675 pub(super) numbers_table_provider: NumbersTableProvider,
676 pub(super) backend: KvBackendRef,
677 pub(super) process_manager: Option<ProcessManagerRef>,
678 pub(super) extra_information_table_factories:
679 std::collections::HashMap<String, InformationSchemaTableFactoryRef>,
680}
681
682impl SystemCatalog {
683 fn schema_names(&self, query_ctx: Option<&QueryContext>) -> Vec<String> {
684 let channel = query_ctx.map_or(Channel::Unknown, |ctx| ctx.channel());
685 match channel {
686 Channel::Postgres => vec![
688 INFORMATION_SCHEMA_NAME.to_string(),
689 PG_CATALOG_NAME.to_string(),
690 ],
691 _ => {
692 vec![INFORMATION_SCHEMA_NAME.to_string()]
693 }
694 }
695 }
696
697 fn table_names(&self, schema: &str, query_ctx: Option<&QueryContext>) -> Vec<String> {
698 let channel = query_ctx.map_or(Channel::Unknown, |ctx| ctx.channel());
699 match schema {
700 INFORMATION_SCHEMA_NAME => self.information_schema_provider.table_names(),
701 PG_CATALOG_NAME if channel == Channel::Postgres => {
702 self.pg_catalog_provider.table_names()
703 }
704 DEFAULT_SCHEMA_NAME => self.numbers_table_provider.table_names(),
705 DEFAULT_PRIVATE_SCHEMA_NAME => SemanticGraphTableProvider::table_names(),
708 _ => vec![],
709 }
710 }
711
712 fn schema_exists(&self, schema: &str, query_ctx: Option<&QueryContext>) -> bool {
713 let channel = query_ctx.map_or(Channel::Unknown, |ctx| ctx.channel());
714 match channel {
715 Channel::Postgres => schema == PG_CATALOG_NAME || schema == INFORMATION_SCHEMA_NAME,
716 _ => schema == INFORMATION_SCHEMA_NAME,
717 }
718 }
719
720 fn table_exists(&self, schema: &str, table: &str, query_ctx: Option<&QueryContext>) -> bool {
721 let channel = query_ctx.map_or(Channel::Unknown, |ctx| ctx.channel());
722 if schema == INFORMATION_SCHEMA_NAME {
723 self.information_schema_provider.table(table).is_some()
724 } else if schema == DEFAULT_SCHEMA_NAME {
725 self.numbers_table_provider.table_exists(table)
726 } else if schema == PG_CATALOG_NAME && channel == Channel::Postgres {
727 self.pg_catalog_provider.table(table).is_some()
728 } else if schema == DEFAULT_PRIVATE_SCHEMA_NAME {
729 SemanticGraphTableProvider::table_exists(table)
730 } else {
731 false
732 }
733 }
734
735 fn table(
736 &self,
737 catalog: &str,
738 schema: &str,
739 table_name: &str,
740 query_ctx: Option<&QueryContext>,
741 ) -> Option<TableRef> {
742 let channel = query_ctx.map_or(Channel::Unknown, |ctx| ctx.channel());
743 if schema == INFORMATION_SCHEMA_NAME {
744 let information_schema_provider =
745 self.catalog_cache.get_with_by_ref(catalog, move || {
746 let provider = InformationSchemaProvider::new(
747 catalog.to_string(),
748 self.catalog_manager.clone(),
749 Arc::new(FlowMetadataManager::new(self.backend.clone())),
750 self.process_manager.clone(),
751 self.backend.clone(),
752 );
753 let provider = provider
754 .with_extra_table_factories(self.extra_information_table_factories.clone());
755 Arc::new(provider)
756 });
757 information_schema_provider.table(table_name)
758 } else if schema == PG_CATALOG_NAME && channel == Channel::Postgres {
759 if catalog == DEFAULT_CATALOG_NAME {
760 self.pg_catalog_provider.table(table_name)
761 } else {
762 let pg_catalog_provider =
763 self.pg_catalog_cache.get_with_by_ref(catalog, move || {
764 Arc::new(PGCatalogProvider::new(
765 catalog.to_string(),
766 self.catalog_manager.clone(),
767 ))
768 });
769 pg_catalog_provider.table(table_name)
770 }
771 } else if schema == DEFAULT_SCHEMA_NAME {
772 self.numbers_table_provider.table(table_name)
773 } else if schema == DEFAULT_PRIVATE_SCHEMA_NAME
774 && SemanticGraphTableProvider::table_exists(table_name)
775 {
776 SemanticGraphTableProvider::new(
780 catalog.to_string(),
781 self.catalog_manager.clone(),
782 query_ctx.cloned().map(Arc::new),
783 )
784 .table(table_name)
785 } else {
786 None
787 }
788 }
789}
790
791#[cfg(test)]
792mod tests {
793 use std::sync::atomic::{AtomicUsize, Ordering};
794
795 use common_catalog::consts::NUMBERS_TABLE_ID;
796 use common_meta::cache::{
797 CacheContainer, CacheRegistryBuilder, Initializer, LayeredCacheRegistryBuilder,
798 };
799 use common_meta::ddl::test_util::create_table::test_create_table_task;
800 use common_meta::instruction::CacheIdent;
801 use common_meta::key::table_route::{LogicalTableRouteValue, TableRouteValue};
802 use common_meta::kv_backend::memory::MemoryKvBackend;
803 use moka::future::Cache as FutureCache;
804 use partition::cache::PartitionInfoCacheRef;
805 use table::metadata::TableInfo;
806 use table::table::numbers::NUMBERS_TABLE_NAME;
807
808 use super::*;
809
810 fn batch_lookup_manager(
811 backend: KvBackendRef,
812 registry: LayeredCacheRegistryRef,
813 ) -> Arc<KvBackendCatalogManager> {
814 crate::kvbackend::KvBackendCatalogManagerBuilder::new(
815 Arc::new(crate::information_schema::NoopInformationExtension),
816 backend,
817 registry,
818 )
819 .build()
820 }
821
822 #[tokio::test]
823 async fn test_batch_lookups_without_table_caches() {
824 let backend = Arc::new(MemoryKvBackend::default());
825 let caches = cache::build_datanode_layered_cache_registry(backend.clone());
826 let routing = CacheRegistryBuilder::default()
827 .add_cache(caches.get::<TableRouteCacheRef>().unwrap())
828 .add_cache(caches.get::<PartitionInfoCacheRef>().unwrap())
829 .build();
830 let registry = LayeredCacheRegistryBuilder::default()
831 .add_cache_registry(routing)
832 .build();
833 let manager = batch_lookup_manager(backend, Arc::new(registry));
834 assert!(manager.table_ids(&[]).await.unwrap().is_empty());
835 assert!(manager.table_infos_by_ids(&[]).await.unwrap().is_empty());
836 let numbers = TableName::new(
837 DEFAULT_CATALOG_NAME,
838 DEFAULT_SCHEMA_NAME,
839 NUMBERS_TABLE_NAME,
840 );
841 assert_eq!(
842 manager.table_ids(&[numbers]).await.unwrap(),
843 [Some(NUMBERS_TABLE_ID)]
844 );
845 }
846
847 #[tokio::test]
848 async fn test_batch_lookups_preserve_positions_and_system_table_precedence() {
849 let backend = Arc::new(MemoryKvBackend::default());
850 let registry = cache::build_datanode_layered_cache_registry(backend.clone());
851 let manager = batch_lookup_manager(backend, Arc::new(registry));
852 for (name, id) in [
853 ("warm", 1024),
854 ("cold", 1025),
855 (NUMBERS_TABLE_NAME, 1026),
856 ("other", 1027),
857 ] {
858 manager
859 .table_metadata_manager
860 .create_table_metadata(
861 test_create_table_task(name, id).table_info,
862 TableRouteValue::physical(vec![]),
863 Default::default(),
864 )
865 .await
866 .unwrap();
867 }
868 assert_eq!(
869 manager
870 .table_id(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, "warm", None)
871 .await
872 .unwrap(),
873 Some(1024)
874 );
875 assert_eq!(
876 manager.table_info_by_id(1024).await.unwrap().unwrap().name,
877 "warm"
878 );
879 let names = [
880 "other",
881 NUMBERS_TABLE_NAME,
882 "cold",
883 "missing",
884 "warm",
885 "other",
886 ]
887 .map(|name| TableName::new(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, name));
888 assert_eq!(
889 manager.table_ids(&names).await.unwrap(),
890 [
891 Some(1027),
892 Some(NUMBERS_TABLE_ID),
893 Some(1025),
894 None,
895 Some(1024),
896 Some(1027)
897 ]
898 );
899 let infos = manager
900 .table_infos_by_ids(&[1026, 4040, 1024, 1025, 1026])
901 .await
902 .unwrap();
903 let entries: Vec<_> = infos
904 .iter()
905 .map(|info| {
906 info.as_ref()
907 .map(|info| (info.table_id(), info.name.as_str()))
908 })
909 .collect();
910 assert_eq!(
911 entries,
912 [
913 Some((1026, NUMBERS_TABLE_NAME)),
914 None,
915 Some((1024, "warm")),
916 Some((1025, "cold")),
917 Some((1026, NUMBERS_TABLE_NAME))
918 ]
919 );
920 }
921
922 #[tokio::test]
923 async fn test_schema_options_preserve_user_options_and_system_schema() {
924 use std::time::Duration;
925
926 use common_meta::key::schema_name::SchemaNameValue;
927 use datatypes::arrow_array::string_array_value_at_index;
928
929 let backend = Arc::new(MemoryKvBackend::default());
930 let registry = cache::build_datanode_layered_cache_registry(backend.clone());
931 let manager = batch_lookup_manager(backend, Arc::new(registry));
932 let options = SchemaNameValue {
933 ttl: Some(Duration::from_secs(9).into()),
934 extra_options: [("region".into(), "east".into())].into(),
935 ..Default::default()
936 };
937 manager
938 .table_metadata_manager
939 .schema_manager()
940 .create(
941 SchemaNameKey::new(DEFAULT_CATALOG_NAME, "user_schema"),
942 Some(options),
943 true,
944 )
945 .await
946 .unwrap();
947 let schemata = manager
948 .table(
949 DEFAULT_CATALOG_NAME,
950 INFORMATION_SCHEMA_NAME,
951 "schemata",
952 None,
953 )
954 .await
955 .unwrap()
956 .unwrap();
957 let batches: Vec<_> = schemata
958 .scan_to_stream(Default::default())
959 .await
960 .unwrap()
961 .try_collect()
962 .await
963 .unwrap();
964 let mut rows = Vec::new();
965 for batch in &batches {
966 let names = batch.column_by_name("schema_name").unwrap();
967 let options = batch.column_by_name("options").unwrap();
968 for row in 0..batch.num_rows() {
969 rows.push((
970 string_array_value_at_index(names, row),
971 string_array_value_at_index(options, row),
972 ));
973 }
974 }
975 rows.sort_unstable();
976 assert_eq!(
977 rows,
978 [
979 (Some(INFORMATION_SCHEMA_NAME), Some("")),
980 (Some("user_schema"), Some("'ttl'='9s'\n'region'='east'\n")),
981 ]
982 );
983 }
984
985 #[tokio::test]
986 async fn test_tables_reuse_batch_loaded_metadata() {
987 use std::collections::HashMap;
988 use std::sync::Mutex;
989
990 use common_meta::key::table_info::TableInfoKey;
991 use common_meta::key::table_name::TableNameValue;
992 use common_meta::key::{MetadataKey, MetadataValue};
993 use common_meta::kv_backend::test_util::MockKvBackendBuilder;
994 use common_meta::rpc::KeyValue;
995 use common_meta::rpc::store::{BatchGetResponse, RangeResponse};
996
997 let mut names = Vec::new();
998 let mut infos = HashMap::new();
999 for id in [1024, 1025] {
1000 let name = format!("table_{id}");
1001 names.push(KeyValue {
1002 key: TableNameKey::new(DEFAULT_CATALOG_NAME, "scan_test", &name).to_bytes(),
1003 value: TableNameValue::new(id).try_as_raw_value().unwrap(),
1004 });
1005 let info = test_create_table_task(&name, id).table_info;
1006 infos.insert(
1007 TableInfoKey::new(id).to_bytes(),
1008 TableInfoValue::new(info).try_as_raw_value().unwrap(),
1009 );
1010 }
1011 let reads = Arc::new(Mutex::new(Vec::new()));
1012 let observed = reads.clone();
1013 let backend = MockKvBackendBuilder::default()
1014 .range_fn(Arc::new(move |_| {
1015 Ok(RangeResponse {
1016 kvs: names.clone(),
1017 more: false,
1018 })
1019 }))
1020 .batch_get_fn(Arc::new(move |req| {
1021 let mut keys = req.keys;
1022 keys.sort();
1023 observed.lock().unwrap().push(keys.clone());
1024 Ok(BatchGetResponse {
1025 kvs: keys
1026 .into_iter()
1027 .map(|key| KeyValue {
1028 value: infos[&key].clone(),
1029 key,
1030 })
1031 .collect(),
1032 })
1033 }))
1034 .max_txn_ops(128)
1035 .build()
1036 .unwrap();
1037 let backend = Arc::new(backend);
1038 let registry = cache::build_datanode_layered_cache_registry(backend.clone());
1039 let manager = batch_lookup_manager(backend, Arc::new(registry));
1040 let ids = [1024, 1025];
1041 let keys = ids.map(|id| TableInfoKey::new(id).to_bytes()).to_vec();
1042 for _ in 0..3 {
1043 let baseline = manager
1044 .table_metadata_manager
1045 .table_info_manager()
1046 .batch_get(&ids)
1047 .await
1048 .unwrap();
1049 assert_eq!(baseline.len(), ids.len());
1050 }
1051 assert_eq!(
1052 std::mem::take(&mut *reads.lock().unwrap()),
1053 vec![keys.clone(); 3]
1054 );
1055 for _ in 0..3 {
1056 let ids_read: Vec<_> = manager
1057 .tables(DEFAULT_CATALOG_NAME, "scan_test", None)
1058 .map_ok(|table| table.table_info().table_id())
1059 .try_collect()
1060 .await
1061 .unwrap();
1062 assert_eq!(ids_read, ids);
1063 }
1064 assert_eq!(*reads.lock().unwrap(), vec![keys]);
1065 }
1066
1067 #[tokio::test]
1068 async fn test_views_scan_yields_incremental_batches() {
1069 let backend = Arc::new(MemoryKvBackend::default());
1070 let registry = cache::with_default_composite_cache_registry(
1071 LayeredCacheRegistryBuilder::default()
1072 .add_cache_registry(cache::build_fundamental_cache_registry(backend.clone())),
1073 )
1074 .unwrap()
1075 .build();
1076 let manager = batch_lookup_manager(backend, Arc::new(registry));
1077 let views = manager
1078 .table(DEFAULT_CATALOG_NAME, INFORMATION_SCHEMA_NAME, "views", None)
1079 .await
1080 .unwrap()
1081 .unwrap();
1082 let empty: Vec<_> = views
1083 .scan_to_stream(Default::default())
1084 .await
1085 .unwrap()
1086 .try_collect()
1087 .await
1088 .unwrap();
1089 assert_eq!(empty.len(), 1);
1090 assert_eq!(empty[0].num_rows(), 0);
1091 manager
1092 .table_metadata_manager
1093 .schema_manager()
1094 .create(
1095 SchemaNameKey::new(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME),
1096 None,
1097 true,
1098 )
1099 .await
1100 .unwrap();
1101 for id in 1024..1153 {
1102 let name = format!("view_{id}");
1103 let mut info = test_create_table_task(&name, id).table_info;
1104 info.catalog_name = DEFAULT_CATALOG_NAME.into();
1105 info.schema_name = DEFAULT_SCHEMA_NAME.into();
1106 info.table_type = table::metadata::TableType::View;
1107 manager
1108 .table_metadata_manager
1109 .create_view_metadata(
1110 info,
1111 vec![],
1112 Default::default(),
1113 vec![],
1114 vec![],
1115 format!("SELECT {id}"),
1116 )
1117 .await
1118 .unwrap();
1119 }
1120 let batches: Vec<_> = views
1121 .scan_to_stream(Default::default())
1122 .await
1123 .unwrap()
1124 .try_collect()
1125 .await
1126 .unwrap();
1127 assert!(batches.len() > 1);
1128 assert_eq!(
1129 batches.iter().map(|batch| batch.num_rows()).sum::<usize>(),
1130 129
1131 );
1132 let cache = manager.view_info_cache().unwrap();
1133 assert!(cache.contains_key(&1024));
1134 assert!(cache.contains_key(&1152));
1135 }
1136
1137 fn metric_table_info(
1138 table_id: TableId,
1139 table_name: &str,
1140 partition_key_indices: Vec<usize>,
1141 ) -> TableInfo {
1142 let mut table_info = test_create_table_task(table_name, table_id).table_info;
1143 table_info.meta.engine = METRIC_ENGINE_NAME.to_string();
1144 table_info.meta.partition_key_indices = partition_key_indices;
1145 table_info
1146 }
1147
1148 #[tokio::test]
1149 async fn test_logical_table_uses_cached_physical_table_info() {
1150 const LOGICAL_TABLE_ID: TableId = 1;
1151 const PHYSICAL_TABLE_ID: TableId = 2;
1152
1153 let route = Arc::new(TableRoute::Logical(Arc::new(LogicalTableRouteValue::new(
1154 PHYSICAL_TABLE_ID,
1155 ))));
1156 let route_initializer: Initializer<TableId, Arc<TableRoute>> = Arc::new(move |_| {
1157 let route = route.clone();
1158 Box::pin(async move { Ok(Some(route)) })
1159 });
1160 let table_route_cache = Arc::new(CacheContainer::new(
1161 "test_table_route_cache".to_string(),
1162 FutureCache::new(16),
1163 route_initializer,
1164 CacheIdent::table_id_key,
1165 ));
1166
1167 let load_count = Arc::new(AtomicUsize::new(0));
1168 let physical_table_info =
1169 Arc::new(metric_table_info(PHYSICAL_TABLE_ID, "physical", vec![1]));
1170 let table_info_initializer: Initializer<TableId, Arc<TableInfo>> = {
1171 let load_count = load_count.clone();
1172 let table_info = physical_table_info.clone();
1173 Arc::new(move |_| {
1174 load_count.fetch_add(1, Ordering::Relaxed);
1175 let table_info = table_info.clone();
1176 Box::pin(async move { Ok(Some(table_info)) })
1177 })
1178 };
1179 let table_info_cache = Arc::new(CacheContainer::new(
1180 "test_table_info_cache".to_string(),
1181 FutureCache::new(16),
1182 table_info_initializer,
1183 CacheIdent::table_id_key,
1184 ));
1185
1186 let logical_table = DistTable::table(Arc::new(metric_table_info(
1187 LOGICAL_TABLE_ID,
1188 "logical",
1189 vec![],
1190 )));
1191 for _ in 0..2 {
1192 let table = KvBackendCatalogManager::override_logical_table_partition_key_indices(
1193 &table_route_cache,
1194 &table_info_cache,
1195 logical_table.clone(),
1196 )
1197 .await
1198 .unwrap();
1199 assert_eq!(table.table_info().meta.partition_key_indices, vec![1]);
1200 }
1201 assert_eq!(load_count.load(Ordering::Relaxed), 1);
1202 }
1203}