Skip to main content

catalog/system_schema/information_schema/
partitions.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
15use core::pin::pin;
16use std::sync::{Arc, Weak};
17
18use arrow_schema::SchemaRef as ArrowSchemaRef;
19use common_catalog::consts::INFORMATION_SCHEMA_PARTITIONS_TABLE_ID;
20use common_error::ext::BoxedError;
21use common_recordbatch::adapter::RecordBatchStreamAdapter;
22use common_recordbatch::{RecordBatch, SendableRecordBatchStream};
23use datafusion::execution::TaskContext;
24use datafusion::physical_plan::SendableRecordBatchStream as DfSendableRecordBatchStream;
25use datafusion::physical_plan::stream::RecordBatchStreamAdapter as DfRecordBatchStreamAdapter;
26use datafusion::physical_plan::streaming::PartitionStream as DfPartitionStream;
27use datatypes::prelude::{ConcreteDataType, ScalarVectorBuilder, VectorRef};
28use datatypes::schema::{ColumnSchema, Schema, SchemaRef};
29use datatypes::timestamp::TimestampSecond;
30use datatypes::value::Value;
31use datatypes::vectors::{
32    Int64Vector, Int64VectorBuilder, MutableVector, StringVector, StringVectorBuilder,
33    TimestampSecondVector, TimestampSecondVectorBuilder, UInt64VectorBuilder,
34};
35use futures::TryStreamExt;
36use partition::manager::PartitionInfo;
37use snafu::{OptionExt, ResultExt};
38use store_api::storage::{ScanRequest, TableId};
39use table::metadata::{TableInfo, TableType};
40
41use crate::CatalogManager;
42use crate::error::{
43    CreateRecordBatchSnafu, FindPartitionsSnafu, InternalSnafu, PartitionManagerNotFoundSnafu,
44    Result, UpgradeWeakCatalogManagerRefSnafu,
45};
46use crate::kvbackend::KvBackendCatalogManager;
47use crate::system_schema::SystemTable;
48use crate::system_schema::information_schema::{
49    InformationSchemaTableScope, InformationTable, PARTITIONS, Predicates,
50};
51
52const TABLE_CATALOG: &str = "table_catalog";
53const TABLE_SCHEMA: &str = "table_schema";
54const TABLE_NAME: &str = "table_name";
55const PARTITION_NAME: &str = "partition_name";
56const PARTITION_EXPRESSION: &str = "partition_expression";
57/// The region id
58const GREPTIME_PARTITION_ID: &str = "greptime_partition_id";
59const INIT_CAPACITY: usize = 42;
60
61/// The `PARTITIONS` table provides information about partitioned tables.
62/// See https://dev.mysql.com/doc/refman/8.0/en/information-schema-partitions-table.html
63/// We provide an extral column `greptime_partition_id` for GreptimeDB region id.
64#[derive(Debug)]
65pub(super) struct InformationSchemaPartitions {
66    schema: SchemaRef,
67    catalog_name: String,
68    catalog_manager: Weak<dyn CatalogManager>,
69}
70
71impl InformationSchemaPartitions {
72    pub(super) fn new(catalog_name: String, catalog_manager: Weak<dyn CatalogManager>) -> Self {
73        Self {
74            schema: Self::schema(),
75            catalog_name,
76            catalog_manager,
77        }
78    }
79
80    pub(crate) fn schema() -> SchemaRef {
81        Arc::new(Schema::new(vec![
82            ColumnSchema::new(TABLE_CATALOG, ConcreteDataType::string_datatype(), false),
83            ColumnSchema::new(TABLE_SCHEMA, ConcreteDataType::string_datatype(), false),
84            ColumnSchema::new(TABLE_NAME, ConcreteDataType::string_datatype(), false),
85            ColumnSchema::new(PARTITION_NAME, ConcreteDataType::string_datatype(), false),
86            ColumnSchema::new(
87                "subpartition_name",
88                ConcreteDataType::string_datatype(),
89                true,
90            ),
91            ColumnSchema::new(
92                "partition_ordinal_position",
93                ConcreteDataType::int64_datatype(),
94                true,
95            ),
96            ColumnSchema::new(
97                "subpartition_ordinal_position",
98                ConcreteDataType::int64_datatype(),
99                true,
100            ),
101            ColumnSchema::new(
102                "partition_method",
103                ConcreteDataType::string_datatype(),
104                true,
105            ),
106            ColumnSchema::new(
107                "subpartition_method",
108                ConcreteDataType::string_datatype(),
109                true,
110            ),
111            ColumnSchema::new(
112                PARTITION_EXPRESSION,
113                ConcreteDataType::string_datatype(),
114                true,
115            ),
116            ColumnSchema::new(
117                "subpartition_expression",
118                ConcreteDataType::string_datatype(),
119                true,
120            ),
121            ColumnSchema::new(
122                "partition_description",
123                ConcreteDataType::string_datatype(),
124                true,
125            ),
126            ColumnSchema::new("table_rows", ConcreteDataType::int64_datatype(), true),
127            ColumnSchema::new("avg_row_length", ConcreteDataType::int64_datatype(), true),
128            ColumnSchema::new("data_length", ConcreteDataType::int64_datatype(), true),
129            ColumnSchema::new("max_data_length", ConcreteDataType::int64_datatype(), true),
130            ColumnSchema::new("index_length", ConcreteDataType::int64_datatype(), true),
131            ColumnSchema::new("data_free", ConcreteDataType::int64_datatype(), true),
132            ColumnSchema::new(
133                "create_time",
134                ConcreteDataType::timestamp_second_datatype(),
135                true,
136            ),
137            ColumnSchema::new(
138                "update_time",
139                ConcreteDataType::timestamp_second_datatype(),
140                true,
141            ),
142            ColumnSchema::new(
143                "check_time",
144                ConcreteDataType::timestamp_second_datatype(),
145                true,
146            ),
147            ColumnSchema::new("checksum", ConcreteDataType::int64_datatype(), true),
148            ColumnSchema::new(
149                "partition_comment",
150                ConcreteDataType::string_datatype(),
151                true,
152            ),
153            ColumnSchema::new("nodegroup", ConcreteDataType::string_datatype(), true),
154            ColumnSchema::new("tablespace_name", ConcreteDataType::string_datatype(), true),
155            ColumnSchema::new(
156                GREPTIME_PARTITION_ID,
157                ConcreteDataType::uint64_datatype(),
158                true,
159            ),
160        ]))
161    }
162
163    fn builder(&self) -> InformationSchemaPartitionsBuilder {
164        InformationSchemaPartitionsBuilder::new(
165            self.schema.clone(),
166            self.catalog_name.clone(),
167            self.catalog_manager.clone(),
168        )
169    }
170}
171
172impl InformationTable for InformationSchemaPartitions {
173    fn scope(&self) -> InformationSchemaTableScope {
174        InformationSchemaTableScope::Catalog
175    }
176}
177
178impl SystemTable for InformationSchemaPartitions {
179    fn table_id(&self) -> TableId {
180        INFORMATION_SCHEMA_PARTITIONS_TABLE_ID
181    }
182
183    fn table_name(&self) -> &'static str {
184        PARTITIONS
185    }
186
187    fn schema(&self) -> SchemaRef {
188        self.schema.clone()
189    }
190
191    fn to_stream(&self, request: ScanRequest) -> Result<SendableRecordBatchStream> {
192        let schema = self.schema.arrow_schema().clone();
193        let mut builder = self.builder();
194        let stream = Box::pin(DfRecordBatchStreamAdapter::new(
195            schema,
196            futures::stream::once(async move {
197                builder
198                    .make_partitions(Some(request))
199                    .await
200                    .map(|x| x.into_df_record_batch())
201                    .map_err(Into::into)
202            }),
203        ));
204        Ok(Box::pin(
205            RecordBatchStreamAdapter::try_new(stream)
206                .map_err(BoxedError::new)
207                .context(InternalSnafu)?,
208        ))
209    }
210}
211
212struct InformationSchemaPartitionsBuilder {
213    schema: SchemaRef,
214    catalog_name: String,
215    catalog_manager: Weak<dyn CatalogManager>,
216
217    catalog_names: StringVectorBuilder,
218    schema_names: StringVectorBuilder,
219    table_names: StringVectorBuilder,
220    partition_names: StringVectorBuilder,
221    partition_ordinal_positions: Int64VectorBuilder,
222    partition_expressions: StringVectorBuilder,
223    partition_descriptions: StringVectorBuilder,
224    create_times: TimestampSecondVectorBuilder,
225    partition_ids: UInt64VectorBuilder,
226}
227
228impl InformationSchemaPartitionsBuilder {
229    fn new(
230        schema: SchemaRef,
231        catalog_name: String,
232        catalog_manager: Weak<dyn CatalogManager>,
233    ) -> Self {
234        Self {
235            schema,
236            catalog_name,
237            catalog_manager,
238            catalog_names: StringVectorBuilder::with_capacity(INIT_CAPACITY),
239            schema_names: StringVectorBuilder::with_capacity(INIT_CAPACITY),
240            table_names: StringVectorBuilder::with_capacity(INIT_CAPACITY),
241            partition_names: StringVectorBuilder::with_capacity(INIT_CAPACITY),
242            partition_ordinal_positions: Int64VectorBuilder::with_capacity(INIT_CAPACITY),
243            partition_expressions: StringVectorBuilder::with_capacity(INIT_CAPACITY),
244            partition_descriptions: StringVectorBuilder::with_capacity(INIT_CAPACITY),
245            create_times: TimestampSecondVectorBuilder::with_capacity(INIT_CAPACITY),
246            partition_ids: UInt64VectorBuilder::with_capacity(INIT_CAPACITY),
247        }
248    }
249
250    /// Construct the `information_schema.partitions` virtual table
251    async fn make_partitions(&mut self, request: Option<ScanRequest>) -> Result<RecordBatch> {
252        let catalog_name = self.catalog_name.clone();
253        let catalog_manager = self
254            .catalog_manager
255            .upgrade()
256            .context(UpgradeWeakCatalogManagerRefSnafu)?;
257
258        let catalog_manager = catalog_manager
259            .as_any()
260            .downcast_ref::<KvBackendCatalogManager>()
261            .context(PartitionManagerNotFoundSnafu)?;
262        let partition_manager = catalog_manager.partition_manager();
263
264        let predicates = Predicates::from_scan_request(&request);
265
266        // Fast path: when the predicates pin both the schema and the table name
267        // with equality, resolve the table directly instead of enumerating all
268        // tables in all schemas and fetching partition metadata for each of them.
269        if let (Some(schema_name), Some(table_name)) = (
270            predicates
271                .find_eq_value(TABLE_SCHEMA)
272                .and_then(Value::as_string),
273            predicates
274                .find_eq_value(TABLE_NAME)
275                .and_then(Value::as_string),
276        ) {
277            if let Some(table) = catalog_manager
278                .table(&catalog_name, &schema_name, &table_name, None)
279                .await?
280            {
281                let table_info = table.table_info();
282
283                // The enumeration path below skips temporary tables, keep the
284                // behavior identical.
285                if table_info.table_type != TableType::Temporary {
286                    let mut table_partitions = partition_manager
287                        .batch_find_table_partitions(&[table_info.table_id()])
288                        .await
289                        .context(FindPartitionsSnafu)?;
290
291                    let partitions = table_partitions
292                        .remove(&table_info.table_id())
293                        .unwrap_or_default();
294
295                    self.add_partitions(
296                        &predicates,
297                        &table_info,
298                        &catalog_name,
299                        &schema_name,
300                        &table_info.name,
301                        &partitions,
302                    );
303                }
304            }
305
306            // The pinned table fully determines the result: the table above was
307            // found (or not) unambiguously, so no other table can contribute rows.
308            return self.finish();
309        }
310
311        for schema_name in catalog_manager.schema_names(&catalog_name, None).await? {
312            // A prefetched table batch can own a physical route needed to resolve the
313            // current batch. Finish its partition lookups before polling the next batch.
314            let batches = catalog_manager.sequential_table_batches(&catalog_name, &schema_name);
315            let mut batches = pin!(batches);
316            while let Some(tables) = batches.try_next().await? {
317                let table_infos: Vec<_> = tables
318                    .map(|table| table.table_info())
319                    .filter(|info| info.table_type != TableType::Temporary)
320                    .collect();
321                if table_infos.is_empty() {
322                    continue;
323                }
324                let table_ids: Vec<TableId> =
325                    table_infos.iter().map(|info| info.ident.table_id).collect();
326
327                let mut table_partitions = partition_manager
328                    .batch_find_table_partitions(&table_ids)
329                    .await
330                    .context(FindPartitionsSnafu)?;
331
332                for table_info in table_infos {
333                    let partitions = table_partitions
334                        .remove(&table_info.ident.table_id)
335                        .unwrap_or(vec![]);
336
337                    self.add_partitions(
338                        &predicates,
339                        &table_info,
340                        &catalog_name,
341                        &schema_name,
342                        &table_info.name,
343                        &partitions,
344                    );
345                }
346            }
347        }
348
349        self.finish()
350    }
351
352    #[allow(clippy::too_many_arguments)]
353    fn add_partitions(
354        &mut self,
355        predicates: &Predicates,
356        table_info: &TableInfo,
357        catalog_name: &str,
358        schema_name: &str,
359        table_name: &str,
360        partitions: &[PartitionInfo],
361    ) {
362        let row = [
363            (TABLE_CATALOG, &Value::from(catalog_name)),
364            (TABLE_SCHEMA, &Value::from(schema_name)),
365            (TABLE_NAME, &Value::from(table_name)),
366        ];
367
368        if !predicates.eval(&row) {
369            return;
370        }
371
372        // Get partition column names (shared by all partitions)
373        // In MySQL, PARTITION_EXPRESSION is the partitioning function expression (e.g., column name)
374        let partition_columns: String = table_info
375            .meta
376            .partition_column_names()
377            .cloned()
378            .collect::<Vec<_>>()
379            .join(", ");
380
381        let partition_expr_str = if partition_columns.is_empty() {
382            None
383        } else {
384            Some(partition_columns)
385        };
386
387        for (index, partition) in partitions.iter().enumerate() {
388            let partition_name = format!("p{index}");
389
390            self.catalog_names.push(Some(catalog_name));
391            self.schema_names.push(Some(schema_name));
392            self.table_names.push(Some(table_name));
393            self.partition_names.push(Some(&partition_name));
394            self.partition_ordinal_positions
395                .push(Some((index + 1) as i64));
396            // PARTITION_EXPRESSION: partition column names (same for all partitions)
397            self.partition_expressions
398                .push(partition_expr_str.as_deref());
399            // PARTITION_DESCRIPTION: partition boundary expression (different for each partition)
400            let description = partition.partition_expr.as_ref().map(|e| e.to_string());
401            self.partition_descriptions.push(description.as_deref());
402            self.create_times.push(Some(TimestampSecond::from(
403                table_info.meta.created_on.timestamp(),
404            )));
405            self.partition_ids.push(Some(partition.id.as_u64()));
406        }
407    }
408
409    fn finish(&mut self) -> Result<RecordBatch> {
410        let rows_num = self.catalog_names.len();
411
412        let null_string_vector = Arc::new(StringVector::from(vec![None as Option<&str>; rows_num]));
413        let null_i64_vector = Arc::new(Int64Vector::from(vec![None; rows_num]));
414        let null_timestamp_second_vector =
415            Arc::new(TimestampSecondVector::from(vec![None; rows_num]));
416        let partition_methods = Arc::new(StringVector::from(vec![Some("RANGE"); rows_num]));
417
418        let columns: Vec<VectorRef> = vec![
419            Arc::new(self.catalog_names.finish()),
420            Arc::new(self.schema_names.finish()),
421            Arc::new(self.table_names.finish()),
422            Arc::new(self.partition_names.finish()),
423            null_string_vector.clone(),
424            Arc::new(self.partition_ordinal_positions.finish()),
425            null_i64_vector.clone(),
426            partition_methods,
427            null_string_vector.clone(),
428            Arc::new(self.partition_expressions.finish()),
429            null_string_vector.clone(),
430            Arc::new(self.partition_descriptions.finish()),
431            // TODO(dennis): rows and index statistics info
432            null_i64_vector.clone(),
433            null_i64_vector.clone(),
434            null_i64_vector.clone(),
435            null_i64_vector.clone(),
436            null_i64_vector.clone(),
437            null_i64_vector.clone(),
438            Arc::new(self.create_times.finish()),
439            // TODO(dennis): supports update_time
440            null_timestamp_second_vector.clone(),
441            null_timestamp_second_vector,
442            null_i64_vector,
443            null_string_vector.clone(),
444            null_string_vector.clone(),
445            null_string_vector,
446            Arc::new(self.partition_ids.finish()),
447        ];
448        RecordBatch::new(self.schema.clone(), columns).context(CreateRecordBatchSnafu)
449    }
450}
451
452impl DfPartitionStream for InformationSchemaPartitions {
453    fn schema(&self) -> &ArrowSchemaRef {
454        self.schema.arrow_schema()
455    }
456
457    fn execute(&self, _: Arc<TaskContext>) -> DfSendableRecordBatchStream {
458        let schema = self.schema.arrow_schema().clone();
459        let mut builder = self.builder();
460        Box::pin(DfRecordBatchStreamAdapter::new(
461            schema,
462            futures::stream::once(async move {
463                builder
464                    .make_partitions(None)
465                    .await
466                    .map(|x| x.into_df_record_batch())
467                    .map_err(Into::into)
468            }),
469        ))
470    }
471}
472
473#[cfg(test)]
474mod tests {
475    use api::v1::meta::Peer;
476    use cache::{build_fundamental_cache_registry, with_default_composite_cache_registry};
477    use common_catalog::consts::{DEFAULT_CATALOG_NAME, INFORMATION_SCHEMA_NAME};
478    use common_meta::cache::{CacheRegistry, CacheRegistryBuilder, LayeredCacheRegistryBuilder};
479    use common_meta::key::schema_name::SchemaNameKey;
480    use common_meta::key::table_route::TableRouteValue;
481    use common_meta::kv_backend::memory::MemoryKvBackend;
482    use common_meta::rpc::router::{Region, RegionRoute};
483    use common_meta::wal_provider::RegionWalOptions;
484    use datafusion::logical_expr::{BinaryExpr, Expr, Operator, col, lit};
485    use futures::TryStreamExt;
486    use store_api::storage::RegionId;
487
488    use super::*;
489    use crate::information_schema::NoopInformationExtension;
490    use crate::kvbackend::KvBackendCatalogManagerBuilder;
491
492    const SCHEMA_1: &str = "partitions_schema_1";
493    const SCHEMA_2: &str = "partitions_schema_2";
494    const PARTITIONED_TABLE: &str = "partitioned_table";
495    const MISSING_TABLE: &str = "missing_table";
496    const TABLE_ID_1: TableId = 1;
497    const TABLE_ID_2: TableId = 2;
498    const REGION_NUMBER_1: u32 = 1;
499    const REGION_NUMBER_2: u32 = 2;
500    const REGION_NUMBER_7: u32 = 7;
501
502    fn kv_catalog_manager(overrides: CacheRegistry) -> Arc<KvBackendCatalogManager> {
503        let backend = Arc::new(MemoryKvBackend::default());
504        let layered_cache_builder =
505            LayeredCacheRegistryBuilder::default().add_cache_registry(overrides);
506        let fundamental_cache_registry = build_fundamental_cache_registry(backend.clone());
507        let layered_cache_registry = Arc::new(
508            with_default_composite_cache_registry(
509                layered_cache_builder.add_cache_registry(fundamental_cache_registry),
510            )
511            .unwrap()
512            .build(),
513        );
514
515        KvBackendCatalogManagerBuilder::new(
516            Arc::new(NoopInformationExtension),
517            backend,
518            layered_cache_registry,
519        )
520        .build()
521    }
522
523    fn region_route(table_id: TableId, region_number: u32) -> RegionRoute {
524        RegionRoute {
525            region: Region {
526                id: RegionId::new(table_id, region_number),
527                ..Default::default()
528            },
529            leader_peer: Some(Peer {
530                id: 1,
531                addr: "127.0.0.1:3001".to_string(),
532            }),
533            ..Default::default()
534        }
535    }
536
537    fn table_info(schema: &str, table: &str, table_id: TableId) -> TableInfo {
538        // The catalog defaults to the default catalog name.
539        let mut table_info =
540            common_meta::key::test_utils::new_test_table_info_with_name(table_id, table);
541        table_info.schema_name = schema.to_string();
542        table_info
543    }
544
545    /// Creates a catalog with two partitioned tables named `PARTITIONED_TABLE`
546    /// in two different schemas:
547    ///
548    /// - `SCHEMA_1.PARTITIONED_TABLE` has two regions.
549    /// - `SCHEMA_2.PARTITIONED_TABLE` has one region.
550    async fn setup_catalog() -> Arc<KvBackendCatalogManager> {
551        let manager = kv_catalog_manager(CacheRegistryBuilder::default().build());
552        let metadata = manager.table_metadata_manager_ref().clone();
553
554        for schema in [SCHEMA_1, SCHEMA_2] {
555            metadata
556                .schema_manager()
557                .create(SchemaNameKey::new(DEFAULT_CATALOG_NAME, schema), None, true)
558                .await
559                .unwrap();
560        }
561
562        for (table_id, schema, region_numbers) in [
563            (TABLE_ID_1, SCHEMA_1, vec![REGION_NUMBER_1, REGION_NUMBER_2]),
564            (TABLE_ID_2, SCHEMA_2, vec![REGION_NUMBER_7]),
565        ] {
566            let routes = region_numbers
567                .into_iter()
568                .map(|region_number| region_route(table_id, region_number))
569                .collect();
570            metadata
571                .create_table_metadata(
572                    table_info(schema, PARTITIONED_TABLE, table_id),
573                    TableRouteValue::physical(routes),
574                    RegionWalOptions::default(),
575                )
576                .await
577                .unwrap();
578        }
579
580        manager
581    }
582
583    /// Scans `information_schema.partitions` and returns the total row count
584    /// and the pretty printed batches.
585    async fn scan_partitions(
586        manager: &Arc<dyn CatalogManager>,
587        filters: Vec<Expr>,
588    ) -> (usize, String) {
589        let table = manager
590            .table(
591                DEFAULT_CATALOG_NAME,
592                INFORMATION_SCHEMA_NAME,
593                PARTITIONS,
594                None,
595            )
596            .await
597            .unwrap()
598            .unwrap();
599        let stream = table
600            .scan_to_stream(ScanRequest {
601                filters,
602                ..Default::default()
603            })
604            .await
605            .unwrap();
606        let batches = stream.try_collect::<Vec<_>>().await.unwrap();
607        let rows = batches.iter().map(|batch| batch.num_rows()).sum();
608        let output = batches
609            .iter()
610            .map(|batch| batch.pretty_print())
611            .collect::<Vec<_>>()
612            .join("\n");
613        (rows, output)
614    }
615
616    fn eq_filter(column: &str, value: &str) -> Expr {
617        Expr::BinaryExpr(BinaryExpr::new(
618            Box::new(col(column)),
619            Operator::Eq,
620            Box::new(lit(value)),
621        ))
622    }
623
624    fn not_eq_filter(column: &str, value: &str) -> Expr {
625        Expr::BinaryExpr(BinaryExpr::new(
626            Box::new(col(column)),
627            Operator::NotEq,
628            Box::new(lit(value)),
629        ))
630    }
631
632    #[tokio::test]
633    async fn test_full_scan_finishes_route_load_for_next_batch() {
634        use std::time::Duration;
635
636        use common_meta::cache::{TableRoute, TableRouteCache};
637        use common_meta::instruction::CacheIdent;
638        use store_api::metric_engine_consts::METRIC_ENGINE_NAME;
639        use tokio::sync::Notify;
640
641        const LOGICAL: TableId = 10_000;
642        const ORDINARY: TableId = LOGICAL + 1;
643        const PHYSICAL: TableId = LOGICAL + 128;
644
645        // Only the partition lookup reads the ordinary table's route. Hold the physical
646        // read until then, so an enumerator that prefetched it must be polled to finish.
647        let gate = Arc::new(Notify::new());
648        let routes = TableRouteCache::new(
649            "test_routes".into(),
650            moka::future::Cache::new(256),
651            Arc::new(move |&id| {
652                let gate = gate.clone();
653                Box::pin(async move {
654                    let value = match id {
655                        LOGICAL => TableRouteValue::logical(PHYSICAL),
656                        ORDINARY => {
657                            gate.notify_one();
658                            TableRouteValue::physical(vec![])
659                        }
660                        PHYSICAL => {
661                            gate.notified().await;
662                            TableRouteValue::physical(vec![region_route(id, REGION_NUMBER_1)])
663                        }
664                        _ => return Ok(None),
665                    };
666                    Ok(Some(Arc::new(TableRoute::from(value))))
667                })
668            }),
669            CacheIdent::table_id_key,
670        );
671        let manager = kv_catalog_manager(
672            CacheRegistryBuilder::default()
673                .add_cache(Arc::new(routes))
674                .build(),
675        );
676        let metadata = manager.table_metadata_manager_ref();
677        metadata
678            .schema_manager()
679            .create(
680                SchemaNameKey::new(DEFAULT_CATALOG_NAME, SCHEMA_1),
681                None,
682                true,
683            )
684            .await
685            .unwrap();
686        // Sorted names place the physical table in batch two. Filtering temporary
687        // tables leaves batch one short, even though its catalog read was full.
688        for id in LOGICAL..=PHYSICAL {
689            let mut info = table_info(SCHEMA_1, &format!("table_{id}"), id);
690            if matches!(id, LOGICAL | PHYSICAL) {
691                info.meta.engine = METRIC_ENGINE_NAME.into();
692            } else if id != ORDINARY {
693                info.table_type = TableType::Temporary;
694            }
695            let route = if id == LOGICAL {
696                TableRouteValue::logical(PHYSICAL)
697            } else {
698                TableRouteValue::physical(vec![])
699            };
700            metadata
701                .create_table_metadata(info, route, Default::default())
702                .await
703                .unwrap();
704        }
705
706        let catalog: Arc<dyn CatalogManager> = manager;
707        let (rows, output) =
708            tokio::time::timeout(Duration::from_secs(5), scan_partitions(&catalog, vec![]))
709                .await
710                .expect(
711                    "partition scan must finish while reading a logical table's physical route",
712                );
713        assert_eq!(rows, 2, "{output}");
714        for id in [LOGICAL, PHYSICAL] {
715            assert!(output.contains(&format!("table_{id}")), "{output}");
716        }
717    }
718
719    #[tokio::test]
720    async fn test_scan_pinned_table_skips_catalog_enumeration() {
721        let manager: Arc<dyn CatalogManager> = setup_catalog().await;
722
723        // No predicates: every partitioned table is listed.
724        let (rows, output) = scan_partitions(&manager, vec![]).await;
725        assert_eq!(3, rows, "{output}");
726
727        // Pins both the schema and the table name, so the scan resolves the
728        // table directly instead of enumerating all catalog entries.
729        let (rows, output) = scan_partitions(
730            &manager,
731            vec![
732                eq_filter(TABLE_SCHEMA, SCHEMA_1),
733                eq_filter(TABLE_NAME, PARTITIONED_TABLE),
734            ],
735        )
736        .await;
737        assert_eq!(2, rows, "{output}");
738        assert!(output.contains(SCHEMA_1), "{output}");
739        assert!(!output.contains(SCHEMA_2), "{output}");
740        assert!(
741            output.contains(
742                &RegionId::new(TABLE_ID_1, REGION_NUMBER_1)
743                    .as_u64()
744                    .to_string()
745            ),
746            "{output}"
747        );
748        assert!(
749            output.contains(
750                &RegionId::new(TABLE_ID_1, REGION_NUMBER_2)
751                    .as_u64()
752                    .to_string()
753            ),
754            "{output}"
755        );
756
757        // The fallback enumeration path must return the identical result. The
758        // inequality on `table_name` doesn't pin a single name, so no direct
759        // lookup happens here.
760        let (fallback_rows, fallback_output) = scan_partitions(
761            &manager,
762            vec![
763                eq_filter(TABLE_SCHEMA, SCHEMA_1),
764                not_eq_filter(TABLE_NAME, MISSING_TABLE),
765            ],
766        )
767        .await;
768        assert_eq!(rows, fallback_rows, "{fallback_output}");
769        assert_eq!(output, fallback_output);
770
771        // Only the table name is pinned: the schema can't be resolved and both
772        // tables of that name are kept.
773        let (rows, output) =
774            scan_partitions(&manager, vec![eq_filter(TABLE_NAME, PARTITIONED_TABLE)]).await;
775        assert_eq!(3, rows, "{output}");
776        assert!(output.contains(SCHEMA_1), "{output}");
777        assert!(output.contains(SCHEMA_2), "{output}");
778
779        // An unknown table in a pinned schema yields no rows.
780        let (rows, output) = scan_partitions(
781            &manager,
782            vec![
783                eq_filter(TABLE_SCHEMA, SCHEMA_1),
784                eq_filter(TABLE_NAME, MISSING_TABLE),
785            ],
786        )
787        .await;
788        assert_eq!(0, rows, "{output}");
789    }
790
791    #[tokio::test]
792    async fn test_scan_equality_under_disjunction_falls_back_to_enumeration() {
793        let manager: Arc<dyn CatalogManager> = setup_catalog().await;
794
795        // `table_schema = SCHEMA_1 OR table_name = PARTITIONED_TABLE` matches
796        // the tables in both schemas: equality nested under a disjunction must
797        // not pin a single table.
798        let filter = Expr::BinaryExpr(BinaryExpr::new(
799            Box::new(eq_filter(TABLE_SCHEMA, SCHEMA_1)),
800            Operator::Or,
801            Box::new(eq_filter(TABLE_NAME, PARTITIONED_TABLE)),
802        ));
803        let (rows, output) = scan_partitions(&manager, vec![filter]).await;
804        assert_eq!(3, rows, "{output}");
805        assert!(output.contains(SCHEMA_1), "{output}");
806        assert!(output.contains(SCHEMA_2), "{output}");
807    }
808}