flow/
transform.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
15//! Transform Substrait into execution plan
16use std::collections::BTreeMap;
17use std::sync::Arc;
18
19use common_error::ext::BoxedError;
20use common_function::function::FunctionContext;
21use datafusion_substrait::extensions::Extensions;
22use datatypes::data_type::ConcreteDataType as CDT;
23use query::QueryEngine;
24use serde::{Deserialize, Serialize};
25use snafu::ResultExt;
26/// note here we are using the `substrait_proto_df` crate from the `substrait` module and
27/// rename it to `substrait_proto`
28use substrait::substrait_proto_df as substrait_proto;
29use substrait_proto::proto::extensions::simple_extension_declaration::MappingType;
30use substrait_proto::proto::extensions::SimpleExtensionDeclaration;
31
32use crate::adapter::FlownodeContext;
33use crate::error::{Error, NotImplementedSnafu, UnexpectedSnafu};
34use crate::expr::{TUMBLE_END, TUMBLE_START};
35/// a simple macro to generate a not implemented error
36macro_rules! not_impl_err {
37    ($($arg:tt)*)  => {
38        NotImplementedSnafu {
39            reason: format!($($arg)*),
40        }.fail()
41    };
42}
43
44/// generate a plan error
45macro_rules! plan_err {
46    ($($arg:tt)*)  => {
47        PlanSnafu {
48            reason: format!($($arg)*),
49        }.fail()
50    };
51}
52
53mod aggr;
54mod expr;
55mod literal;
56mod plan;
57
58pub(crate) use expr::from_scalar_fn_to_df_fn_impl;
59
60/// In Substrait, a function can be define by an u32 anchor, and the anchor can be mapped to a name
61///
62/// So in substrait plan, a ref to a function can be a single u32 anchor instead of a full name in string
63#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
64pub struct FunctionExtensions {
65    anchor_to_name: BTreeMap<u32, String>,
66}
67
68impl FunctionExtensions {
69    pub fn from_iter(inner: impl IntoIterator<Item = (u32, impl ToString)>) -> Self {
70        Self {
71            anchor_to_name: inner.into_iter().map(|(k, s)| (k, s.to_string())).collect(),
72        }
73    }
74
75    /// Create a new FunctionExtensions from a list of SimpleExtensionDeclaration
76    pub fn try_from_proto(extensions: &[SimpleExtensionDeclaration]) -> Result<Self, Error> {
77        let mut anchor_to_name = BTreeMap::new();
78        for e in extensions {
79            match &e.mapping_type {
80                Some(ext) => match ext {
81                    MappingType::ExtensionFunction(ext_f) => {
82                        anchor_to_name.insert(ext_f.function_anchor, ext_f.name.clone());
83                    }
84                    _ => not_impl_err!("Extension type not supported: {ext:?}")?,
85                },
86                None => not_impl_err!("Cannot parse empty extension")?,
87            }
88        }
89        Ok(Self { anchor_to_name })
90    }
91
92    /// Get the name of a function by it's anchor
93    pub fn get(&self, anchor: &u32) -> Option<&String> {
94        self.anchor_to_name.get(anchor)
95    }
96
97    pub fn to_extensions(&self) -> Extensions {
98        Extensions {
99            functions: self
100                .anchor_to_name
101                .iter()
102                .map(|(k, v)| (*k, v.clone()))
103                .collect(),
104            ..Default::default()
105        }
106    }
107}
108
109/// register flow-specific functions to the query engine
110pub fn register_function_to_query_engine(engine: &Arc<dyn QueryEngine>) {
111    engine.register_function(Arc::new(TumbleFunction::new("tumble")));
112    engine.register_function(Arc::new(TumbleFunction::new(TUMBLE_START)));
113    engine.register_function(Arc::new(TumbleFunction::new(TUMBLE_END)));
114}
115
116#[derive(Debug)]
117pub struct TumbleFunction {
118    name: String,
119}
120
121impl TumbleFunction {
122    fn new(name: &str) -> Self {
123        Self {
124            name: name.to_string(),
125        }
126    }
127}
128
129impl std::fmt::Display for TumbleFunction {
130    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
131        write!(f, "{}", self.name.to_ascii_uppercase())
132    }
133}
134
135impl common_function::function::Function for TumbleFunction {
136    fn name(&self) -> &str {
137        &self.name
138    }
139
140    fn return_type(&self, _input_types: &[CDT]) -> common_query::error::Result<CDT> {
141        Ok(CDT::timestamp_millisecond_datatype())
142    }
143
144    fn signature(&self) -> common_query::prelude::Signature {
145        common_query::prelude::Signature::variadic_any(common_query::prelude::Volatility::Immutable)
146    }
147
148    fn eval(
149        &self,
150        _func_ctx: &FunctionContext,
151        _columns: &[datatypes::prelude::VectorRef],
152    ) -> common_query::error::Result<datatypes::prelude::VectorRef> {
153        UnexpectedSnafu {
154            reason: "Tumbler function is not implemented for datafusion executor",
155        }
156        .fail()
157        .map_err(BoxedError::new)
158        .context(common_query::error::ExecuteSnafu)
159    }
160}
161
162#[cfg(test)]
163mod test {
164    use std::sync::Arc;
165
166    use catalog::RegisterTableRequest;
167    use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, NUMBERS_TABLE_ID};
168    use datatypes::prelude::*;
169    use datatypes::schema::Schema;
170    use datatypes::timestamp::TimestampMillisecond;
171    use datatypes::vectors::{TimestampMillisecondVectorBuilder, VectorRef};
172    use itertools::Itertools;
173    use prost::Message;
174    use query::options::QueryOptions;
175    use query::parser::QueryLanguageParser;
176    use query::query_engine::DefaultSerializer;
177    use query::QueryEngine;
178    use session::context::QueryContext;
179    use substrait::{DFLogicalSubstraitConvertor, SubstraitPlan};
180    use substrait_proto::proto;
181    use table::table::numbers::{NumbersTable, NUMBERS_TABLE_NAME};
182    use table::test_util::MemTable;
183
184    use super::*;
185    use crate::adapter::node_context::IdToNameMap;
186    use crate::adapter::table_source::test::FlowDummyTableSource;
187    use crate::df_optimizer::apply_df_optimizer;
188    use crate::expr::GlobalId;
189
190    pub fn create_test_ctx() -> FlownodeContext {
191        let mut tri_map = IdToNameMap::new();
192        // FIXME(discord9): deprecated, use `numbers_with_ts` instead since this table has no timestamp column
193        {
194            let gid = GlobalId::User(0);
195            let name = [
196                "greptime".to_string(),
197                "public".to_string(),
198                "numbers".to_string(),
199            ];
200            tri_map.insert(Some(name.clone()), Some(1024), gid);
201        }
202
203        {
204            let gid = GlobalId::User(1);
205            let name = [
206                "greptime".to_string(),
207                "public".to_string(),
208                "numbers_with_ts".to_string(),
209            ];
210            tri_map.insert(Some(name.clone()), Some(1025), gid);
211        }
212
213        let dummy_source = FlowDummyTableSource::default();
214
215        let mut ctx = FlownodeContext::new(Box::new(dummy_source));
216        ctx.table_repr = tri_map;
217        ctx.query_context = Some(Arc::new(QueryContext::with("greptime", "public")));
218
219        ctx
220    }
221
222    pub fn create_test_query_engine() -> Arc<dyn QueryEngine> {
223        let catalog_list = catalog::memory::new_memory_catalog_manager().unwrap();
224        let req = RegisterTableRequest {
225            catalog: DEFAULT_CATALOG_NAME.to_string(),
226            schema: DEFAULT_SCHEMA_NAME.to_string(),
227            table_name: NUMBERS_TABLE_NAME.to_string(),
228            table_id: NUMBERS_TABLE_ID,
229            table: NumbersTable::table(NUMBERS_TABLE_ID),
230        };
231        catalog_list.register_table_sync(req).unwrap();
232
233        let schema = vec![
234            datatypes::schema::ColumnSchema::new("number", CDT::uint32_datatype(), false),
235            datatypes::schema::ColumnSchema::new(
236                "ts",
237                CDT::timestamp_millisecond_datatype(),
238                false,
239            ),
240        ];
241        let mut columns = vec![];
242        let numbers = (1..=10).collect_vec();
243        let column: VectorRef = Arc::new(<u32 as Scalar>::VectorType::from_vec(numbers));
244        columns.push(column);
245
246        let ts = (1..=10).collect_vec();
247        let mut builder = TimestampMillisecondVectorBuilder::with_capacity(10);
248        ts.into_iter()
249            .map(|v| builder.push(Some(TimestampMillisecond::new(v))))
250            .count();
251        let column: VectorRef = builder.to_vector_cloned();
252        columns.push(column);
253
254        let schema = Arc::new(Schema::new(schema));
255        let recordbatch = common_recordbatch::RecordBatch::new(schema, columns).unwrap();
256        let table = MemTable::table("numbers_with_ts", recordbatch);
257
258        let req_with_ts = RegisterTableRequest {
259            catalog: DEFAULT_CATALOG_NAME.to_string(),
260            schema: DEFAULT_SCHEMA_NAME.to_string(),
261            table_name: "numbers_with_ts".to_string(),
262            table_id: 1024,
263            table,
264        };
265        catalog_list.register_table_sync(req_with_ts).unwrap();
266
267        let factory = query::QueryEngineFactory::new(
268            catalog_list,
269            None,
270            None,
271            None,
272            None,
273            false,
274            QueryOptions::default(),
275        );
276
277        let engine = factory.query_engine();
278        register_function_to_query_engine(&engine);
279
280        assert_eq!("datafusion", engine.name());
281        engine
282    }
283
284    pub async fn sql_to_substrait(engine: Arc<dyn QueryEngine>, sql: &str) -> proto::Plan {
285        // let engine = create_test_query_engine();
286        let stmt = QueryLanguageParser::parse_sql(sql, &QueryContext::arc()).unwrap();
287        let plan = engine
288            .planner()
289            .plan(&stmt, QueryContext::arc())
290            .await
291            .unwrap();
292        let plan = apply_df_optimizer(plan).await.unwrap();
293
294        // encode then decode so to rely on the impl of conversion from logical plan to substrait plan
295        let bytes = DFLogicalSubstraitConvertor {}
296            .encode(&plan, DefaultSerializer)
297            .unwrap();
298
299        proto::Plan::decode(bytes).unwrap()
300    }
301
302    /// TODO(discord9): add more illegal sql tests
303    #[tokio::test]
304    async fn test_missing_key_check() {
305        let engine = create_test_query_engine();
306        let sql = "SELECT avg(number) FROM numbers_with_ts GROUP BY tumble(ts, '1 hour'), number";
307
308        let stmt = QueryLanguageParser::parse_sql(sql, &QueryContext::arc()).unwrap();
309        let plan = engine
310            .planner()
311            .plan(&stmt, QueryContext::arc())
312            .await
313            .unwrap();
314        let plan = apply_df_optimizer(plan).await;
315
316        assert!(plan.is_err());
317    }
318}