Skip to main content

common_query/
logical_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
15mod expr;
16
17use std::sync::Arc;
18
19use api::v1::TableName;
20use datafusion::catalog::CatalogProviderList;
21use datafusion::error::Result as DatafusionResult;
22use datafusion::logical_expr::{LogicalPlan, LogicalPlanBuilder};
23use datafusion_common::{Column, TableReference};
24use datafusion_expr::dml::InsertOp;
25use datafusion_expr::{DmlStatement, TableSource, WriteOp, col};
26pub use expr::{
27    build_filter_from_timestamp, build_same_type_ts_filter, is_lossless_substrait_type,
28};
29
30use crate::error::Result;
31
32/// Rename columns by applying a new projection. Returns an error if the column to be
33/// renamed does not exist. The `renames` parameter is a `Vector` with elements
34/// in the form of `(old_name, new_name)`.
35pub fn rename_logical_plan_columns(
36    enable_ident_normalization: bool,
37    plan: LogicalPlan,
38    renames: Vec<(&str, &str)>,
39) -> DatafusionResult<LogicalPlan> {
40    let mut projection = Vec::with_capacity(renames.len());
41
42    for (old_name, new_name) in renames {
43        let old_column: Column = if enable_ident_normalization {
44            Column::from_qualified_name(old_name)
45        } else {
46            Column::from_qualified_name_ignore_case(old_name)
47        };
48
49        let (qualifier_rename, field_rename) =
50            plan.schema().qualified_field_from_column(&old_column)?;
51
52        for (qualifier, field) in plan.schema().iter() {
53            if qualifier.eq(&qualifier_rename) && field == field_rename {
54                projection.push(col(Column::from((qualifier, field))).alias(new_name));
55            }
56        }
57    }
58
59    LogicalPlanBuilder::from(plan).project(projection)?.build()
60}
61
62/// Convert a insert into logical plan to an (table_name, logical_plan)
63/// where table_name is the name of the table to insert into.
64/// logical_plan is the plan to be executed.
65///
66/// if input logical plan is not `insert into table_name <input>`, return None
67///
68/// Returned TableName will use provided catalog and schema if not specified in the logical plan,
69/// if table scan in logical plan have full table name, will **NOT** override it.
70pub fn breakup_insert_plan(
71    plan: &LogicalPlan,
72    default_catalog: &str,
73    default_schema: &str,
74) -> Option<(TableName, Arc<LogicalPlan>)> {
75    if let LogicalPlan::Dml(dml) = plan {
76        if dml.op != WriteOp::Insert(InsertOp::Append) {
77            return None;
78        }
79        let table_name = &dml.table_name;
80        let table_name = match table_name {
81            TableReference::Bare { table } => TableName {
82                catalog_name: default_catalog.to_string(),
83                schema_name: default_schema.to_string(),
84                table_name: table.to_string(),
85            },
86            TableReference::Partial { schema, table } => TableName {
87                catalog_name: default_catalog.to_string(),
88                schema_name: schema.to_string(),
89                table_name: table.to_string(),
90            },
91            TableReference::Full {
92                catalog,
93                schema,
94                table,
95            } => TableName {
96                catalog_name: catalog.to_string(),
97                schema_name: schema.to_string(),
98                table_name: table.to_string(),
99            },
100        };
101        let logical_plan = dml.input.clone();
102        Some((table_name, logical_plan))
103    } else {
104        None
105    }
106}
107
108/// create a `insert into table_name <input>` logical plan
109pub fn add_insert_to_logical_plan(
110    table_name: TableName,
111    target: Arc<dyn TableSource>,
112    input: LogicalPlan,
113) -> Result<LogicalPlan> {
114    let table_name = TableReference::Full {
115        catalog: table_name.catalog_name.into(),
116        schema: table_name.schema_name.into(),
117        table: table_name.table_name.into(),
118    };
119
120    let plan = LogicalPlan::Dml(DmlStatement::new(
121        table_name,
122        target,
123        WriteOp::Insert(InsertOp::Append),
124        Arc::new(input),
125    ));
126    let plan = plan.recompute_schema()?;
127    Ok(plan)
128}
129
130/// The datafusion `[LogicalPlan]` decoder.
131#[async_trait::async_trait]
132pub trait SubstraitPlanDecoder {
133    /// Decode the [`LogicalPlan`] from bytes with the [`CatalogProviderList`].
134    /// When `optimize` is true, it will do the optimization for decoded plan.
135    ///
136    /// TODO(dennis): It's not a good design for an API to do many things.
137    /// The `optimize` was introduced because of `query` and `catalog` cyclic dependency issue
138    /// I am happy to refactor it if we have a better solution.
139    async fn decode(
140        &self,
141        message: bytes::Bytes,
142        catalog_list: Arc<dyn CatalogProviderList>,
143        optimize: bool,
144    ) -> Result<LogicalPlan>;
145}
146
147pub type SubstraitPlanDecoderRef = Arc<dyn SubstraitPlanDecoder + Send + Sync>;
148
149#[cfg(test)]
150mod tests {
151    use std::sync::Arc;
152
153    use datafusion_expr::builder::LogicalTableSource;
154    use datafusion_expr::lit;
155    use datatypes::arrow::datatypes::{DataType, Field, Schema, SchemaRef};
156
157    use super::*;
158
159    fn mock_plan() -> LogicalPlan {
160        let schema = Schema::new(vec![
161            Field::new("id", DataType::Int32, true),
162            Field::new("name", DataType::Utf8, true),
163        ]);
164        let table_source = LogicalTableSource::new(SchemaRef::new(schema));
165
166        let projection = None;
167
168        let builder =
169            LogicalPlanBuilder::scan("person", Arc::new(table_source), projection).unwrap();
170
171        builder
172            .filter(col("id").gt(lit(500)))
173            .unwrap()
174            .build()
175            .unwrap()
176    }
177
178    #[test]
179    fn test_rename_logical_plan_columns() {
180        let plan = mock_plan();
181        let new_plan =
182            rename_logical_plan_columns(true, plan, vec![("id", "a"), ("name", "b")]).unwrap();
183
184        assert_eq!(
185            r#"
186Projection: person.id AS a, person.name AS b
187  Filter: person.id > Int32(500)
188    TableScan: person"#,
189            format!("\n{}", new_plan)
190        );
191    }
192}