Skip to main content

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, WindowUDF, 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, 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    fn optimize_physical_plan(
359        &self,
360        ctx: &mut QueryEngineContext,
361        plan: Arc<dyn ExecutionPlan>,
362    ) -> Result<Arc<dyn ExecutionPlan>> {
363        let _timer = metrics::OPTIMIZE_PHYSICAL_ELAPSED.start_timer();
364
365        // TODO(ruihang): `self.create_physical_plan()` already optimize the plan, check
366        // if we need to optimize it again here.
367        // let state = ctx.state();
368        // let config = state.config_options();
369
370        // skip optimize AnalyzeExec plan
371        let optimized_plan = if let Some(analyze_plan) = plan.as_any().downcast_ref::<AnalyzeExec>()
372        {
373            let format = if let Some(format) = ctx.query_ctx().explain_format()
374                && format.to_lowercase() == "json"
375            {
376                AnalyzeFormat::JSON
377            } else {
378                AnalyzeFormat::TEXT
379            };
380            // Sets the verbose flag of the query context.
381            // The MergeScanExec plan uses the verbose flag to determine whether to print the plan in verbose mode.
382            ctx.query_ctx().set_explain_verbose(analyze_plan.verbose());
383
384            Arc::new(DistAnalyzeExec::new(
385                analyze_plan.input().clone(),
386                analyze_plan.verbose(),
387                format,
388            ))
389            // let mut new_plan = analyze_plan.input().clone();
390            // for optimizer in state.physical_optimizers() {
391            //     new_plan = optimizer
392            //         .optimize(new_plan, config)
393            //         .context(DataFusionSnafu)?;
394            // }
395            // Arc::new(DistAnalyzeExec::new(new_plan))
396        } else {
397            plan
398            // let mut new_plan = plan;
399            // for optimizer in state.physical_optimizers() {
400            //     new_plan = optimizer
401            //         .optimize(new_plan, config)
402            //         .context(DataFusionSnafu)?;
403            // }
404            // new_plan
405        };
406
407        Ok(optimized_plan)
408    }
409}
410
411#[async_trait]
412impl QueryEngine for DatafusionQueryEngine {
413    fn as_any(&self) -> &dyn Any {
414        self
415    }
416
417    fn planner(&self) -> Arc<dyn LogicalPlanner> {
418        Arc::new(DfLogicalPlanner::new(self.state.clone()))
419    }
420
421    fn name(&self) -> &str {
422        "datafusion"
423    }
424
425    async fn describe(
426        &self,
427        plan: LogicalPlan,
428        _query_ctx: QueryContextRef,
429    ) -> Result<DescribeResult> {
430        Ok(DescribeResult { logical_plan: plan })
431    }
432
433    async fn execute(&self, plan: LogicalPlan, query_ctx: QueryContextRef) -> Result<Output> {
434        match plan {
435            LogicalPlan::Dml(dml) => self.exec_dml_statement(dml, query_ctx).await,
436            _ => self.exec_query_plan(plan, query_ctx).await,
437        }
438    }
439
440    /// Note in SQL queries, aggregate names are looked up using
441    /// lowercase unless the query uses quotes. For example,
442    ///
443    /// `SELECT MY_UDAF(x)...` will look for an aggregate named `"my_udaf"`
444    /// `SELECT "my_UDAF"(x)` will look for an aggregate named `"my_UDAF"`
445    ///
446    /// So it's better to make UDAF name lowercase when creating one.
447    fn register_aggregate_function(&self, func: AggregateUDF) {
448        self.state.register_aggr_function(func);
449    }
450
451    /// Register an scalar function.
452    /// Will override if the function with same name is already registered.
453    fn register_scalar_function(&self, func: ScalarFunctionFactory) {
454        self.state.register_scalar_function(func);
455    }
456
457    fn register_table_function(&self, func: Arc<TableFunction>) {
458        self.state.register_table_function(func);
459    }
460
461    fn register_window_function(&self, func: WindowUDF) {
462        self.state.register_window_function(func);
463    }
464
465    fn read_table(&self, table: TableRef) -> Result<DataFrame> {
466        self.state.read_table(table).map_err(Into::into)
467    }
468
469    fn engine_context(&self, query_ctx: QueryContextRef) -> QueryEngineContext {
470        let mut state = self.state.session_state();
471        state.config_mut().set_extension(query_ctx.clone());
472        // note that hints in "x-greptime-hints" is automatically parsed
473        // and set to query context's extension, so we can get it from query context.
474        if let Some(parallelism) = query_ctx.extension(QUERY_PARALLELISM_HINT) {
475            if let Ok(n) = parallelism.parse::<u64>() {
476                if n > 0 {
477                    let new_cfg = state.config().clone().with_target_partitions(n as usize);
478                    *state.config_mut() = new_cfg;
479                }
480            } else {
481                common_telemetry::warn!(
482                    "Failed to parse query_parallelism: {}, using default value",
483                    parallelism
484                );
485            }
486        }
487
488        // configure execution options
489        state.config_mut().options_mut().execution.time_zone =
490            Some(query_ctx.timezone().to_string());
491
492        // usually it's impossible to have both `set variable` set by sql client and
493        // hint in header by grpc client, so only need to deal with them separately
494        if query_ctx.configuration_parameter().allow_query_fallback() {
495            state
496                .config_mut()
497                .options_mut()
498                .extensions
499                .insert(DistPlannerOptions {
500                    allow_query_fallback: true,
501                });
502        } else if let Some(fallback) = query_ctx.extension(QUERY_FALLBACK_HINT) {
503            // also check the query context for fallback hint
504            // if it is set, we will enable the fallback
505            if fallback.to_lowercase().parse::<bool>().unwrap_or(false) {
506                state
507                    .config_mut()
508                    .options_mut()
509                    .extensions
510                    .insert(DistPlannerOptions {
511                        allow_query_fallback: true,
512                    });
513            }
514        }
515
516        state
517            .config_mut()
518            .options_mut()
519            .extensions
520            .insert(FunctionContext {
521                query_ctx: query_ctx.clone(),
522                state: self.engine_state().function_state(),
523            });
524
525        let config_options = state.config_options().clone();
526        let _ = state
527            .execution_props_mut()
528            .config_options
529            .insert(config_options);
530
531        QueryEngineContext::new(state, query_ctx)
532    }
533
534    fn engine_state(&self) -> &QueryEngineState {
535        &self.state
536    }
537}
538
539impl QueryExecutor for DatafusionQueryEngine {
540    #[tracing::instrument(skip_all)]
541    fn execute_stream(
542        &self,
543        ctx: &QueryEngineContext,
544        plan: &Arc<dyn ExecutionPlan>,
545    ) -> Result<SendableRecordBatchStream> {
546        let explain_verbose = ctx.query_ctx().explain_verbose();
547        let output_partitions = plan.properties().output_partitioning().partition_count();
548        if explain_verbose {
549            common_telemetry::info!("Executing query plan, output_partitions: {output_partitions}");
550        }
551
552        let exec_timer = metrics::EXEC_PLAN_ELAPSED.start_timer();
553        let task_ctx = ctx.build_task_ctx();
554        let span = Span::current();
555
556        match plan.properties().output_partitioning().partition_count() {
557            0 => {
558                let schema = Arc::new(
559                    Schema::try_from(plan.schema())
560                        .map_err(BoxedError::new)
561                        .context(QueryExecutionSnafu)?,
562                );
563                Ok(Box::pin(EmptyRecordBatchStream::new(schema)))
564            }
565            1 => {
566                let df_stream = plan.execute(0, task_ctx)?;
567                let mut stream = RecordBatchStreamAdapter::try_new_with_span(df_stream, span)
568                    .context(error::ConvertDfRecordBatchStreamSnafu)
569                    .map_err(BoxedError::new)
570                    .context(QueryExecutionSnafu)?;
571                stream.set_metrics2(plan.clone());
572                stream.set_explain_verbose(explain_verbose);
573                let stream = OnDone::new(Box::pin(stream), move || {
574                    let exec_cost = exec_timer.stop_and_record();
575                    if explain_verbose {
576                        common_telemetry::info!(
577                            "DatafusionQueryEngine execute 1 stream, cost: {:?}s",
578                            exec_cost,
579                        );
580                    }
581                });
582                Ok(Box::pin(stream))
583            }
584            _ => {
585                // merge into a single partition
586                let merged_plan = CoalescePartitionsExec::new(plan.clone());
587                // CoalescePartitionsExec must produce a single partition
588                assert_eq!(
589                    1,
590                    merged_plan
591                        .properties()
592                        .output_partitioning()
593                        .partition_count()
594                );
595                let df_stream = merged_plan.execute(0, task_ctx)?;
596                let mut stream = RecordBatchStreamAdapter::try_new_with_span(df_stream, span)
597                    .context(error::ConvertDfRecordBatchStreamSnafu)
598                    .map_err(BoxedError::new)
599                    .context(QueryExecutionSnafu)?;
600                stream.set_metrics2(plan.clone());
601                stream.set_explain_verbose(ctx.query_ctx().explain_verbose());
602                let stream = OnDone::new(Box::pin(stream), move || {
603                    let exec_cost = exec_timer.stop_and_record();
604                    if explain_verbose {
605                        common_telemetry::info!(
606                            "DatafusionQueryEngine execute {output_partitions} stream, cost: {:?}s",
607                            exec_cost
608                        );
609                    }
610                });
611                Ok(Box::pin(stream))
612            }
613        }
614    }
615}
616
617#[cfg(test)]
618mod tests {
619    use std::fmt;
620    use std::sync::Arc;
621    use std::sync::atomic::{AtomicUsize, Ordering};
622
623    use api::v1::SemanticType;
624    use arrow::array::{ArrayRef, UInt64Array};
625    use arrow_schema::SortOptions;
626    use catalog::RegisterTableRequest;
627    use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, NUMBERS_TABLE_ID};
628    use common_error::ext::BoxedError;
629    use common_recordbatch::{EmptyRecordBatchStream, SendableRecordBatchStream, util};
630    use datafusion::physical_plan::display::{DisplayAs, DisplayFormatType};
631    use datafusion::physical_plan::expressions::PhysicalSortExpr;
632    use datafusion::physical_plan::joins::{HashJoinExec, JoinOn, PartitionMode};
633    use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet;
634    use datafusion::physical_plan::{ExecutionPlan, PhysicalExpr};
635    use datafusion::prelude::{col, lit};
636    use datafusion_common::{JoinType, NullEquality};
637    use datafusion_physical_expr::expressions::Column;
638    use datatypes::prelude::ConcreteDataType;
639    use datatypes::schema::{ColumnSchema, SchemaRef};
640    use datatypes::vectors::{Helper, UInt32Vector, VectorRef};
641    use session::context::{QueryContext, QueryContextBuilder};
642    use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder, RegionMetadataRef};
643    use store_api::region_engine::{
644        PartitionRange, PrepareRequest, QueryScanContext, RegionScanner, ScannerProperties,
645    };
646    use store_api::storage::{RegionId, ScanRequest};
647    use table::table::numbers::{NUMBERS_TABLE_NAME, NumbersTable};
648    use table::table::scan::RegionScanExec;
649
650    use super::*;
651    use crate::options::QueryOptions;
652    use crate::parser::QueryLanguageParser;
653    use crate::part_sort::PartSortExec;
654    use crate::query_engine::{QueryEngineFactory, QueryEngineRef};
655
656    #[derive(Debug)]
657    struct RecordingScanner {
658        schema: SchemaRef,
659        metadata: RegionMetadataRef,
660        properties: ScannerProperties,
661        update_calls: Arc<AtomicUsize>,
662        last_filter_len: Arc<AtomicUsize>,
663    }
664
665    impl RecordingScanner {
666        fn new(
667            schema: SchemaRef,
668            metadata: RegionMetadataRef,
669            update_calls: Arc<AtomicUsize>,
670            last_filter_len: Arc<AtomicUsize>,
671        ) -> Self {
672            Self {
673                schema,
674                metadata,
675                properties: ScannerProperties::default(),
676                update_calls,
677                last_filter_len,
678            }
679        }
680    }
681
682    impl RegionScanner for RecordingScanner {
683        fn name(&self) -> &str {
684            "RecordingScanner"
685        }
686
687        fn properties(&self) -> &ScannerProperties {
688            &self.properties
689        }
690
691        fn schema(&self) -> SchemaRef {
692            self.schema.clone()
693        }
694
695        fn metadata(&self) -> RegionMetadataRef {
696            self.metadata.clone()
697        }
698
699        fn prepare(&mut self, request: PrepareRequest) -> std::result::Result<(), BoxedError> {
700            self.properties.prepare(request);
701            Ok(())
702        }
703
704        fn scan_partition(
705            &self,
706            _ctx: &QueryScanContext,
707            _metrics_set: &ExecutionPlanMetricsSet,
708            _partition: usize,
709        ) -> std::result::Result<SendableRecordBatchStream, BoxedError> {
710            Ok(Box::pin(EmptyRecordBatchStream::new(self.schema.clone())))
711        }
712
713        fn has_predicate_without_region(&self) -> bool {
714            true
715        }
716
717        fn add_dyn_filter_to_predicate(
718            &mut self,
719            filter_exprs: Vec<Arc<dyn PhysicalExpr>>,
720        ) -> Vec<bool> {
721            self.update_calls.fetch_add(1, Ordering::Relaxed);
722            self.last_filter_len
723                .store(filter_exprs.len(), Ordering::Relaxed);
724            vec![true; filter_exprs.len()]
725        }
726
727        fn set_logical_region(&mut self, logical_region: bool) {
728            self.properties.set_logical_region(logical_region);
729        }
730    }
731
732    impl DisplayAs for RecordingScanner {
733        fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter<'_>) -> fmt::Result {
734            write!(f, "RecordingScanner")
735        }
736    }
737
738    async fn create_test_engine() -> QueryEngineRef {
739        let catalog_manager = catalog::memory::new_memory_catalog_manager().unwrap();
740        let req = RegisterTableRequest {
741            catalog: DEFAULT_CATALOG_NAME.to_string(),
742            schema: DEFAULT_SCHEMA_NAME.to_string(),
743            table_name: NUMBERS_TABLE_NAME.to_string(),
744            table_id: NUMBERS_TABLE_ID,
745            table: NumbersTable::table(NUMBERS_TABLE_ID),
746        };
747        catalog_manager.register_table_sync(req).unwrap();
748
749        QueryEngineFactory::new(
750            catalog_manager,
751            None,
752            None,
753            None,
754            None,
755            false,
756            QueryOptions::default(),
757        )
758        .query_engine()
759    }
760
761    #[tokio::test]
762    async fn test_sql_to_plan() {
763        let engine = create_test_engine().await;
764        let sql = "select sum(number) from numbers limit 20";
765
766        let stmt = QueryLanguageParser::parse_sql(sql, &QueryContext::arc()).unwrap();
767        let plan = engine
768            .planner()
769            .plan(&stmt, QueryContext::arc())
770            .await
771            .unwrap();
772
773        assert_eq!(
774            plan.to_string(),
775            r#"Limit: skip=0, fetch=20
776  Projection: sum(numbers.number)
777    Aggregate: groupBy=[[]], aggr=[[sum(numbers.number)]]
778      TableScan: numbers"#
779        );
780    }
781
782    #[tokio::test]
783    async fn test_execute() {
784        let engine = create_test_engine().await;
785        let sql = "select sum(number) from numbers limit 20";
786
787        let stmt = QueryLanguageParser::parse_sql(sql, &QueryContext::arc()).unwrap();
788        let plan = engine
789            .planner()
790            .plan(&stmt, QueryContext::arc())
791            .await
792            .unwrap();
793
794        let output = engine.execute(plan, QueryContext::arc()).await.unwrap();
795
796        match output.data {
797            OutputData::Stream(recordbatch) => {
798                let numbers = util::collect(recordbatch).await.unwrap();
799                assert_eq!(1, numbers.len());
800                assert_eq!(numbers[0].num_columns(), 1);
801                assert_eq!(1, numbers[0].schema.num_columns());
802                assert_eq!(
803                    "sum(numbers.number)",
804                    numbers[0].schema.column_schemas()[0].name
805                );
806
807                let batch = &numbers[0];
808                assert_eq!(1, batch.num_columns());
809                assert_eq!(batch.column(0).len(), 1);
810
811                let expected = Arc::new(UInt64Array::from_iter_values([4950])) as ArrayRef;
812                assert_eq!(batch.column(0), &expected);
813            }
814            _ => unreachable!(),
815        }
816    }
817
818    #[tokio::test]
819    async fn test_read_table() {
820        let engine = create_test_engine().await;
821
822        let engine = engine
823            .as_any()
824            .downcast_ref::<DatafusionQueryEngine>()
825            .unwrap();
826        let query_ctx = Arc::new(QueryContextBuilder::default().build());
827        let table = engine
828            .find_table(
829                &ResolvedTableReference {
830                    catalog: "greptime".into(),
831                    schema: "public".into(),
832                    table: "numbers".into(),
833                },
834                &query_ctx,
835            )
836            .await
837            .unwrap();
838
839        let df = engine.read_table(table).unwrap();
840        let df = df
841            .select_columns(&["number"])
842            .unwrap()
843            .filter(col("number").lt(lit(10)))
844            .unwrap();
845        let batches = df.collect().await.unwrap();
846        assert_eq!(1, batches.len());
847        let batch = &batches[0];
848
849        assert_eq!(1, batch.num_columns());
850        assert_eq!(batch.column(0).len(), 10);
851
852        assert_eq!(
853            Helper::try_into_vector(batch.column(0)).unwrap(),
854            Arc::new(UInt32Vector::from_slice([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])) as VectorRef
855        );
856    }
857
858    #[tokio::test]
859    async fn test_describe() {
860        let engine = create_test_engine().await;
861        let sql = "select sum(number) from numbers limit 20";
862
863        let stmt = QueryLanguageParser::parse_sql(sql, &QueryContext::arc()).unwrap();
864
865        let plan = engine
866            .planner()
867            .plan(&stmt, QueryContext::arc())
868            .await
869            .unwrap();
870
871        let DescribeResult { logical_plan } =
872            engine.describe(plan, QueryContext::arc()).await.unwrap();
873
874        let schema: Schema = logical_plan.schema().clone().try_into().unwrap();
875
876        assert_eq!(
877            schema.column_schemas()[0],
878            ColumnSchema::new(
879                "sum(numbers.number)",
880                ConcreteDataType::uint64_datatype(),
881                true
882            )
883        );
884        assert_eq!(
885            "Limit: skip=0, fetch=20\n  Projection: sum(numbers.number)\n    Aggregate: groupBy=[[]], aggr=[[sum(numbers.number)]]\n      TableScan: numbers",
886            format!("{}", logical_plan.display_indent())
887        );
888    }
889
890    #[tokio::test]
891    async fn test_topk_dynamic_filter_pushdown_reaches_region_scan() {
892        let engine = create_test_engine().await;
893        let engine = engine
894            .as_any()
895            .downcast_ref::<DatafusionQueryEngine>()
896            .unwrap();
897        let engine_ctx = engine.engine_context(QueryContext::arc());
898        let state = engine_ctx.state();
899
900        let schema = Arc::new(datatypes::schema::Schema::new(vec![ColumnSchema::new(
901            "ts",
902            ConcreteDataType::timestamp_millisecond_datatype(),
903            false,
904        )]));
905
906        let mut metadata_builder = RegionMetadataBuilder::new(RegionId::new(1024, 1));
907        metadata_builder
908            .push_column_metadata(ColumnMetadata {
909                column_schema: ColumnSchema::new(
910                    "ts",
911                    ConcreteDataType::timestamp_millisecond_datatype(),
912                    false,
913                )
914                .with_time_index(true),
915                semantic_type: SemanticType::Timestamp,
916                column_id: 1,
917            })
918            .primary_key(vec![]);
919        let metadata = Arc::new(metadata_builder.build().unwrap());
920
921        let update_calls = Arc::new(AtomicUsize::new(0));
922        let last_filter_len = Arc::new(AtomicUsize::new(0));
923        let scanner = Box::new(RecordingScanner::new(
924            schema,
925            metadata,
926            update_calls.clone(),
927            last_filter_len.clone(),
928        ));
929        let scan = Arc::new(RegionScanExec::new(scanner, ScanRequest::default(), None).unwrap());
930
931        let sort_expr = PhysicalSortExpr {
932            expr: Arc::new(Column::new("ts", 0)),
933            options: SortOptions {
934                descending: true,
935                ..Default::default()
936            },
937        };
938        let partition_ranges: Vec<Vec<PartitionRange>> = vec![vec![]];
939        let mut plan: Arc<dyn ExecutionPlan> =
940            Arc::new(PartSortExec::try_new(sort_expr, Some(3), partition_ranges, scan).unwrap());
941
942        for optimizer in state.physical_optimizers() {
943            plan = optimizer.optimize(plan, state.config_options()).unwrap();
944        }
945
946        assert!(update_calls.load(Ordering::Relaxed) > 0);
947        assert!(last_filter_len.load(Ordering::Relaxed) > 0);
948    }
949
950    #[tokio::test]
951    async fn test_join_dynamic_filter_pushdown_reaches_region_scan() {
952        let engine = create_test_engine().await;
953        let engine = engine
954            .as_any()
955            .downcast_ref::<DatafusionQueryEngine>()
956            .unwrap();
957        let engine_ctx = engine.engine_context(QueryContext::arc());
958        let state = engine_ctx.state();
959
960        assert!(
961            state
962                .config_options()
963                .optimizer
964                .enable_join_dynamic_filter_pushdown
965        );
966
967        let schema = Arc::new(datatypes::schema::Schema::new(vec![ColumnSchema::new(
968            "ts",
969            ConcreteDataType::timestamp_millisecond_datatype(),
970            false,
971        )]));
972
973        let mut left_metadata_builder = RegionMetadataBuilder::new(RegionId::new(2048, 1));
974        left_metadata_builder
975            .push_column_metadata(ColumnMetadata {
976                column_schema: ColumnSchema::new(
977                    "ts",
978                    ConcreteDataType::timestamp_millisecond_datatype(),
979                    false,
980                )
981                .with_time_index(true),
982                semantic_type: SemanticType::Timestamp,
983                column_id: 1,
984            })
985            .primary_key(vec![]);
986        let left_metadata = Arc::new(left_metadata_builder.build().unwrap());
987
988        let mut right_metadata_builder = RegionMetadataBuilder::new(RegionId::new(2048, 2));
989        right_metadata_builder
990            .push_column_metadata(ColumnMetadata {
991                column_schema: ColumnSchema::new(
992                    "ts",
993                    ConcreteDataType::timestamp_millisecond_datatype(),
994                    false,
995                )
996                .with_time_index(true),
997                semantic_type: SemanticType::Timestamp,
998                column_id: 1,
999            })
1000            .primary_key(vec![]);
1001        let right_metadata = Arc::new(right_metadata_builder.build().unwrap());
1002
1003        let left_update_calls = Arc::new(AtomicUsize::new(0));
1004        let left_last_filter_len = Arc::new(AtomicUsize::new(0));
1005        let right_update_calls = Arc::new(AtomicUsize::new(0));
1006        let right_last_filter_len = Arc::new(AtomicUsize::new(0));
1007
1008        let left_scan = Arc::new(
1009            RegionScanExec::new(
1010                Box::new(RecordingScanner::new(
1011                    schema.clone(),
1012                    left_metadata,
1013                    left_update_calls.clone(),
1014                    left_last_filter_len.clone(),
1015                )),
1016                ScanRequest::default(),
1017                None,
1018            )
1019            .unwrap(),
1020        );
1021        let right_scan = Arc::new(
1022            RegionScanExec::new(
1023                Box::new(RecordingScanner::new(
1024                    schema,
1025                    right_metadata,
1026                    right_update_calls.clone(),
1027                    right_last_filter_len.clone(),
1028                )),
1029                ScanRequest::default(),
1030                None,
1031            )
1032            .unwrap(),
1033        );
1034
1035        let on: JoinOn = vec![(
1036            Arc::new(Column::new("ts", 0)) as Arc<dyn PhysicalExpr>,
1037            Arc::new(Column::new("ts", 0)) as Arc<dyn PhysicalExpr>,
1038        )];
1039
1040        let mut plan: Arc<dyn ExecutionPlan> = Arc::new(
1041            HashJoinExec::try_new(
1042                left_scan,
1043                right_scan,
1044                on,
1045                None,
1046                &JoinType::Inner,
1047                None,
1048                PartitionMode::CollectLeft,
1049                NullEquality::NullEqualsNull,
1050                false,
1051            )
1052            .unwrap(),
1053        );
1054
1055        for optimizer in state.physical_optimizers() {
1056            plan = optimizer.optimize(plan, state.config_options()).unwrap();
1057        }
1058
1059        assert!(left_update_calls.load(Ordering::Relaxed) > 0);
1060        assert_eq!(0, left_last_filter_len.load(Ordering::Relaxed));
1061        assert!(right_update_calls.load(Ordering::Relaxed) > 0);
1062        assert!(right_last_filter_len.load(Ordering::Relaxed) > 0);
1063    }
1064}