Skip to main content

catalog/
table_source.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 futures::TryStreamExt;
16use std::collections::HashMap;
17use std::sync::Arc;
18
19use common_catalog::format_full_table_name;
20use common_query::logical_plan::{SubstraitPlanDecoderRef, rename_logical_plan_columns};
21use datafusion::common::{ResolvedTableReference, TableReference};
22use datafusion::datasource::view::ViewTable;
23use datafusion::datasource::{TableProvider, provider_as_source};
24use datafusion::logical_expr::TableSource;
25use itertools::Itertools;
26use session::context::QueryContextRef;
27use snafu::{OptionExt, ResultExt, ensure};
28use table::metadata::TableType;
29use table::table::adapter::DfTableProviderAdapter;
30pub mod dummy_catalog;
31use dummy_catalog::DummyCatalogList;
32use table::TableRef;
33
34use crate::CatalogManagerRef;
35use crate::error::{
36    CastManagerSnafu, DecodePlanSnafu, GetViewCacheSnafu, ProjectViewColumnsSnafu,
37    QueryAccessDeniedSnafu, Result, TableNotExistSnafu, ViewInfoNotFoundSnafu,
38    ViewPlanColumnsChangedSnafu,
39};
40use crate::kvbackend::KvBackendCatalogManager;
41
42pub struct DfTableSourceProvider {
43    catalog_manager: CatalogManagerRef,
44    resolved_tables: HashMap<String, Arc<dyn TableSource>>,
45    disallow_cross_catalog_query: bool,
46    default_catalog: String,
47    default_schema: String,
48    query_ctx: QueryContextRef,
49    plan_decoder: SubstraitPlanDecoderRef,
50    enable_ident_normalization: bool,
51}
52
53impl DfTableSourceProvider {
54    pub fn new(
55        catalog_manager: CatalogManagerRef,
56        disallow_cross_catalog_query: bool,
57        query_ctx: QueryContextRef,
58        plan_decoder: SubstraitPlanDecoderRef,
59        enable_ident_normalization: bool,
60    ) -> Self {
61        Self {
62            catalog_manager,
63            disallow_cross_catalog_query,
64            resolved_tables: HashMap::new(),
65            default_catalog: query_ctx.current_catalog().to_owned(),
66            default_schema: query_ctx.current_schema(),
67            query_ctx,
68            plan_decoder,
69            enable_ident_normalization,
70        }
71    }
72
73    /// Returns the query context.
74    pub fn query_ctx(&self) -> &QueryContextRef {
75        &self.query_ctx
76    }
77
78    /// The logical metric tables of `schema`: the metric engine's own tables, not their physical
79    /// backing. A selector that names no metric is answered by enumerating these.
80    pub async fn logical_metric_tables(&self, schema: &str) -> Result<Vec<TableRef>> {
81        self.catalog_manager
82            .tables(&self.default_catalog, schema, Some(&self.query_ctx))
83            .try_filter(|table| {
84                std::future::ready(
85                    table.table_info().meta.engine == common_catalog::consts::METRIC_ENGINE
86                        && !table.table_info().is_physical_table(),
87                )
88            })
89            .try_collect()
90            .await
91    }
92
93    pub fn resolve_table_ref(&self, table_ref: TableReference) -> Result<ResolvedTableReference> {
94        if self.disallow_cross_catalog_query {
95            match &table_ref {
96                TableReference::Bare { .. } | TableReference::Partial { .. } => {}
97                TableReference::Full {
98                    catalog, schema, ..
99                } => {
100                    ensure!(
101                        catalog.as_ref() == self.default_catalog,
102                        QueryAccessDeniedSnafu {
103                            catalog: catalog.as_ref(),
104                            schema: schema.as_ref(),
105                        }
106                    );
107                }
108            };
109        }
110
111        Ok(table_ref.resolve(&self.default_catalog, &self.default_schema))
112    }
113
114    pub async fn resolve_table(
115        &mut self,
116        table_ref: TableReference,
117    ) -> Result<Arc<dyn TableSource>> {
118        let table_ref = self.resolve_table_ref(table_ref)?;
119
120        let resolved_name = table_ref.to_string();
121        if let Some(table) = self.resolved_tables.get(&resolved_name) {
122            return Ok(table.clone());
123        }
124
125        let catalog_name = table_ref.catalog.as_ref();
126        let schema_name = table_ref.schema.as_ref();
127        let table_name = table_ref.table.as_ref();
128
129        let table = self
130            .catalog_manager
131            .table(catalog_name, schema_name, table_name, Some(&self.query_ctx))
132            .await?
133            .with_context(|| TableNotExistSnafu {
134                table: format_full_table_name(catalog_name, schema_name, table_name),
135            })?;
136
137        let provider: Arc<dyn TableProvider> = if table.table_info().table_type == TableType::View {
138            self.create_view_provider(&table).await?
139        } else {
140            Arc::new(DfTableProviderAdapter::new(table))
141        };
142
143        let source = provider_as_source(provider);
144
145        let _ = self.resolved_tables.insert(resolved_name, source.clone());
146        Ok(source)
147    }
148
149    async fn create_view_provider(&self, table: &TableRef) -> Result<Arc<dyn TableProvider>> {
150        let catalog_manager = self
151            .catalog_manager
152            .as_any()
153            .downcast_ref::<KvBackendCatalogManager>()
154            .context(CastManagerSnafu)?;
155
156        let view_info = catalog_manager
157            .view_info_cache()?
158            .get(table.table_info().ident.table_id)
159            .await
160            .context(GetViewCacheSnafu)?
161            .context(ViewInfoNotFoundSnafu {
162                name: &table.table_info().name,
163            })?;
164
165        // Build the catalog list provider for deserialization.
166        let catalog_list = Arc::new(DummyCatalogList::new(self.catalog_manager.clone()));
167        let logical_plan = self
168            .plan_decoder
169            .decode(view_info.view_info.clone().into(), catalog_list, false)
170            .await
171            .context(DecodePlanSnafu {
172                name: &table.table_info().name,
173            })?;
174
175        let columns: Vec<_> = view_info.columns.iter().map(|c| c.as_str()).collect();
176
177        let original_plan_columns: Vec<_> =
178            view_info.plan_columns.iter().map(|c| c.as_str()).collect();
179
180        let plan_columns: Vec<_> = logical_plan
181            .schema()
182            .columns()
183            .into_iter()
184            .map(|c| c.name)
185            .collect();
186
187        // Only check columns number, because substrait doesn't include aliases currently.
188        // See https://github.com/apache/datafusion/issues/10815#issuecomment-2158666881
189        // and https://github.com/apache/datafusion/issues/6489
190        // TODO(dennis): check column names
191        ensure!(
192            original_plan_columns.len() == plan_columns.len(),
193            ViewPlanColumnsChangedSnafu {
194                origin_names: original_plan_columns.iter().join(","),
195                actual_names: plan_columns.iter().join(","),
196            }
197        );
198
199        // We have to do `columns` projection here, because
200        // substrait doesn't include aliases neither for tables nor for columns:
201        // https://github.com/apache/datafusion/issues/10815#issuecomment-2158666881
202        let logical_plan = if !columns.is_empty() {
203            rename_logical_plan_columns(
204                self.enable_ident_normalization,
205                logical_plan,
206                plan_columns
207                    .iter()
208                    .map(|c| c.as_str())
209                    .zip(columns)
210                    .collect(),
211            )
212            .context(ProjectViewColumnsSnafu)?
213        } else {
214            logical_plan
215        };
216
217        Ok(Arc::new(ViewTable::new(
218            logical_plan,
219            Some(view_info.definition.clone()),
220        )))
221    }
222}
223
224#[cfg(test)]
225mod tests {
226    use common_query::test_util::DummyDecoder;
227    use session::context::QueryContext;
228
229    use super::*;
230    use crate::kvbackend::KvBackendCatalogManagerBuilder;
231    use crate::memory::MemoryCatalogManager;
232
233    #[test]
234    fn test_validate_table_ref() {
235        let query_ctx = Arc::new(QueryContext::with("greptime", "public"));
236
237        let table_provider = DfTableSourceProvider::new(
238            MemoryCatalogManager::with_default_setup(),
239            true,
240            query_ctx.clone(),
241            DummyDecoder::arc(),
242            true,
243        );
244
245        let table_ref = TableReference::bare("table_name");
246        let result = table_provider.resolve_table_ref(table_ref);
247        assert!(result.is_ok());
248
249        let table_ref = TableReference::partial("public", "table_name");
250        let result = table_provider.resolve_table_ref(table_ref);
251        assert!(result.is_ok());
252
253        let table_ref = TableReference::partial("wrong_schema", "table_name");
254        let result = table_provider.resolve_table_ref(table_ref);
255        assert!(result.is_ok());
256
257        let table_ref = TableReference::full("greptime", "public", "table_name");
258        let result = table_provider.resolve_table_ref(table_ref);
259        assert!(result.is_ok());
260
261        let table_ref = TableReference::full("wrong_catalog", "public", "table_name");
262        let result = table_provider.resolve_table_ref(table_ref);
263        assert!(result.is_err());
264
265        let table_ref = TableReference::partial("information_schema", "columns");
266        let result = table_provider.resolve_table_ref(table_ref);
267        assert!(result.is_ok());
268
269        let table_ref = TableReference::full("greptime", "information_schema", "columns");
270        assert!(table_provider.resolve_table_ref(table_ref).is_ok());
271
272        let table_ref = TableReference::full("dummy", "information_schema", "columns");
273        assert!(table_provider.resolve_table_ref(table_ref).is_err());
274
275        let table_ref = TableReference::full("greptime", "greptime_private", "columns");
276        assert!(table_provider.resolve_table_ref(table_ref).is_ok());
277    }
278
279    use std::collections::HashSet;
280
281    use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
282    use cache::{build_fundamental_cache_registry, with_default_composite_cache_registry};
283    use common_meta::cache::{CacheRegistryBuilder, LayeredCacheRegistryBuilder};
284    use common_meta::key::TableMetadataManager;
285    use common_meta::kv_backend::memory::MemoryKvBackend;
286    use common_query::error::Result as QueryResult;
287    use common_query::logical_plan::SubstraitPlanDecoder;
288    use datafusion::catalog::CatalogProviderList;
289    use datafusion::logical_expr::builder::LogicalTableSource;
290    use datafusion::logical_expr::{LogicalPlan, LogicalPlanBuilder, col, lit};
291
292    use crate::information_schema::NoopInformationExtension;
293
294    struct MockDecoder;
295    impl MockDecoder {
296        pub fn arc() -> Arc<Self> {
297            Arc::new(MockDecoder)
298        }
299    }
300
301    #[async_trait::async_trait]
302    impl SubstraitPlanDecoder for MockDecoder {
303        async fn decode(
304            &self,
305            _message: bytes::Bytes,
306            _catalog_list: Arc<dyn CatalogProviderList>,
307            _optimize: bool,
308        ) -> QueryResult<LogicalPlan> {
309            Ok(mock_plan())
310        }
311    }
312
313    fn mock_plan() -> LogicalPlan {
314        let schema = Schema::new(vec![
315            Field::new("id", DataType::Int32, true),
316            Field::new("name", DataType::Utf8, true),
317        ]);
318        let table_source = LogicalTableSource::new(SchemaRef::new(schema));
319
320        let projection = None;
321
322        let builder =
323            LogicalPlanBuilder::scan("person", Arc::new(table_source), projection).unwrap();
324
325        builder
326            .filter(col("id").gt(lit(500)))
327            .unwrap()
328            .build()
329            .unwrap()
330    }
331
332    #[tokio::test]
333    async fn test_resolve_view() {
334        let query_ctx = Arc::new(QueryContext::with("greptime", "public"));
335        let backend = Arc::new(MemoryKvBackend::default());
336        let layered_cache_builder = LayeredCacheRegistryBuilder::default()
337            .add_cache_registry(CacheRegistryBuilder::default().build());
338        let fundamental_cache_registry = build_fundamental_cache_registry(backend.clone());
339        let layered_cache_registry = Arc::new(
340            with_default_composite_cache_registry(
341                layered_cache_builder.add_cache_registry(fundamental_cache_registry),
342            )
343            .unwrap()
344            .build(),
345        );
346
347        let catalog_manager = KvBackendCatalogManagerBuilder::new(
348            Arc::new(NoopInformationExtension),
349            backend.clone(),
350            layered_cache_registry,
351        )
352        .build();
353
354        let table_metadata_manager = TableMetadataManager::new(backend);
355        let mut view_info = common_meta::key::test_utils::new_test_table_info(1024);
356        view_info.table_type = TableType::View;
357        let logical_plan = vec![1, 2, 3];
358        // Create view metadata
359        table_metadata_manager
360            .create_view_metadata(
361                view_info.clone(),
362                logical_plan,
363                HashSet::new(),
364                vec!["a".to_string(), "b".to_string()],
365                vec!["id".to_string(), "name".to_string()],
366                "definition".to_string(),
367            )
368            .await
369            .unwrap();
370
371        let mut table_provider = DfTableSourceProvider::new(
372            catalog_manager,
373            true,
374            query_ctx.clone(),
375            MockDecoder::arc(),
376            true,
377        );
378
379        // View not found
380        let table_ref = TableReference::bare("not_exists_view");
381        assert!(table_provider.resolve_table(table_ref).await.is_err());
382
383        let table_ref = TableReference::bare(view_info.name);
384        let source = table_provider.resolve_table(table_ref).await.unwrap();
385        assert_eq!(
386            r#"
387Projection: person.id AS a, person.name AS b
388  Filter: person.id > Int32(500)
389    TableScan: person"#,
390            format!("\n{}", source.get_logical_plan().unwrap())
391        );
392    }
393}