query/
datafusion.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//! Planner, QueryEngine implementations based on DataFusion.
16
17mod error;
18mod planner;
19
20use std::any::Any;
21use std::collections::HashMap;
22use std::sync::Arc;
23
24use async_trait::async_trait;
25use common_base::Plugins;
26use common_catalog::consts::is_readonly_schema;
27use common_error::ext::BoxedError;
28use common_function::function::FunctionContext;
29use common_function::function_factory::ScalarFunctionFactory;
30use common_query::{Output, OutputData, OutputMeta};
31use common_recordbatch::adapter::RecordBatchStreamAdapter;
32use common_recordbatch::{EmptyRecordBatchStream, SendableRecordBatchStream};
33use common_telemetry::tracing;
34use datafusion::catalog::TableFunction;
35use datafusion::dataframe::DataFrame;
36use datafusion::physical_plan::ExecutionPlan;
37use datafusion::physical_plan::analyze::AnalyzeExec;
38use datafusion::physical_plan::coalesce_partitions::CoalescePartitionsExec;
39use datafusion_common::ResolvedTableReference;
40use datafusion_expr::{
41    AggregateUDF, DmlStatement, LogicalPlan as DfLogicalPlan, LogicalPlan, WriteOp,
42};
43use datatypes::prelude::VectorRef;
44use datatypes::schema::Schema;
45use futures_util::StreamExt;
46use session::context::QueryContextRef;
47use snafu::{OptionExt, ResultExt, ensure};
48use sqlparser::ast::AnalyzeFormat;
49use table::TableRef;
50use table::requests::{DeleteRequest, InsertRequest};
51use tracing::Span;
52
53use crate::analyze::DistAnalyzeExec;
54pub use crate::datafusion::planner::DfContextProviderAdapter;
55use crate::dist_plan::{DistPlannerOptions, MergeScanLogicalPlan};
56use crate::error::{
57    CatalogSnafu, ConvertSchemaSnafu, CreateRecordBatchSnafu, MissingTableMutationHandlerSnafu,
58    MissingTimestampColumnSnafu, QueryExecutionSnafu, Result, TableMutationSnafu,
59    TableNotFoundSnafu, TableReadOnlySnafu, UnsupportedExprSnafu,
60};
61use crate::executor::QueryExecutor;
62use crate::metrics::{OnDone, QUERY_STAGE_ELAPSED};
63use crate::physical_wrapper::PhysicalPlanWrapperRef;
64use crate::planner::{DfLogicalPlanner, LogicalPlanner};
65use crate::query_engine::{DescribeResult, QueryEngineContext, QueryEngineState};
66use crate::{QueryEngine, metrics};
67
68/// Query parallelism hint key.
69/// This hint can be set in the query context to control the parallelism of the query execution.
70pub const QUERY_PARALLELISM_HINT: &str = "query_parallelism";
71
72/// Whether to fallback to the original plan when failed to push down.
73pub const QUERY_FALLBACK_HINT: &str = "query_fallback";
74
75pub struct DatafusionQueryEngine {
76    state: Arc<QueryEngineState>,
77    plugins: Plugins,
78}
79
80impl DatafusionQueryEngine {
81    pub fn new(state: Arc<QueryEngineState>, plugins: Plugins) -> Self {
82        Self { state, plugins }
83    }
84
85    #[tracing::instrument(skip_all)]
86    async fn exec_query_plan(
87        &self,
88        plan: LogicalPlan,
89        query_ctx: QueryContextRef,
90    ) -> Result<Output> {
91        let mut ctx = self.engine_context(query_ctx.clone());
92
93        // `create_physical_plan` will optimize logical plan internally
94        let physical_plan = self.create_physical_plan(&mut ctx, &plan).await?;
95        let optimized_physical_plan = self.optimize_physical_plan(&mut ctx, physical_plan)?;
96
97        let physical_plan = if let Some(wrapper) = self.plugins.get::<PhysicalPlanWrapperRef>() {
98            wrapper.wrap(optimized_physical_plan, query_ctx)
99        } else {
100            optimized_physical_plan
101        };
102
103        Ok(Output::new(
104            OutputData::Stream(self.execute_stream(&ctx, &physical_plan)?),
105            OutputMeta::new_with_plan(physical_plan),
106        ))
107    }
108
109    #[tracing::instrument(skip_all)]
110    async fn exec_dml_statement(
111        &self,
112        dml: DmlStatement,
113        query_ctx: QueryContextRef,
114    ) -> Result<Output> {
115        ensure!(
116            matches!(dml.op, WriteOp::Insert(_) | WriteOp::Delete),
117            UnsupportedExprSnafu {
118                name: format!("DML op {}", dml.op),
119            }
120        );
121
122        let _timer = QUERY_STAGE_ELAPSED
123            .with_label_values(&[dml.op.name()])
124            .start_timer();
125
126        let default_catalog = &query_ctx.current_catalog().to_owned();
127        let default_schema = &query_ctx.current_schema();
128        let table_name = dml.table_name.resolve(default_catalog, default_schema);
129        let table = self.find_table(&table_name, &query_ctx).await?;
130
131        let output = self
132            .exec_query_plan((*dml.input).clone(), query_ctx.clone())
133            .await?;
134        let mut stream = match output.data {
135            OutputData::RecordBatches(batches) => batches.as_stream(),
136            OutputData::Stream(stream) => stream,
137            _ => unreachable!(),
138        };
139
140        let mut affected_rows = 0;
141        let mut insert_cost = 0;
142
143        while let Some(batch) = stream.next().await {
144            let batch = batch.context(CreateRecordBatchSnafu)?;
145            let column_vectors = batch
146                .column_vectors(&table_name.to_string(), table.schema())
147                .map_err(BoxedError::new)
148                .context(QueryExecutionSnafu)?;
149
150            match dml.op {
151                WriteOp::Insert(_) => {
152                    // We ignore the insert op.
153                    let output = self
154                        .insert(&table_name, column_vectors, query_ctx.clone())
155                        .await?;
156                    let (rows, cost) = output.extract_rows_and_cost();
157                    affected_rows += rows;
158                    insert_cost += cost;
159                }
160                WriteOp::Delete => {
161                    affected_rows += self
162                        .delete(&table_name, &table, column_vectors, query_ctx.clone())
163                        .await?;
164                }
165                _ => unreachable!("guarded by the 'ensure!' at the beginning"),
166            }
167        }
168        Ok(Output::new(
169            OutputData::AffectedRows(affected_rows),
170            OutputMeta::new_with_cost(insert_cost),
171        ))
172    }
173
174    #[tracing::instrument(skip_all)]
175    async fn delete(
176        &self,
177        table_name: &ResolvedTableReference,
178        table: &TableRef,
179        column_vectors: HashMap<String, VectorRef>,
180        query_ctx: QueryContextRef,
181    ) -> Result<usize> {
182        let catalog_name = table_name.catalog.to_string();
183        let schema_name = table_name.schema.to_string();
184        let table_name = table_name.table.to_string();
185        let table_schema = table.schema();
186
187        ensure!(
188            !is_readonly_schema(&schema_name),
189            TableReadOnlySnafu { table: table_name }
190        );
191
192        let ts_column = table_schema
193            .timestamp_column()
194            .map(|x| &x.name)
195            .with_context(|| MissingTimestampColumnSnafu {
196                table_name: table_name.clone(),
197            })?;
198
199        let table_info = table.table_info();
200        let rowkey_columns = table_info
201            .meta
202            .row_key_column_names()
203            .collect::<Vec<&String>>();
204        let column_vectors = column_vectors
205            .into_iter()
206            .filter(|x| &x.0 == ts_column || rowkey_columns.contains(&&x.0))
207            .collect::<HashMap<_, _>>();
208
209        let request = DeleteRequest {
210            catalog_name,
211            schema_name,
212            table_name,
213            key_column_values: column_vectors,
214        };
215
216        self.state
217            .table_mutation_handler()
218            .context(MissingTableMutationHandlerSnafu)?
219            .delete(request, query_ctx)
220            .await
221            .context(TableMutationSnafu)
222    }
223
224    #[tracing::instrument(skip_all)]
225    async fn insert(
226        &self,
227        table_name: &ResolvedTableReference,
228        column_vectors: HashMap<String, VectorRef>,
229        query_ctx: QueryContextRef,
230    ) -> Result<Output> {
231        let catalog_name = table_name.catalog.to_string();
232        let schema_name = table_name.schema.to_string();
233        let table_name = table_name.table.to_string();
234
235        ensure!(
236            !is_readonly_schema(&schema_name),
237            TableReadOnlySnafu { table: table_name }
238        );
239
240        let request = InsertRequest {
241            catalog_name,
242            schema_name,
243            table_name,
244            columns_values: column_vectors,
245        };
246
247        self.state
248            .table_mutation_handler()
249            .context(MissingTableMutationHandlerSnafu)?
250            .insert(request, query_ctx)
251            .await
252            .context(TableMutationSnafu)
253    }
254
255    async fn find_table(
256        &self,
257        table_name: &ResolvedTableReference,
258        query_context: &QueryContextRef,
259    ) -> Result<TableRef> {
260        let catalog_name = table_name.catalog.as_ref();
261        let schema_name = table_name.schema.as_ref();
262        let table_name = table_name.table.as_ref();
263
264        self.state
265            .catalog_manager()
266            .table(catalog_name, schema_name, table_name, Some(query_context))
267            .await
268            .context(CatalogSnafu)?
269            .with_context(|| TableNotFoundSnafu { table: table_name })
270    }
271
272    #[tracing::instrument(skip_all)]
273    async fn create_physical_plan(
274        &self,
275        ctx: &mut QueryEngineContext,
276        logical_plan: &LogicalPlan,
277    ) -> Result<Arc<dyn ExecutionPlan>> {
278        /// Only print context on panic, to avoid cluttering logs.
279        ///
280        /// TODO(discord9): remove this once we catch the bug
281        #[derive(Debug)]
282        struct PanicLogger<'a> {
283            input_logical_plan: &'a LogicalPlan,
284            after_analyze: Option<LogicalPlan>,
285            after_optimize: Option<LogicalPlan>,
286            phy_plan: Option<Arc<dyn ExecutionPlan>>,
287        }
288        impl Drop for PanicLogger<'_> {
289            fn drop(&mut self) {
290                if std::thread::panicking() {
291                    common_telemetry::error!(
292                        "Panic while creating physical plan, input logical plan: {:?}, after analyze: {:?}, after optimize: {:?}, final physical plan: {:?}",
293                        self.input_logical_plan,
294                        self.after_analyze,
295                        self.after_optimize,
296                        self.phy_plan
297                    );
298                }
299            }
300        }
301
302        let mut logger = PanicLogger {
303            input_logical_plan: logical_plan,
304            after_analyze: None,
305            after_optimize: None,
306            phy_plan: None,
307        };
308
309        let _timer = metrics::CREATE_PHYSICAL_ELAPSED.start_timer();
310        let state = ctx.state();
311
312        common_telemetry::debug!("Create physical plan, input plan: {logical_plan}");
313
314        // special handle EXPLAIN plan
315        if matches!(logical_plan, DfLogicalPlan::Explain(_)) {
316            return state
317                .create_physical_plan(logical_plan)
318                .await
319                .map_err(Into::into);
320        }
321
322        // analyze first
323        let analyzed_plan = state.analyzer().execute_and_check(
324            logical_plan.clone(),
325            state.config_options(),
326            |_, _| {},
327        )?;
328
329        logger.after_analyze = Some(analyzed_plan.clone());
330
331        common_telemetry::debug!("Create physical plan, analyzed plan: {analyzed_plan}");
332
333        // skip optimize for MergeScan
334        let optimized_plan = if let DfLogicalPlan::Extension(ext) = &analyzed_plan
335            && ext.node.name() == MergeScanLogicalPlan::name()
336        {
337            analyzed_plan.clone()
338        } else {
339            state
340                .optimizer()
341                .optimize(analyzed_plan, state, |_, _| {})?
342        };
343
344        common_telemetry::debug!("Create physical plan, optimized plan: {optimized_plan}");
345        logger.after_optimize = Some(optimized_plan.clone());
346
347        let physical_plan = state
348            .query_planner()
349            .create_physical_plan(&optimized_plan, state)
350            .await?;
351
352        logger.phy_plan = Some(physical_plan.clone());
353        drop(logger);
354        Ok(physical_plan)
355    }
356
357    #[tracing::instrument(skip_all)]
358    pub fn optimize(
359        &self,
360        context: &QueryEngineContext,
361        plan: &LogicalPlan,
362    ) -> Result<LogicalPlan> {
363        let _timer = metrics::OPTIMIZE_LOGICAL_ELAPSED.start_timer();
364
365        // Optimized by extension rules
366        let optimized_plan = self
367            .state
368            .optimize_by_extension_rules(plan.clone(), context)?;
369
370        // Optimized by datafusion optimizer
371        let optimized_plan = self.state.session_state().optimize(&optimized_plan)?;
372
373        Ok(optimized_plan)
374    }
375
376    #[tracing::instrument(skip_all)]
377    fn optimize_physical_plan(
378        &self,
379        ctx: &mut QueryEngineContext,
380        plan: Arc<dyn ExecutionPlan>,
381    ) -> Result<Arc<dyn ExecutionPlan>> {
382        let _timer = metrics::OPTIMIZE_PHYSICAL_ELAPSED.start_timer();
383
384        // TODO(ruihang): `self.create_physical_plan()` already optimize the plan, check
385        // if we need to optimize it again here.
386        // let state = ctx.state();
387        // let config = state.config_options();
388
389        // skip optimize AnalyzeExec plan
390        let optimized_plan = if let Some(analyze_plan) = plan.as_any().downcast_ref::<AnalyzeExec>()
391        {
392            let format = if let Some(format) = ctx.query_ctx().explain_format()
393                && format.to_lowercase() == "json"
394            {
395                AnalyzeFormat::JSON
396            } else {
397                AnalyzeFormat::TEXT
398            };
399            // Sets the verbose flag of the query context.
400            // The MergeScanExec plan uses the verbose flag to determine whether to print the plan in verbose mode.
401            ctx.query_ctx().set_explain_verbose(analyze_plan.verbose());
402
403            Arc::new(DistAnalyzeExec::new(
404                analyze_plan.input().clone(),
405                analyze_plan.verbose(),
406                format,
407            ))
408            // let mut new_plan = analyze_plan.input().clone();
409            // for optimizer in state.physical_optimizers() {
410            //     new_plan = optimizer
411            //         .optimize(new_plan, config)
412            //         .context(DataFusionSnafu)?;
413            // }
414            // Arc::new(DistAnalyzeExec::new(new_plan))
415        } else {
416            plan
417            // let mut new_plan = plan;
418            // for optimizer in state.physical_optimizers() {
419            //     new_plan = optimizer
420            //         .optimize(new_plan, config)
421            //         .context(DataFusionSnafu)?;
422            // }
423            // new_plan
424        };
425
426        Ok(optimized_plan)
427    }
428}
429
430#[async_trait]
431impl QueryEngine for DatafusionQueryEngine {
432    fn as_any(&self) -> &dyn Any {
433        self
434    }
435
436    fn planner(&self) -> Arc<dyn LogicalPlanner> {
437        Arc::new(DfLogicalPlanner::new(self.state.clone()))
438    }
439
440    fn name(&self) -> &str {
441        "datafusion"
442    }
443
444    async fn describe(
445        &self,
446        plan: LogicalPlan,
447        query_ctx: QueryContextRef,
448    ) -> Result<DescribeResult> {
449        let ctx = self.engine_context(query_ctx);
450        if let Ok(optimised_plan) = self.optimize(&ctx, &plan) {
451            let schema = optimised_plan
452                .schema()
453                .clone()
454                .try_into()
455                .context(ConvertSchemaSnafu)?;
456            Ok(DescribeResult {
457                schema,
458                logical_plan: optimised_plan,
459            })
460        } else {
461            // Table's like those in information_schema cannot be optimized when
462            // it contains parameters. So we fallback to original plans.
463            let schema = plan
464                .schema()
465                .clone()
466                .try_into()
467                .context(ConvertSchemaSnafu)?;
468            Ok(DescribeResult {
469                schema,
470                logical_plan: plan,
471            })
472        }
473    }
474
475    async fn execute(&self, plan: LogicalPlan, query_ctx: QueryContextRef) -> Result<Output> {
476        match plan {
477            LogicalPlan::Dml(dml) => self.exec_dml_statement(dml, query_ctx).await,
478            _ => self.exec_query_plan(plan, query_ctx).await,
479        }
480    }
481
482    /// Note in SQL queries, aggregate names are looked up using
483    /// lowercase unless the query uses quotes. For example,
484    ///
485    /// `SELECT MY_UDAF(x)...` will look for an aggregate named `"my_udaf"`
486    /// `SELECT "my_UDAF"(x)` will look for an aggregate named `"my_UDAF"`
487    ///
488    /// So it's better to make UDAF name lowercase when creating one.
489    fn register_aggregate_function(&self, func: AggregateUDF) {
490        self.state.register_aggr_function(func);
491    }
492
493    /// Register an scalar function.
494    /// Will override if the function with same name is already registered.
495    fn register_scalar_function(&self, func: ScalarFunctionFactory) {
496        self.state.register_scalar_function(func);
497    }
498
499    fn register_table_function(&self, func: Arc<TableFunction>) {
500        self.state.register_table_function(func);
501    }
502
503    fn read_table(&self, table: TableRef) -> Result<DataFrame> {
504        self.state.read_table(table).map_err(Into::into)
505    }
506
507    fn engine_context(&self, query_ctx: QueryContextRef) -> QueryEngineContext {
508        let mut state = self.state.session_state();
509        state.config_mut().set_extension(query_ctx.clone());
510        // note that hints in "x-greptime-hints" is automatically parsed
511        // and set to query context's extension, so we can get it from query context.
512        if let Some(parallelism) = query_ctx.extension(QUERY_PARALLELISM_HINT) {
513            if let Ok(n) = parallelism.parse::<u64>() {
514                if n > 0 {
515                    let new_cfg = state.config().clone().with_target_partitions(n as usize);
516                    *state.config_mut() = new_cfg;
517                }
518            } else {
519                common_telemetry::warn!(
520                    "Failed to parse query_parallelism: {}, using default value",
521                    parallelism
522                );
523            }
524        }
525
526        // configure execution options
527        state.config_mut().options_mut().execution.time_zone =
528            Some(query_ctx.timezone().to_string());
529
530        // usually it's impossible to have both `set variable` set by sql client and
531        // hint in header by grpc client, so only need to deal with them separately
532        if query_ctx.configuration_parameter().allow_query_fallback() {
533            state
534                .config_mut()
535                .options_mut()
536                .extensions
537                .insert(DistPlannerOptions {
538                    allow_query_fallback: true,
539                });
540        } else if let Some(fallback) = query_ctx.extension(QUERY_FALLBACK_HINT) {
541            // also check the query context for fallback hint
542            // if it is set, we will enable the fallback
543            if fallback.to_lowercase().parse::<bool>().unwrap_or(false) {
544                state
545                    .config_mut()
546                    .options_mut()
547                    .extensions
548                    .insert(DistPlannerOptions {
549                        allow_query_fallback: true,
550                    });
551            }
552        }
553
554        state
555            .config_mut()
556            .options_mut()
557            .extensions
558            .insert(FunctionContext {
559                query_ctx: query_ctx.clone(),
560                state: self.engine_state().function_state(),
561            });
562
563        let config_options = state.config_options().clone();
564        let _ = state
565            .execution_props_mut()
566            .config_options
567            .insert(config_options);
568
569        QueryEngineContext::new(state, query_ctx)
570    }
571
572    fn engine_state(&self) -> &QueryEngineState {
573        &self.state
574    }
575}
576
577impl QueryExecutor for DatafusionQueryEngine {
578    #[tracing::instrument(skip_all)]
579    fn execute_stream(
580        &self,
581        ctx: &QueryEngineContext,
582        plan: &Arc<dyn ExecutionPlan>,
583    ) -> Result<SendableRecordBatchStream> {
584        let explain_verbose = ctx.query_ctx().explain_verbose();
585        let output_partitions = plan.properties().output_partitioning().partition_count();
586        if explain_verbose {
587            common_telemetry::info!("Executing query plan, output_partitions: {output_partitions}");
588        }
589
590        let exec_timer = metrics::EXEC_PLAN_ELAPSED.start_timer();
591        let task_ctx = ctx.build_task_ctx();
592        let span = Span::current();
593
594        match plan.properties().output_partitioning().partition_count() {
595            0 => {
596                let schema = Arc::new(
597                    Schema::try_from(plan.schema())
598                        .map_err(BoxedError::new)
599                        .context(QueryExecutionSnafu)?,
600                );
601                Ok(Box::pin(EmptyRecordBatchStream::new(schema)))
602            }
603            1 => {
604                let df_stream = plan.execute(0, task_ctx)?;
605                let mut stream = RecordBatchStreamAdapter::try_new_with_span(df_stream, span)
606                    .context(error::ConvertDfRecordBatchStreamSnafu)
607                    .map_err(BoxedError::new)
608                    .context(QueryExecutionSnafu)?;
609                stream.set_metrics2(plan.clone());
610                stream.set_explain_verbose(explain_verbose);
611                let stream = OnDone::new(Box::pin(stream), move || {
612                    let exec_cost = exec_timer.stop_and_record();
613                    if explain_verbose {
614                        common_telemetry::info!(
615                            "DatafusionQueryEngine execute 1 stream, cost: {:?}s",
616                            exec_cost,
617                        );
618                    }
619                });
620                Ok(Box::pin(stream))
621            }
622            _ => {
623                // merge into a single partition
624                let merged_plan = CoalescePartitionsExec::new(plan.clone());
625                // CoalescePartitionsExec must produce a single partition
626                assert_eq!(
627                    1,
628                    merged_plan
629                        .properties()
630                        .output_partitioning()
631                        .partition_count()
632                );
633                let df_stream = merged_plan.execute(0, task_ctx)?;
634                let mut stream = RecordBatchStreamAdapter::try_new_with_span(df_stream, span)
635                    .context(error::ConvertDfRecordBatchStreamSnafu)
636                    .map_err(BoxedError::new)
637                    .context(QueryExecutionSnafu)?;
638                stream.set_metrics2(plan.clone());
639                stream.set_explain_verbose(ctx.query_ctx().explain_verbose());
640                let stream = OnDone::new(Box::pin(stream), move || {
641                    let exec_cost = exec_timer.stop_and_record();
642                    if explain_verbose {
643                        common_telemetry::info!(
644                            "DatafusionQueryEngine execute {output_partitions} stream, cost: {:?}s",
645                            exec_cost
646                        );
647                    }
648                });
649                Ok(Box::pin(stream))
650            }
651        }
652    }
653}
654
655#[cfg(test)]
656mod tests {
657    use std::sync::Arc;
658
659    use arrow::array::{ArrayRef, UInt64Array};
660    use catalog::RegisterTableRequest;
661    use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, NUMBERS_TABLE_ID};
662    use common_recordbatch::util;
663    use datafusion::prelude::{col, lit};
664    use datatypes::prelude::ConcreteDataType;
665    use datatypes::schema::ColumnSchema;
666    use datatypes::vectors::{Helper, UInt32Vector, VectorRef};
667    use session::context::{QueryContext, QueryContextBuilder};
668    use table::table::numbers::{NUMBERS_TABLE_NAME, NumbersTable};
669
670    use super::*;
671    use crate::options::QueryOptions;
672    use crate::parser::QueryLanguageParser;
673    use crate::query_engine::{QueryEngineFactory, QueryEngineRef};
674
675    async fn create_test_engine() -> QueryEngineRef {
676        let catalog_manager = catalog::memory::new_memory_catalog_manager().unwrap();
677        let req = RegisterTableRequest {
678            catalog: DEFAULT_CATALOG_NAME.to_string(),
679            schema: DEFAULT_SCHEMA_NAME.to_string(),
680            table_name: NUMBERS_TABLE_NAME.to_string(),
681            table_id: NUMBERS_TABLE_ID,
682            table: NumbersTable::table(NUMBERS_TABLE_ID),
683        };
684        catalog_manager.register_table_sync(req).unwrap();
685
686        QueryEngineFactory::new(
687            catalog_manager,
688            None,
689            None,
690            None,
691            None,
692            false,
693            QueryOptions::default(),
694        )
695        .query_engine()
696    }
697
698    #[tokio::test]
699    async fn test_sql_to_plan() {
700        let engine = create_test_engine().await;
701        let sql = "select sum(number) from numbers limit 20";
702
703        let stmt = QueryLanguageParser::parse_sql(sql, &QueryContext::arc()).unwrap();
704        let plan = engine
705            .planner()
706            .plan(&stmt, QueryContext::arc())
707            .await
708            .unwrap();
709
710        assert_eq!(
711            plan.to_string(),
712            r#"Limit: skip=0, fetch=20
713  Projection: sum(numbers.number)
714    Aggregate: groupBy=[[]], aggr=[[sum(numbers.number)]]
715      TableScan: numbers"#
716        );
717    }
718
719    #[tokio::test]
720    async fn test_execute() {
721        let engine = create_test_engine().await;
722        let sql = "select sum(number) from numbers limit 20";
723
724        let stmt = QueryLanguageParser::parse_sql(sql, &QueryContext::arc()).unwrap();
725        let plan = engine
726            .planner()
727            .plan(&stmt, QueryContext::arc())
728            .await
729            .unwrap();
730
731        let output = engine.execute(plan, QueryContext::arc()).await.unwrap();
732
733        match output.data {
734            OutputData::Stream(recordbatch) => {
735                let numbers = util::collect(recordbatch).await.unwrap();
736                assert_eq!(1, numbers.len());
737                assert_eq!(numbers[0].num_columns(), 1);
738                assert_eq!(1, numbers[0].schema.num_columns());
739                assert_eq!(
740                    "sum(numbers.number)",
741                    numbers[0].schema.column_schemas()[0].name
742                );
743
744                let batch = &numbers[0];
745                assert_eq!(1, batch.num_columns());
746                assert_eq!(batch.column(0).len(), 1);
747
748                let expected = Arc::new(UInt64Array::from_iter_values([4950])) as ArrayRef;
749                assert_eq!(batch.column(0), &expected);
750            }
751            _ => unreachable!(),
752        }
753    }
754
755    #[tokio::test]
756    async fn test_read_table() {
757        let engine = create_test_engine().await;
758
759        let engine = engine
760            .as_any()
761            .downcast_ref::<DatafusionQueryEngine>()
762            .unwrap();
763        let query_ctx = Arc::new(QueryContextBuilder::default().build());
764        let table = engine
765            .find_table(
766                &ResolvedTableReference {
767                    catalog: "greptime".into(),
768                    schema: "public".into(),
769                    table: "numbers".into(),
770                },
771                &query_ctx,
772            )
773            .await
774            .unwrap();
775
776        let df = engine.read_table(table).unwrap();
777        let df = df
778            .select_columns(&["number"])
779            .unwrap()
780            .filter(col("number").lt(lit(10)))
781            .unwrap();
782        let batches = df.collect().await.unwrap();
783        assert_eq!(1, batches.len());
784        let batch = &batches[0];
785
786        assert_eq!(1, batch.num_columns());
787        assert_eq!(batch.column(0).len(), 10);
788
789        assert_eq!(
790            Helper::try_into_vector(batch.column(0)).unwrap(),
791            Arc::new(UInt32Vector::from_slice([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])) as VectorRef
792        );
793    }
794
795    #[tokio::test]
796    async fn test_describe() {
797        let engine = create_test_engine().await;
798        let sql = "select sum(number) from numbers limit 20";
799
800        let stmt = QueryLanguageParser::parse_sql(sql, &QueryContext::arc()).unwrap();
801
802        let plan = engine
803            .planner()
804            .plan(&stmt, QueryContext::arc())
805            .await
806            .unwrap();
807
808        let DescribeResult {
809            schema,
810            logical_plan,
811        } = engine.describe(plan, QueryContext::arc()).await.unwrap();
812
813        assert_eq!(
814            schema.column_schemas()[0],
815            ColumnSchema::new(
816                "sum(numbers.number)",
817                ConcreteDataType::uint64_datatype(),
818                true
819            )
820        );
821        assert_eq!(
822            "Limit: skip=0, fetch=20\n  Aggregate: groupBy=[[]], aggr=[[sum(CAST(numbers.number AS UInt64))]]\n    TableScan: numbers projection=[number]",
823            format!("{}", logical_plan.display_indent())
824        );
825    }
826}