Skip to main content

catalog/
lib.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 std::any::Any;
16use std::fmt::{Debug, Formatter};
17use std::sync::Arc;
18
19use api::v1::CreateTableExpr;
20use common_catalog::consts::system_schema_name;
21use futures::future::BoxFuture;
22use futures_util::stream::BoxStream;
23use session::context::QueryContext;
24use table::TableRef;
25use table::metadata::{TableId, TableInfoRef};
26use table::table_name::TableName;
27
28use crate::error::Result;
29
30mod batch_scan;
31pub mod error;
32pub mod information_extension;
33pub mod kvbackend;
34#[cfg(any(test, feature = "testing"))]
35pub mod memory;
36mod metrics;
37pub mod system_schema;
38pub mod information_schema {
39    // TODO(j0hn50n133): re-export to make it compatible with the legacy code, migrate to the new path later
40    pub use crate::system_schema::information_schema::*;
41}
42
43pub mod process_manager;
44pub mod table_source;
45
46#[async_trait::async_trait]
47pub trait CatalogManager: Send + Sync {
48    fn as_any(&self) -> &dyn Any;
49
50    async fn catalog_names(&self) -> Result<Vec<String>>;
51
52    async fn schema_names(
53        &self,
54        catalog: &str,
55        query_ctx: Option<&QueryContext>,
56    ) -> Result<Vec<String>>;
57
58    async fn table_names(
59        &self,
60        catalog: &str,
61        schema: &str,
62        query_ctx: Option<&QueryContext>,
63    ) -> Result<Vec<String>>;
64
65    async fn catalog_exists(&self, catalog: &str) -> Result<bool>;
66
67    async fn schema_exists(
68        &self,
69        catalog: &str,
70        schema: &str,
71        query_ctx: Option<&QueryContext>,
72    ) -> Result<bool>;
73
74    async fn table_exists(
75        &self,
76        catalog: &str,
77        schema: &str,
78        table: &str,
79        query_ctx: Option<&QueryContext>,
80    ) -> Result<bool>;
81
82    /// Returns the table by catalog, schema and table name.
83    async fn table(
84        &self,
85        catalog: &str,
86        schema: &str,
87        table_name: &str,
88        query_ctx: Option<&QueryContext>,
89    ) -> Result<Option<TableRef>>;
90
91    /// Returns the table id of provided table ident.
92    async fn table_id(
93        &self,
94        catalog: &str,
95        schema: &str,
96        table_name: &str,
97        query_ctx: Option<&QueryContext>,
98    ) -> Result<Option<TableId>> {
99        Ok(self
100            .table(catalog, schema, table_name, query_ctx)
101            .await?
102            .map(|t| t.table_info().ident.table_id))
103    }
104
105    /// Returns one ID per input name in order, preserving duplicates and returning
106    /// `None` for missing names. Names are resolved in the supplied catalog and
107    /// schema without a query context or an implicit PostgreSQL catalog lookup.
108    async fn table_ids(&self, names: &[TableName]) -> Result<Vec<Option<TableId>>> {
109        let mut result = Vec::with_capacity(names.len());
110        for name in names {
111            result.push(
112                self.table_id(
113                    &name.catalog_name,
114                    &name.schema_name,
115                    &name.table_name,
116                    None,
117                )
118                .await?,
119            );
120        }
121        Ok(result)
122    }
123
124    /// Returns one metadata entry per input ID in order, preserving duplicates
125    /// and returning `None` for missing tables.
126    async fn table_infos_by_ids(&self, ids: &[TableId]) -> Result<Vec<Option<TableInfoRef>>> {
127        let mut result = Vec::with_capacity(ids.len());
128        for &id in ids {
129            result.push(self.table_info_by_id(id).await?);
130        }
131        Ok(result)
132    }
133
134    /// Returns the table of provided id.
135    async fn table_info_by_id(&self, table_id: TableId) -> Result<Option<TableInfoRef>>;
136
137    /// Returns the tables by table ids.
138    async fn tables_by_ids(
139        &self,
140        catalog: &str,
141        schema: &str,
142        table_ids: &[TableId],
143    ) -> Result<Vec<TableRef>>;
144
145    /// Returns all tables with a stream by catalog and schema.
146    fn tables<'a>(
147        &'a self,
148        catalog: &'a str,
149        schema: &'a str,
150        query_ctx: Option<&'a QueryContext>,
151    ) -> BoxStream<'a, Result<TableRef>>;
152
153    /// Check if `schema` is a reserved schema name
154    fn is_reserved_schema_name(&self, schema: &str) -> bool {
155        // We have to check whether a schema name is reserved before create schema.
156        // We need this rather than use schema_exists directly because `pg_catalog` is
157        // only visible via postgres protocol. So if we don't check, a mysql client may
158        // create a schema named `pg_catalog` which is somehow malformed.
159        //
160        // Case-insensitive, otherwise `CREATE DATABASE "INFORMATION_SCHEMA"` keeps its
161        // case and creates a schema shadowed by the system one.
162        system_schema_name(schema).is_some()
163    }
164}
165
166pub type CatalogManagerRef = Arc<dyn CatalogManager>;
167
168/// Hook called after system table opening.
169pub type OpenSystemTableHook =
170    Box<dyn Fn(TableRef) -> BoxFuture<'static, Result<()>> + Send + Sync>;
171
172/// Register system table request:
173/// - When system table is already created and registered, the hook will be called
174///     with table ref after opening the system table
175/// - When system table is not exists, create and register the table by `create_table_expr` and calls `open_hook` with the created table.
176pub struct RegisterSystemTableRequest {
177    pub create_table_expr: CreateTableExpr,
178    pub open_hook: Option<OpenSystemTableHook>,
179}
180
181#[derive(Clone)]
182pub struct RegisterTableRequest {
183    pub catalog: String,
184    pub schema: String,
185    pub table_name: String,
186    pub table_id: TableId,
187    pub table: TableRef,
188}
189
190impl Debug for RegisterTableRequest {
191    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
192        f.debug_struct("RegisterTableRequest")
193            .field("catalog", &self.catalog)
194            .field("schema", &self.schema)
195            .field("table_name", &self.table_name)
196            .field("table_id", &self.table_id)
197            .field("table", &self.table.table_info())
198            .finish()
199    }
200}
201
202#[derive(Debug, Clone)]
203pub struct RenameTableRequest {
204    pub catalog: String,
205    pub schema: String,
206    pub table_name: String,
207    pub new_table_name: String,
208    pub table_id: TableId,
209}
210
211#[derive(Debug, Clone)]
212pub struct DeregisterTableRequest {
213    pub catalog: String,
214    pub schema: String,
215    pub table_name: String,
216}
217
218#[derive(Debug, Clone)]
219pub struct DeregisterSchemaRequest {
220    pub catalog: String,
221    pub schema: String,
222}
223
224#[derive(Debug, Clone)]
225pub struct RegisterSchemaRequest {
226    pub catalog: String,
227    pub schema: String,
228}