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_function::function::FunctionRef;
20use datafusion::arrow::datatypes::{DataType, TimeUnit};
21use datafusion::logical_expr::ColumnarValue;
22use datafusion_expr::{ScalarFunctionArgs, Signature, Volatility};
23use datafusion_substrait::extensions::Extensions;
24use query::QueryEngine;
25use serde::{Deserialize, Serialize};
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::SimpleExtensionDeclaration;
30use substrait_proto::proto::extensions::simple_extension_declaration::MappingType;
31
32use crate::adapter::FlownodeContext;
33use crate::error::{Error, NotImplementedSnafu};
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    let tumble_fn = Arc::new(TumbleFunction::new("tumble")) as FunctionRef;
112    let tumble_start_fn = Arc::new(TumbleFunction::new(TUMBLE_START)) as FunctionRef;
113    let tumble_end_fn = Arc::new(TumbleFunction::new(TUMBLE_END)) as FunctionRef;
114
115    engine.register_scalar_function(tumble_fn.into());
116    engine.register_scalar_function(tumble_start_fn.into());
117    engine.register_scalar_function(tumble_end_fn.into());
118}
119
120#[derive(Debug)]
121pub struct TumbleFunction {
122    name: String,
123    signature: Signature,
124}
125
126impl TumbleFunction {
127    fn new(name: &str) -> Self {
128        Self {
129            name: name.to_string(),
130            signature: Signature::variadic_any(Volatility::Immutable),
131        }
132    }
133}
134
135impl std::fmt::Display for TumbleFunction {
136    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
137        write!(f, "{}", self.name.to_ascii_uppercase())
138    }
139}
140
141impl common_function::function::Function for TumbleFunction {
142    fn name(&self) -> &str {
143        &self.name
144    }
145
146    fn return_type(&self, _: &[DataType]) -> datafusion_common::Result<DataType> {
147        Ok(DataType::Timestamp(TimeUnit::Millisecond, None))
148    }
149
150    fn signature(&self) -> &Signature {
151        &self.signature
152    }
153
154    fn invoke_with_args(&self, _: ScalarFunctionArgs) -> datafusion_common::Result<ColumnarValue> {
155        datafusion_common::not_impl_err!("{}", self.name())
156    }
157}
158
159#[cfg(test)]
160mod test {
161    use std::sync::Arc;
162
163    use catalog::RegisterTableRequest;
164    use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, NUMBERS_TABLE_ID};
165    use datatypes::data_type::ConcreteDataType as CDT;
166    use datatypes::prelude::*;
167    use datatypes::schema::Schema;
168    use datatypes::timestamp::TimestampMillisecond;
169    use datatypes::vectors::{TimestampMillisecondVectorBuilder, VectorRef};
170    use itertools::Itertools;
171    use prost::Message;
172    use query::QueryEngine;
173    use query::options::QueryOptions;
174    use query::parser::QueryLanguageParser;
175    use query::query_engine::DefaultSerializer;
176    use session::context::QueryContext;
177    use substrait::{DFLogicalSubstraitConvertor, SubstraitPlan};
178    use substrait_proto::proto;
179    use table::table::numbers::{NUMBERS_TABLE_NAME, NumbersTable};
180    use table::test_util::MemTable;
181
182    use super::*;
183    use crate::adapter::node_context::IdToNameMap;
184    use crate::adapter::table_source::test::FlowDummyTableSource;
185    use crate::df_optimizer::apply_df_optimizer;
186    use crate::expr::GlobalId;
187
188    pub fn create_test_ctx() -> FlownodeContext {
189        let mut tri_map = IdToNameMap::new();
190        // FIXME(discord9): deprecated, use `numbers_with_ts` instead since this table has no timestamp column
191        {
192            let gid = GlobalId::User(0);
193            let name = [
194                "greptime".to_string(),
195                "public".to_string(),
196                "numbers".to_string(),
197            ];
198            tri_map.insert(Some(name.clone()), Some(1024), gid);
199        }
200
201        {
202            let gid = GlobalId::User(1);
203            let name = [
204                "greptime".to_string(),
205                "public".to_string(),
206                "numbers_with_ts".to_string(),
207            ];
208            tri_map.insert(Some(name.clone()), Some(1025), gid);
209        }
210
211        let dummy_source = FlowDummyTableSource::default();
212
213        let mut ctx = FlownodeContext::new(Box::new(dummy_source));
214        ctx.table_repr = tri_map;
215        ctx.query_context = Some(Arc::new(QueryContext::with("greptime", "public")));
216
217        ctx
218    }
219
220    pub fn create_test_query_engine() -> Arc<dyn QueryEngine> {
221        let catalog_list = catalog::memory::new_memory_catalog_manager().unwrap();
222        let req = RegisterTableRequest {
223            catalog: DEFAULT_CATALOG_NAME.to_string(),
224            schema: DEFAULT_SCHEMA_NAME.to_string(),
225            table_name: NUMBERS_TABLE_NAME.to_string(),
226            table_id: NUMBERS_TABLE_ID,
227            table: NumbersTable::table(NUMBERS_TABLE_ID),
228        };
229        catalog_list.register_table_sync(req).unwrap();
230
231        let schema = vec![
232            datatypes::schema::ColumnSchema::new("number", CDT::uint32_datatype(), false),
233            datatypes::schema::ColumnSchema::new(
234                "ts",
235                CDT::timestamp_millisecond_datatype(),
236                false,
237            ),
238        ];
239        let mut columns = vec![];
240        let numbers = (1..=10).collect_vec();
241        let column: VectorRef = Arc::new(<u32 as Scalar>::VectorType::from_vec(numbers));
242        columns.push(column);
243
244        let ts = (1..=10).collect_vec();
245        let mut builder = TimestampMillisecondVectorBuilder::with_capacity(10);
246        ts.into_iter()
247            .map(|v| builder.push(Some(TimestampMillisecond::new(v))))
248            .count();
249        let column: VectorRef = builder.to_vector_cloned();
250        columns.push(column);
251
252        let schema = Arc::new(Schema::new(schema));
253        let recordbatch = common_recordbatch::RecordBatch::new(schema, columns).unwrap();
254        let table = MemTable::table("numbers_with_ts", recordbatch);
255
256        let req_with_ts = RegisterTableRequest {
257            catalog: DEFAULT_CATALOG_NAME.to_string(),
258            schema: DEFAULT_SCHEMA_NAME.to_string(),
259            table_name: "numbers_with_ts".to_string(),
260            table_id: 1024,
261            table,
262        };
263        catalog_list.register_table_sync(req_with_ts).unwrap();
264
265        let factory = query::QueryEngineFactory::new(
266            catalog_list,
267            None,
268            None,
269            None,
270            None,
271            false,
272            QueryOptions::default(),
273        );
274
275        let engine = factory.query_engine();
276        register_function_to_query_engine(&engine);
277
278        assert_eq!("datafusion", engine.name());
279        engine
280    }
281
282    pub async fn sql_to_substrait(engine: Arc<dyn QueryEngine>, sql: &str) -> proto::Plan {
283        // let engine = create_test_query_engine();
284        let stmt = QueryLanguageParser::parse_sql(sql, &QueryContext::arc()).unwrap();
285        let plan = engine
286            .planner()
287            .plan(&stmt, QueryContext::arc())
288            .await
289            .unwrap();
290        let plan = apply_df_optimizer(plan, &QueryContext::arc())
291            .await
292            .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, &QueryContext::arc()).await;
315
316        assert!(plan.is_err());
317    }
318}