Skip to main content

query/
plan.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::collections::{HashMap, HashSet};
16use std::sync::Arc;
17
18use catalog::CatalogManagerRef;
19use datafusion::datasource::{DefaultTableSource, provider_as_source};
20use datafusion_common::TableReference;
21use datafusion_common::tree_node::{Transformed, TreeNodeRecursion, TreeNodeRewriter};
22use datafusion_expr::logical_plan::TableScan;
23use datafusion_expr::{Expr, LogicalPlan};
24use session::context::{QueryContext, QueryContextRef};
25use snafu::ResultExt;
26use table::TableRef;
27use table::dist_table::DistTable;
28pub use table::metadata::TableType;
29use table::table::PartitionRules;
30use table::table::adapter::DfTableProviderAdapter;
31use table::table_name::TableName;
32
33use crate::error::{CatalogSnafu, Result};
34
35struct TableNamesExtractAndRewriter {
36    pub(crate) table_names: HashSet<TableName>,
37    query_ctx: QueryContextRef,
38}
39
40impl TreeNodeRewriter for TableNamesExtractAndRewriter {
41    type Node = LogicalPlan;
42
43    /// descend
44    fn f_down<'a>(
45        &mut self,
46        node: Self::Node,
47    ) -> datafusion::error::Result<Transformed<Self::Node>> {
48        match node {
49            LogicalPlan::TableScan(mut scan) => {
50                if let Some(table) = scanned_base_table(&scan) {
51                    let info = table.table_info();
52                    self.table_names.insert(TableName::new(
53                        info.catalog_name.clone(),
54                        info.schema_name.clone(),
55                        info.name.clone(),
56                    ));
57                }
58                match &scan.table_name {
59                    TableReference::Full {
60                        catalog,
61                        schema,
62                        table,
63                    } => {
64                        self.table_names.insert(TableName::new(
65                            catalog.to_string(),
66                            schema.to_string(),
67                            table.to_string(),
68                        ));
69                    }
70                    TableReference::Partial { schema, table } => {
71                        self.table_names.insert(TableName::new(
72                            self.query_ctx.current_catalog(),
73                            schema.to_string(),
74                            table.to_string(),
75                        ));
76
77                        scan.table_name = TableReference::Full {
78                            catalog: self.query_ctx.current_catalog().into(),
79                            schema: schema.clone(),
80                            table: table.clone(),
81                        };
82                    }
83                    TableReference::Bare { table } => {
84                        self.table_names.insert(TableName::new(
85                            self.query_ctx.current_catalog(),
86                            self.query_ctx.current_schema(),
87                            table.to_string(),
88                        ));
89
90                        scan.table_name = TableReference::Full {
91                            catalog: self.query_ctx.current_catalog().into(),
92                            schema: self.query_ctx.current_schema().into(),
93                            table: table.clone(),
94                        };
95                    }
96                }
97                Ok(Transformed::yes(LogicalPlan::TableScan(scan)))
98            }
99            node => Ok(Transformed::no(node)),
100        }
101    }
102}
103
104impl TableNamesExtractAndRewriter {
105    fn new(query_ctx: QueryContextRef) -> Self {
106        Self {
107            query_ctx,
108            table_names: HashSet::new(),
109        }
110    }
111}
112
113/// Extracts and rewrites the table names in the plan in the fully qualified style,
114/// return the table names and new plan.
115pub fn extract_and_rewrite_full_table_names(
116    plan: LogicalPlan,
117    query_ctx: QueryContextRef,
118) -> Result<(HashSet<TableName>, LogicalPlan)> {
119    let mut extractor = TableNamesExtractAndRewriter::new(query_ctx);
120    let plan = plan.rewrite_with_subqueries(&mut extractor)?;
121    Ok((extractor.table_names, plan.data))
122}
123
124/// Updates the scans in `plan` whose table changed its partition columns after the plan was built.
125///
126/// Distributed planning reads the partition columns from the table a scan holds, and the regions
127/// from the current route. A plan kept across executions, such as a prepared statement's, must
128/// therefore report the current partition columns, or a query that needs merging on the frontend
129/// runs entirely on each region.
130///
131/// Returns `plan` as it is when no scanned table changed its partition columns.
132pub async fn refresh_partition_columns(
133    plan: LogicalPlan,
134    catalog_manager: &CatalogManagerRef,
135    query_ctx: &QueryContext,
136) -> Result<LogicalPlan> {
137    let mut scanned = HashMap::new();
138    plan.apply_with_subqueries(|node| {
139        if let LogicalPlan::TableScan(scan) = node
140            && let Some(table) = scanned_base_table(scan)
141        {
142            scanned.insert(table.table_info().table_id(), table);
143        }
144        Ok(TreeNodeRecursion::Continue)
145    })?;
146
147    let mut refreshed = HashMap::new();
148    for (table_id, table) in scanned {
149        // Looks up by id to follow a rename and to not bind a table that replaced the scanned one.
150        let Some(info) = catalog_manager
151            .table_info_by_id(table_id)
152            .await
153            .context(CatalogSnafu)?
154        else {
155            continue;
156        };
157        let current = catalog_manager
158            .table(
159                &info.catalog_name,
160                &info.schema_name,
161                &info.name,
162                Some(query_ctx),
163            )
164            .await
165            .context(CatalogSnafu)?;
166        let Some(current) = current.filter(|t| t.table_info().table_id() == table_id) else {
167            continue;
168        };
169        if has_same_partition_columns(&table, &current) {
170            continue;
171        }
172        let table = if table.schema() == current.schema() {
173            current
174        } else {
175            with_unmapped_partition_columns(&table, &current)
176        };
177        refreshed.insert(table_id, table);
178    }
179    if refreshed.is_empty() {
180        return Ok(plan);
181    }
182
183    let plan = plan.transform_with_subqueries(|node| {
184        let LogicalPlan::TableScan(mut scan) = node else {
185            return Ok(Transformed::no(node));
186        };
187        let Some(table) = scanned_base_table(&scan)
188            .and_then(|table| refreshed.get(&table.table_info().table_id()))
189        else {
190            return Ok(Transformed::no(LogicalPlan::TableScan(scan)));
191        };
192        scan.source = provider_as_source(Arc::new(DfTableProviderAdapter::new(table.clone())));
193        Ok(Transformed::yes(LogicalPlan::TableScan(scan)))
194    })?;
195    Ok(plan.data)
196}
197
198fn scanned_base_table(scan: &TableScan) -> Option<TableRef> {
199    let source = scan.source.downcast_ref::<DefaultTableSource>()?;
200    let provider = source
201        .table_provider
202        .downcast_ref::<DfTableProviderAdapter>()?;
203    let table = provider.table();
204    (table.table_type() == TableType::Base).then_some(table)
205}
206
207fn has_same_partition_columns(left: &TableRef, right: &TableRef) -> bool {
208    left.table_info()
209        .meta
210        .partition_column_names()
211        .eq(right.table_info().meta.partition_column_names())
212        && extra_partition_columns(left) == extra_partition_columns(right)
213}
214
215fn extra_partition_columns(table: &TableRef) -> &[String] {
216    table
217        .partition_rules()
218        .map(|rules| rules.extra_phy_cols_not_in_logical_table.as_slice())
219        .unwrap_or_default()
220}
221
222/// Builds a table that keeps the schema of `table` and reports the partition columns of `current`
223/// as absent from that schema.
224///
225/// A scan's projection holds indices into the schema it was built on, and Substrait sends that
226/// schema with those indices, so a plan cannot move to a changed schema. Reporting the columns as
227/// absent keeps distributed planning from relying on any of them.
228fn with_unmapped_partition_columns(table: &TableRef, current: &TableRef) -> TableRef {
229    let mut info = (*table.table_info()).clone();
230    info.meta.partition_key_indices.clear();
231    let current_info = current.table_info();
232    let extra_phy_cols_not_in_logical_table = current_info
233        .meta
234        .partition_column_names()
235        .chain(extra_partition_columns(current))
236        .cloned()
237        .collect();
238    DistTable::table_partitioned(
239        Arc::new(info),
240        Some(PartitionRules {
241            extra_phy_cols_not_in_logical_table,
242        }),
243    )
244}
245
246/// A trait to extract expressions from a logical plan.
247pub trait ExtractExpr {
248    /// Gets expressions from a logical plan.
249    /// It handles [Join] specially so [LogicalPlan::with_new_exprs()] can use the expressions
250    /// this method returns.
251    fn expressions_consider_join(&self) -> Vec<Expr>;
252}
253
254impl ExtractExpr for LogicalPlan {
255    fn expressions_consider_join(&self) -> Vec<Expr> {
256        self.expressions()
257    }
258}
259
260#[cfg(test)]
261pub(crate) mod tests {
262
263    use std::sync::Arc;
264
265    use arrow::datatypes::{DataType, Field, Schema, SchemaRef, TimeUnit};
266    use catalog::RegisterTableRequest;
267    use catalog::memory::MemoryCatalogManager;
268    use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
269    use datafusion::logical_expr::builder::LogicalTableSource;
270    use datafusion::logical_expr::{LogicalPlan, LogicalPlanBuilder, col, lit, scalar_subquery};
271    use datatypes::prelude::ConcreteDataType;
272    use datatypes::schema::{ColumnSchema, Schema as TableSchema};
273    use session::context::QueryContextBuilder;
274    use table::test_util::table_info::test_table_info;
275
276    use super::*;
277
278    const TABLE_ID: u32 = 1024;
279
280    fn mock_table_source() -> Arc<LogicalTableSource> {
281        let schema = Schema::new(vec![
282            Field::new("id", DataType::Int32, true),
283            Field::new("name", DataType::Utf8, true),
284            Field::new("ts", DataType::Timestamp(TimeUnit::Millisecond, None), true),
285        ]);
286        Arc::new(LogicalTableSource::new(SchemaRef::new(schema)))
287    }
288
289    fn mock_plan() -> LogicalPlan {
290        let table_source = mock_table_source();
291
292        let projection = None;
293
294        let builder = LogicalPlanBuilder::scan("devices", table_source, projection).unwrap();
295
296        builder
297            .filter(col("id").gt(lit(500)))
298            .unwrap()
299            .build()
300            .unwrap()
301    }
302
303    fn scalar_subquery_plan(table_name: TableReference) -> LogicalPlan {
304        let subquery = LogicalPlanBuilder::scan(table_name, mock_table_source(), None)
305            .unwrap()
306            .project(vec![col("id")])
307            .unwrap()
308            .build()
309            .unwrap();
310
311        LogicalPlanBuilder::empty(false)
312            .project(vec![scalar_subquery(Arc::new(subquery))])
313            .unwrap()
314            .build()
315            .unwrap()
316    }
317
318    fn assert_dependencies(actual: &HashSet<TableName>, expected: &[(&str, &str, &str)]) {
319        let expected = expected
320            .iter()
321            .map(|(catalog, schema, table)| TableName::new(*catalog, *schema, *table))
322            .collect::<HashSet<_>>();
323        assert_eq!(&expected, actual);
324    }
325
326    fn assert_nested_scalar_subquery_table_name(plan: &LogicalPlan, expected: TableReference) {
327        let LogicalPlan::Projection(projection) = plan else {
328            panic!("expected scalar-subquery projection, got {plan:?}");
329        };
330        let [Expr::ScalarSubquery(subquery)] = projection.expr.as_slice() else {
331            panic!(
332                "expected one scalar-subquery expression, got {:?}",
333                projection.expr
334            );
335        };
336        let LogicalPlan::Projection(projection) = subquery.subquery.as_ref() else {
337            panic!(
338                "expected scalar-subquery projection, got {:?}",
339                subquery.subquery
340            );
341        };
342        let LogicalPlan::TableScan(scan) = projection.input.as_ref() else {
343            panic!(
344                "expected scalar-subquery table scan, got {:?}",
345                projection.input
346            );
347        };
348
349        assert_eq!(expected, scan.table_name);
350    }
351
352    #[test]
353    fn test_extract_full_table_names() {
354        let ctx = QueryContextBuilder::default()
355            .current_schema("test".to_string())
356            .build();
357
358        let (table_names, plan) =
359            extract_and_rewrite_full_table_names(mock_plan(), Arc::new(ctx)).unwrap();
360
361        assert_dependencies(&table_names, &[(DEFAULT_CATALOG_NAME, "test", "devices")]);
362
363        assert_eq!(
364            "Filter: devices.id > Int32(500)\n  TableScan: greptime.test.devices",
365            plan.to_string()
366        );
367    }
368
369    #[test]
370    fn test_extract_full_table_names_from_scalar_subquery_bare_table_scan() {
371        let ctx = QueryContextBuilder::default()
372            .current_catalog("qp031_catalog".to_string())
373            .current_schema("qp031_current_schema".to_string())
374            .build();
375
376        let (table_names, plan) = extract_and_rewrite_full_table_names(
377            scalar_subquery_plan(TableReference::bare("lookup")),
378            Arc::new(ctx),
379        )
380        .unwrap();
381
382        assert_dependencies(
383            &table_names,
384            &[("qp031_catalog", "qp031_current_schema", "lookup")],
385        );
386        assert_nested_scalar_subquery_table_name(
387            &plan,
388            TableReference::full("qp031_catalog", "qp031_current_schema", "lookup"),
389        );
390    }
391
392    #[test]
393    fn test_extract_full_table_names_from_scalar_subquery_partial_table_scan() {
394        let ctx = QueryContextBuilder::default()
395            .current_catalog("qp031_catalog".to_string())
396            .current_schema("qp031_current_schema".to_string())
397            .build();
398
399        let (table_names, plan) = extract_and_rewrite_full_table_names(
400            scalar_subquery_plan(TableReference::partial("qp031_lookup_schema", "lookup")),
401            Arc::new(ctx),
402        )
403        .unwrap();
404
405        assert_dependencies(
406            &table_names,
407            &[("qp031_catalog", "qp031_lookup_schema", "lookup")],
408        );
409        assert_nested_scalar_subquery_table_name(
410            &plan,
411            TableReference::full("qp031_catalog", "qp031_lookup_schema", "lookup"),
412        );
413    }
414
415    #[test]
416    fn test_extract_full_table_names_from_scalar_subquery_full_table_scan() {
417        let ctx = QueryContextBuilder::default()
418            .current_catalog("qp031_catalog".to_string())
419            .current_schema("qp031_current_schema".to_string())
420            .build();
421
422        let (table_names, plan) = extract_and_rewrite_full_table_names(
423            scalar_subquery_plan(TableReference::full(
424                "qp031_external_catalog",
425                "qp031_external_schema",
426                "lookup",
427            )),
428            Arc::new(ctx),
429        )
430        .unwrap();
431
432        assert_dependencies(
433            &table_names,
434            &[("qp031_external_catalog", "qp031_external_schema", "lookup")],
435        );
436        assert_nested_scalar_subquery_table_name(
437            &plan,
438            TableReference::full("qp031_external_catalog", "qp031_external_schema", "lookup"),
439        );
440    }
441
442    fn partitioned_table(
443        columns: &[&str],
444        partition_key_indices: Vec<usize>,
445        extras: &[&str],
446    ) -> TableRef {
447        let columns = columns
448            .iter()
449            .map(|name| ColumnSchema::new(*name, ConcreteDataType::string_datatype(), true))
450            .collect();
451        let mut info = test_table_info(
452            TABLE_ID,
453            "t",
454            DEFAULT_SCHEMA_NAME,
455            DEFAULT_CATALOG_NAME,
456            Arc::new(TableSchema::new(columns)),
457        );
458        info.meta.partition_key_indices = partition_key_indices;
459        let rules = PartitionRules {
460            extra_phy_cols_not_in_logical_table: extras.iter().map(ToString::to_string).collect(),
461        };
462        DistTable::table_partitioned(Arc::new(info), Some(rules))
463    }
464
465    /// Returns the plan that [refresh_partition_columns] builds for a scan of `captured` when
466    /// the catalog holds `current`.
467    async fn refresh_scan(captured: TableRef, current: TableRef) -> (TableScan, TableScan) {
468        let source = provider_as_source(Arc::new(DfTableProviderAdapter::new(captured)));
469        let filters = vec![col("a").gt(lit("x"))];
470        let plan = LogicalPlanBuilder::scan_with_filters_fetch(
471            "t",
472            source,
473            Some(vec![1]),
474            filters,
475            Some(5),
476        )
477        .unwrap()
478        .build()
479        .unwrap();
480        let catalog_manager = MemoryCatalogManager::with_default_setup();
481        catalog_manager
482            .register_table_sync(RegisterTableRequest {
483                catalog: DEFAULT_CATALOG_NAME.to_string(),
484                schema: DEFAULT_SCHEMA_NAME.to_string(),
485                table_name: "t".to_string(),
486                table_id: TABLE_ID,
487                table: current,
488            })
489            .unwrap();
490        let catalog_manager: CatalogManagerRef = catalog_manager;
491        let refreshed =
492            refresh_partition_columns(plan.clone(), &catalog_manager, &QueryContext::arc())
493                .await
494                .unwrap();
495        let (LogicalPlan::TableScan(original), LogicalPlan::TableScan(refreshed)) =
496            (plan, refreshed)
497        else {
498            panic!("expected table scans");
499        };
500        (original, refreshed)
501    }
502
503    #[tokio::test]
504    async fn test_refresh_partition_columns_compares_names() {
505        let captured = partitioned_table(&["a", "b"], vec![1], &[]);
506        let current = partitioned_table(&["b", "a", "c"], vec![0], &[]);
507
508        let (original, refreshed) = refresh_scan(captured, current).await;
509
510        assert!(Arc::ptr_eq(&original.source, &refreshed.source));
511    }
512
513    #[tokio::test]
514    async fn test_refresh_partition_columns_with_equal_schema() {
515        let captured = partitioned_table(&["a", "b"], vec![], &[]);
516        let current = partitioned_table(&["a", "b"], vec![1], &[]);
517
518        let (original, refreshed) = refresh_scan(captured, current.clone()).await;
519
520        let table = scanned_base_table(&refreshed).unwrap();
521        assert!(Arc::ptr_eq(&table, &current));
522        assert_eq!(original.projection, refreshed.projection);
523        assert_eq!(original.projected_schema, refreshed.projected_schema);
524        assert_eq!(original.filters, refreshed.filters);
525        assert_eq!(original.fetch, refreshed.fetch);
526    }
527
528    #[tokio::test]
529    async fn test_refresh_partition_columns_with_changed_schema() {
530        let captured = partitioned_table(&["a", "b"], vec![1], &[]);
531        let current = partitioned_table(&["a", "b", "c"], vec![2], &["d"]);
532
533        let (original, refreshed) = refresh_scan(captured.clone(), current).await;
534
535        let table = scanned_base_table(&refreshed).unwrap();
536        assert_eq!(table.schema(), captured.schema());
537        assert!(table.table_info().meta.partition_key_indices.is_empty());
538        assert_eq!(extra_partition_columns(&table), ["c", "d"]);
539        assert_eq!(original.projection, refreshed.projection);
540        assert_eq!(original.projected_schema, refreshed.projected_schema);
541        assert_eq!(original.filters, refreshed.filters);
542        assert_eq!(original.fetch, refreshed.fetch);
543    }
544}