Skip to main content

catalog/system_schema/information_schema/
schemata.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::sync::{Arc, Weak};
16
17use arrow_schema::SchemaRef as ArrowSchemaRef;
18use common_catalog::consts::INFORMATION_SCHEMA_SCHEMATA_TABLE_ID;
19use common_error::ext::BoxedError;
20use common_recordbatch::adapter::RecordBatchStreamAdapter;
21use common_recordbatch::{RecordBatch, SendableRecordBatchStream};
22use datafusion::execution::TaskContext;
23use datafusion::physical_plan::SendableRecordBatchStream as DfSendableRecordBatchStream;
24use datafusion::physical_plan::stream::RecordBatchStreamAdapter as DfRecordBatchStreamAdapter;
25use datafusion::physical_plan::streaming::PartitionStream as DfPartitionStream;
26use datatypes::prelude::{ConcreteDataType, ScalarVectorBuilder, VectorRef};
27use datatypes::schema::{ColumnSchema, Schema, SchemaRef};
28use datatypes::value::Value;
29use datatypes::vectors::StringVectorBuilder;
30use snafu::{OptionExt, ResultExt};
31use store_api::storage::{ScanRequest, TableId};
32
33use crate::CatalogManager;
34use crate::error::{
35    CreateRecordBatchSnafu, InternalSnafu, Result, UpgradeWeakCatalogManagerRefSnafu,
36};
37use crate::kvbackend::KvBackendCatalogManager;
38use crate::system_schema::SystemTable;
39use crate::system_schema::information_schema::{
40    InformationSchemaTableScope, InformationTable, Predicates, SCHEMATA,
41};
42
43pub const CATALOG_NAME: &str = "catalog_name";
44pub const SCHEMA_NAME: &str = "schema_name";
45const DEFAULT_CHARACTER_SET_NAME: &str = "default_character_set_name";
46const DEFAULT_COLLATION_NAME: &str = "default_collation_name";
47/// The database options
48pub const SCHEMA_OPTS: &str = "options";
49const INIT_CAPACITY: usize = 42;
50
51/// The `information_schema.schemata` table implementation.
52#[derive(Debug)]
53pub(super) struct InformationSchemaSchemata {
54    schema: SchemaRef,
55    catalog_name: String,
56    catalog_manager: Weak<dyn CatalogManager>,
57}
58
59impl InformationSchemaSchemata {
60    pub(super) fn new(catalog_name: String, catalog_manager: Weak<dyn CatalogManager>) -> Self {
61        Self {
62            schema: Self::schema(),
63            catalog_name,
64            catalog_manager,
65        }
66    }
67
68    pub(crate) fn schema() -> SchemaRef {
69        Arc::new(Schema::new(vec![
70            ColumnSchema::new(CATALOG_NAME, ConcreteDataType::string_datatype(), false),
71            ColumnSchema::new(SCHEMA_NAME, ConcreteDataType::string_datatype(), false),
72            ColumnSchema::new(
73                DEFAULT_CHARACTER_SET_NAME,
74                ConcreteDataType::string_datatype(),
75                false,
76            ),
77            ColumnSchema::new(
78                DEFAULT_COLLATION_NAME,
79                ConcreteDataType::string_datatype(),
80                false,
81            ),
82            ColumnSchema::new("sql_path", ConcreteDataType::string_datatype(), true),
83            ColumnSchema::new(SCHEMA_OPTS, ConcreteDataType::string_datatype(), true),
84        ]))
85    }
86
87    fn builder(&self) -> InformationSchemaSchemataBuilder {
88        InformationSchemaSchemataBuilder::new(
89            self.schema.clone(),
90            self.catalog_name.clone(),
91            self.catalog_manager.clone(),
92        )
93    }
94}
95
96impl InformationTable for InformationSchemaSchemata {
97    fn scope(&self) -> InformationSchemaTableScope {
98        InformationSchemaTableScope::Catalog
99    }
100}
101
102impl SystemTable for InformationSchemaSchemata {
103    fn table_id(&self) -> TableId {
104        INFORMATION_SCHEMA_SCHEMATA_TABLE_ID
105    }
106
107    fn table_name(&self) -> &'static str {
108        SCHEMATA
109    }
110
111    fn schema(&self) -> SchemaRef {
112        self.schema.clone()
113    }
114
115    fn to_stream(&self, request: ScanRequest) -> Result<SendableRecordBatchStream> {
116        let schema = self.schema.arrow_schema().clone();
117        let mut builder = self.builder();
118        let stream = Box::pin(DfRecordBatchStreamAdapter::new(
119            schema,
120            futures::stream::once(async move {
121                builder
122                    .make_schemata(Some(request))
123                    .await
124                    .map(|x| x.into_df_record_batch())
125                    .map_err(Into::into)
126            }),
127        ));
128        Ok(Box::pin(
129            RecordBatchStreamAdapter::try_new(stream)
130                .map_err(BoxedError::new)
131                .context(InternalSnafu)?,
132        ))
133    }
134}
135
136/// Builds the `information_schema.schemata` table row by row
137///
138/// Columns are based on <https://docs.pingcap.com/tidb/stable/information-schema-schemata>
139struct InformationSchemaSchemataBuilder {
140    schema: SchemaRef,
141    catalog_name: String,
142    catalog_manager: Weak<dyn CatalogManager>,
143
144    catalog_names: StringVectorBuilder,
145    schema_names: StringVectorBuilder,
146    charset_names: StringVectorBuilder,
147    collation_names: StringVectorBuilder,
148    sql_paths: StringVectorBuilder,
149    schema_options: StringVectorBuilder,
150}
151
152impl InformationSchemaSchemataBuilder {
153    fn new(
154        schema: SchemaRef,
155        catalog_name: String,
156        catalog_manager: Weak<dyn CatalogManager>,
157    ) -> Self {
158        Self {
159            schema,
160            catalog_name,
161            catalog_manager,
162            catalog_names: StringVectorBuilder::with_capacity(INIT_CAPACITY),
163            schema_names: StringVectorBuilder::with_capacity(INIT_CAPACITY),
164            charset_names: StringVectorBuilder::with_capacity(INIT_CAPACITY),
165            collation_names: StringVectorBuilder::with_capacity(INIT_CAPACITY),
166            sql_paths: StringVectorBuilder::with_capacity(INIT_CAPACITY),
167            schema_options: StringVectorBuilder::with_capacity(INIT_CAPACITY),
168        }
169    }
170
171    /// Construct the `information_schema.schemata` virtual table
172    async fn make_schemata(&mut self, request: Option<ScanRequest>) -> Result<RecordBatch> {
173        let catalog_name = self.catalog_name.clone();
174        let catalog_manager = self
175            .catalog_manager
176            .upgrade()
177            .context(UpgradeWeakCatalogManagerRefSnafu)?;
178        let predicates = Predicates::from_scan_request(&request);
179
180        if let Some(manager) = catalog_manager
181            .as_any()
182            .downcast_ref::<KvBackendCatalogManager>()
183        {
184            for (name, options) in manager.schema_options(&catalog_name).await? {
185                self.add_schema(&predicates, &catalog_name, &name, &options);
186            }
187        } else {
188            for name in catalog_manager.schema_names(&catalog_name, None).await? {
189                self.add_schema(&predicates, &catalog_name, &name, "");
190            }
191        }
192
193        self.finish()
194    }
195
196    fn add_schema(
197        &mut self,
198        predicates: &Predicates,
199        catalog_name: &str,
200        schema_name: &str,
201        schema_options: &str,
202    ) {
203        let row = [
204            (CATALOG_NAME, &Value::from(catalog_name)),
205            (SCHEMA_NAME, &Value::from(schema_name)),
206            (DEFAULT_CHARACTER_SET_NAME, &Value::from("utf8")),
207            (DEFAULT_COLLATION_NAME, &Value::from("utf8_bin")),
208            (SCHEMA_OPTS, &Value::from(schema_options)),
209        ];
210
211        if !predicates.eval(&row) {
212            return;
213        }
214
215        self.catalog_names.push(Some(catalog_name));
216        self.schema_names.push(Some(schema_name));
217        self.charset_names.push(Some("utf8"));
218        self.collation_names.push(Some("utf8_bin"));
219        self.sql_paths.push(None);
220        self.schema_options.push(Some(schema_options));
221    }
222
223    fn finish(&mut self) -> Result<RecordBatch> {
224        let columns: Vec<VectorRef> = vec![
225            Arc::new(self.catalog_names.finish()),
226            Arc::new(self.schema_names.finish()),
227            Arc::new(self.charset_names.finish()),
228            Arc::new(self.collation_names.finish()),
229            Arc::new(self.sql_paths.finish()),
230            Arc::new(self.schema_options.finish()),
231        ];
232        RecordBatch::new(self.schema.clone(), columns).context(CreateRecordBatchSnafu)
233    }
234}
235
236impl DfPartitionStream for InformationSchemaSchemata {
237    fn schema(&self) -> &ArrowSchemaRef {
238        self.schema.arrow_schema()
239    }
240
241    fn execute(&self, _: Arc<TaskContext>) -> DfSendableRecordBatchStream {
242        let schema = self.schema.arrow_schema().clone();
243        let mut builder = self.builder();
244        Box::pin(DfRecordBatchStreamAdapter::new(
245            schema,
246            futures::stream::once(async move {
247                builder
248                    .make_schemata(None)
249                    .await
250                    .map(|x| x.into_df_record_batch())
251                    .map_err(Into::into)
252            }),
253        ))
254    }
255}