Skip to main content

catalog/system_schema/information_schema/
views.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_VIEW_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::streaming::PartitionStream as DfPartitionStream;
25use datatypes::prelude::{ConcreteDataType, ScalarVectorBuilder, VectorRef};
26use datatypes::schema::{ColumnSchema, Schema, SchemaRef};
27use datatypes::value::Value;
28use datatypes::vectors::StringVectorBuilder;
29use futures::TryStreamExt;
30use snafu::{OptionExt, ResultExt};
31use store_api::storage::{ScanRequest, TableId};
32use table::metadata::TableType;
33
34use crate::CatalogManager;
35use crate::batch_scan::BatchScanner;
36use crate::error::{
37    CastManagerSnafu, CreateRecordBatchSnafu, InternalSnafu, Result,
38    UpgradeWeakCatalogManagerRefSnafu, ViewInfoNotFoundSnafu,
39};
40use crate::kvbackend::KvBackendCatalogManager;
41use crate::system_schema::SystemTable;
42use crate::system_schema::information_schema::loaders;
43use crate::system_schema::information_schema::{
44    InformationSchemaTableScope, InformationTable, Predicates, VIEWS,
45};
46const INIT_CAPACITY: usize = 42;
47
48pub const TABLE_CATALOG: &str = "table_catalog";
49pub const TABLE_SCHEMA: &str = "table_schema";
50pub const TABLE_NAME: &str = "table_name";
51pub const VIEW_DEFINITION: &str = "view_definition";
52pub const CHECK_OPTION: &str = "check_option";
53pub const IS_UPDATABLE: &str = "is_updatable";
54pub const DEFINER: &str = "definer";
55pub const SECURITY_TYPE: &str = "security_type";
56pub const CHARACTER_SET_CLIENT: &str = "character_set_client";
57pub const COLLATION_CONNECTION: &str = "collation_connection";
58
59/// The `information_schema.views` to provides information about views in databases.
60#[derive(Debug)]
61pub(super) struct InformationSchemaViews {
62    schema: SchemaRef,
63    catalog_name: String,
64    catalog_manager: Weak<dyn CatalogManager>,
65}
66
67impl InformationSchemaViews {
68    pub(super) fn new(catalog_name: String, catalog_manager: Weak<dyn CatalogManager>) -> Self {
69        Self {
70            schema: Self::schema(),
71            catalog_name,
72            catalog_manager,
73        }
74    }
75
76    pub(crate) fn schema() -> SchemaRef {
77        Arc::new(Schema::new(vec![
78            ColumnSchema::new(TABLE_CATALOG, ConcreteDataType::string_datatype(), false),
79            ColumnSchema::new(TABLE_SCHEMA, ConcreteDataType::string_datatype(), false),
80            ColumnSchema::new(TABLE_NAME, ConcreteDataType::string_datatype(), false),
81            ColumnSchema::new(VIEW_DEFINITION, ConcreteDataType::string_datatype(), false),
82            ColumnSchema::new(CHECK_OPTION, ConcreteDataType::string_datatype(), true),
83            ColumnSchema::new(IS_UPDATABLE, ConcreteDataType::string_datatype(), true),
84            ColumnSchema::new(DEFINER, ConcreteDataType::string_datatype(), true),
85            ColumnSchema::new(SECURITY_TYPE, ConcreteDataType::string_datatype(), true),
86            ColumnSchema::new(
87                CHARACTER_SET_CLIENT,
88                ConcreteDataType::string_datatype(),
89                true,
90            ),
91            ColumnSchema::new(
92                COLLATION_CONNECTION,
93                ConcreteDataType::string_datatype(),
94                true,
95            ),
96        ]))
97    }
98
99    fn builder(&self) -> InformationSchemaViewsBuilder {
100        InformationSchemaViewsBuilder::new(
101            self.schema.clone(),
102            self.catalog_name.clone(),
103            self.catalog_manager.clone(),
104        )
105    }
106}
107
108impl InformationTable for InformationSchemaViews {
109    fn scope(&self) -> InformationSchemaTableScope {
110        InformationSchemaTableScope::Catalog
111    }
112}
113
114impl SystemTable for InformationSchemaViews {
115    fn table_id(&self) -> TableId {
116        INFORMATION_SCHEMA_VIEW_TABLE_ID
117    }
118
119    fn table_name(&self) -> &'static str {
120        VIEWS
121    }
122
123    fn schema(&self) -> SchemaRef {
124        self.schema.clone()
125    }
126
127    fn to_stream(&self, request: ScanRequest) -> Result<SendableRecordBatchStream> {
128        let stream = crate::system_schema::utils::record_batch_stream(
129            &self.schema,
130            self.builder().scan(Some(request)),
131        );
132        Ok(Box::pin(
133            RecordBatchStreamAdapter::try_new(stream)
134                .map_err(BoxedError::new)
135                .context(InternalSnafu)?,
136        ))
137    }
138}
139
140/// Builds the `information_schema.VIEWS` table row by row
141///
142/// Columns are based on <https://dev.mysql.com/doc/refman/8.4/en/information-schema-views-table.html>
143struct InformationSchemaViewsBuilder {
144    schema: SchemaRef,
145    catalog_name: String,
146    catalog_manager: Weak<dyn CatalogManager>,
147
148    catalog_names: StringVectorBuilder,
149    schema_names: StringVectorBuilder,
150    table_names: StringVectorBuilder,
151    view_definitions: StringVectorBuilder,
152    check_options: StringVectorBuilder,
153    is_updatable: StringVectorBuilder,
154    definer: StringVectorBuilder,
155    security_type: StringVectorBuilder,
156    character_set_client: StringVectorBuilder,
157    collation_connection: StringVectorBuilder,
158}
159
160impl InformationSchemaViewsBuilder {
161    fn new(
162        schema: SchemaRef,
163        catalog_name: String,
164        catalog_manager: Weak<dyn CatalogManager>,
165    ) -> Self {
166        Self {
167            schema,
168            catalog_name,
169            catalog_manager,
170            catalog_names: StringVectorBuilder::with_capacity(INIT_CAPACITY),
171            schema_names: StringVectorBuilder::with_capacity(INIT_CAPACITY),
172            table_names: StringVectorBuilder::with_capacity(INIT_CAPACITY),
173            view_definitions: StringVectorBuilder::with_capacity(INIT_CAPACITY),
174            check_options: StringVectorBuilder::with_capacity(INIT_CAPACITY),
175            is_updatable: StringVectorBuilder::with_capacity(INIT_CAPACITY),
176            definer: StringVectorBuilder::with_capacity(INIT_CAPACITY),
177            security_type: StringVectorBuilder::with_capacity(INIT_CAPACITY),
178            character_set_client: StringVectorBuilder::with_capacity(INIT_CAPACITY),
179            collation_connection: StringVectorBuilder::with_capacity(INIT_CAPACITY),
180        }
181    }
182
183    /// Construct the `information_schema.views` virtual table
184    fn scan(
185        mut self,
186        request: Option<ScanRequest>,
187    ) -> impl futures::Stream<Item = Result<RecordBatch>> {
188        async_stream::try_stream!({
189            let catalog_name = self.catalog_name.clone();
190            let catalog_manager = self
191                .catalog_manager
192                .upgrade()
193                .context(UpgradeWeakCatalogManagerRefSnafu)?;
194            let predicates = Predicates::from_scan_request(&request);
195            let view_info_cache = catalog_manager
196                .as_any()
197                .downcast_ref::<KvBackendCatalogManager>()
198                .context(CastManagerSnafu)?
199                .view_info_cache()?;
200
201            for schema_name in catalog_manager.schema_names(&catalog_name, None).await? {
202                let views = catalog_manager
203                    .tables(&catalog_name, &schema_name, None)
204                    .try_filter_map(|table| async move {
205                        let info = table.table_info();
206                        Ok((info.table_type == TableType::View).then_some(info))
207                    });
208                let batches = BatchScanner::METADATA.scan(views, |tables| {
209                    loaders::load_view_definitions(&view_info_cache, tables)
210                });
211                let mut batches = std::pin::pin!(batches);
212                while let Some(batch) = batches.try_next().await? {
213                    for (table, definition) in batch {
214                        let view =
215                            definition.context(ViewInfoNotFoundSnafu { name: &table.name })?;
216                        self.add_view(
217                            &predicates,
218                            &catalog_name,
219                            &schema_name,
220                            &table.name,
221                            &view.definition,
222                        );
223                    }
224                    yield self.finish()?;
225                }
226            }
227        })
228    }
229
230    fn add_view(
231        &mut self,
232        predicates: &Predicates,
233        catalog_name: &str,
234        schema_name: &str,
235        table_name: &str,
236        definition: &str,
237    ) {
238        let row = [
239            (TABLE_CATALOG, &Value::from(catalog_name)),
240            (TABLE_SCHEMA, &Value::from(schema_name)),
241            (TABLE_NAME, &Value::from(table_name)),
242        ];
243
244        if !predicates.eval(&row) {
245            return;
246        }
247        self.catalog_names.push(Some(catalog_name));
248        self.schema_names.push(Some(schema_name));
249        self.table_names.push(Some(table_name));
250        self.view_definitions.push(Some(definition));
251        self.check_options.push(None);
252        // View is not updatable, statements such UPDATE , DELETE , and INSERT are illegal and are rejected.
253        self.is_updatable.push(Some("NO"));
254        self.definer.push(None);
255        self.security_type.push(None);
256        self.character_set_client.push(Some("utf8"));
257        self.collation_connection.push(Some("utf8_bin"));
258    }
259
260    fn finish(&mut self) -> Result<RecordBatch> {
261        let columns: Vec<VectorRef> = vec![
262            Arc::new(self.catalog_names.finish()),
263            Arc::new(self.schema_names.finish()),
264            Arc::new(self.table_names.finish()),
265            Arc::new(self.view_definitions.finish()),
266            Arc::new(self.check_options.finish()),
267            Arc::new(self.is_updatable.finish()),
268            Arc::new(self.definer.finish()),
269            Arc::new(self.security_type.finish()),
270            Arc::new(self.character_set_client.finish()),
271            Arc::new(self.collation_connection.finish()),
272        ];
273        RecordBatch::new(self.schema.clone(), columns).context(CreateRecordBatchSnafu)
274    }
275}
276
277impl DfPartitionStream for InformationSchemaViews {
278    fn schema(&self) -> &ArrowSchemaRef {
279        self.schema.arrow_schema()
280    }
281
282    fn execute(&self, _: Arc<TaskContext>) -> DfSendableRecordBatchStream {
283        crate::system_schema::utils::record_batch_stream(&self.schema, self.builder().scan(None))
284    }
285}