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 json_expr_planner;
19mod planner;
20
21use std::any::Any;
22use std::collections::HashMap;
23use std::sync::Arc;
24
25use async_trait::async_trait;
26use common_base::Plugins;
27use common_catalog::consts::is_readonly_schema;
28use common_error::ext::BoxedError;
29use common_function::function::FunctionContext;
30use common_function::function_factory::ScalarFunctionFactory;
31use common_query::{Output, OutputData, OutputMeta};
32use common_recordbatch::adapter::RecordBatchStreamAdapter;
33use common_recordbatch::{EmptyRecordBatchStream, SendableRecordBatchStream};
34use common_telemetry::tracing;
35use datafusion::catalog::TableFunction;
36use datafusion::dataframe::DataFrame;
37use datafusion::physical_plan::ExecutionPlan;
38use datafusion::physical_plan::analyze::AnalyzeExec;
39use datafusion::physical_plan::coalesce_partitions::CoalescePartitionsExec;
40use datafusion_common::ResolvedTableReference;
41use datafusion_expr::{
42    AggregateUDF, DmlStatement, LogicalPlan as DfLogicalPlan, LogicalPlan, WindowUDF, WriteOp,
43};
44use datatypes::prelude::VectorRef;
45use datatypes::schema::Schema;
46use futures_util::StreamExt;
47use session::context::QueryContextRef;
48use snafu::{OptionExt, ResultExt, ensure};
49use sqlparser::ast::AnalyzeFormat;
50use table::TableRef;
51use table::requests::{DeleteRequest, InsertRequest};
52use table::table::scan::{REGION_SCAN_EXEC_NAME, RegionScanExec};
53use tracing::Span;
54
55use crate::analyze::DistAnalyzeExec;
56pub use crate::datafusion::planner::DfContextProviderAdapter;
57use crate::dist_plan::{
58    DistPlannerOptions, MergeScanLogicalPlan, RemoteDynFilterReceiverInjectorRef,
59};
60use crate::error::{
61    CatalogSnafu, CreateRecordBatchSnafu, MissingTableMutationHandlerSnafu,
62    MissingTimestampColumnSnafu, QueryExecutionSnafu, Result, TableMutationSnafu,
63    TableNotFoundSnafu, TableReadOnlySnafu, UnsupportedExprSnafu,
64};
65use crate::executor::QueryExecutor;
66use crate::metrics::{
67    OnDone, QUERY_STAGE_ELAPSED, maybe_attach_region_watermark_metrics,
68    should_collect_region_watermark_from_query_ctx,
69};
70use crate::physical_wrapper::PhysicalPlanWrapperRef;
71use crate::planner::{DfLogicalPlanner, LogicalPlanner};
72use crate::query_engine::{DescribeResult, QueryEngineContext, QueryEngineState};
73use crate::{QueryEngine, metrics};
74
75/// Query parallelism hint key.
76/// This hint can be set in the query context to control the parallelism of the query execution.
77pub const QUERY_PARALLELISM_HINT: &str = "query_parallelism";
78
79/// Whether to fallback to the original plan when failed to push down.
80pub const QUERY_FALLBACK_HINT: &str = "query_fallback";
81
82fn query_load_region_id(plan: &Arc<dyn ExecutionPlan>) -> Option<u64> {
83    let mut region_id = None;
84    let mut stack = vec![plan.clone()];
85
86    while let Some(plan) = stack.pop() {
87        if plan.name() == REGION_SCAN_EXEC_NAME
88            && let Some(scan) = plan.as_any().downcast_ref::<RegionScanExec>()
89            && let Some(scan_region_id) = scan.query_load_region_id()
90        {
91            match region_id {
92                Some(region_id) if region_id != scan_region_id => return None,
93                Some(_) => {}
94                None => region_id = Some(scan_region_id),
95            }
96        }
97        stack.extend(plan.children().into_iter().cloned());
98    }
99
100    region_id
101}
102
103pub struct DatafusionQueryEngine {
104    state: Arc<QueryEngineState>,
105    plugins: Plugins,
106}
107
108impl DatafusionQueryEngine {
109    pub fn new(state: Arc<QueryEngineState>, plugins: Plugins) -> Self {
110        Self { state, plugins }
111    }
112
113    #[tracing::instrument(skip_all)]
114    async fn exec_query_plan(
115        &self,
116        plan: LogicalPlan,
117        query_ctx: QueryContextRef,
118    ) -> Result<Output> {
119        let mut ctx = self.engine_context(query_ctx.clone());
120        let plan = if let Some(receiver_injector) =
121            self.plugins.get::<RemoteDynFilterReceiverInjectorRef>()
122        {
123            receiver_injector.maybe_inject(plan, query_ctx.clone())
124        } else {
125            plan
126        };
127
128        // `create_physical_plan` will optimize logical plan internally
129        let physical_plan = self.create_physical_plan(&mut ctx, &plan).await?;
130        let physical_plan = self.optimize_physical_plan(&mut ctx, physical_plan)?;
131        let physical_plan = if let Some(wrapper) = self.plugins.get::<PhysicalPlanWrapperRef>() {
132            wrapper.wrap(physical_plan, query_ctx)
133        } else {
134            physical_plan
135        };
136
137        let stream = self.execute_stream(&ctx, &physical_plan)?;
138
139        Ok(Output::new(
140            OutputData::Stream(stream),
141            OutputMeta::new_with_plan(physical_plan),
142        ))
143    }
144
145    #[tracing::instrument(skip_all)]
146    async fn exec_dml_statement(
147        &self,
148        dml: DmlStatement,
149        query_ctx: QueryContextRef,
150    ) -> Result<Output> {
151        ensure!(
152            matches!(dml.op, WriteOp::Insert(_) | WriteOp::Delete),
153            UnsupportedExprSnafu {
154                name: format!("DML op {}", dml.op),
155            }
156        );
157
158        let _timer = QUERY_STAGE_ELAPSED
159            .with_label_values(&[dml.op.name()])
160            .start_timer();
161
162        let default_catalog = &query_ctx.current_catalog().to_owned();
163        let default_schema = &query_ctx.current_schema();
164        let table_name = dml.table_name.resolve(default_catalog, default_schema);
165        let table = self.find_table(&table_name, &query_ctx).await?;
166
167        let Output { data, meta } = self
168            .exec_query_plan((*dml.input).clone(), query_ctx.clone())
169            .await?;
170        let mut stream = match data {
171            OutputData::RecordBatches(batches) => batches.as_stream(),
172            OutputData::Stream(stream) => stream,
173            _ => unreachable!(),
174        };
175
176        let mut affected_rows = 0;
177        let mut insert_cost = 0;
178
179        while let Some(batch) = stream.next().await {
180            let batch = batch.context(CreateRecordBatchSnafu)?;
181            let column_vectors = batch
182                .column_vectors(&table_name.to_string(), table.schema())
183                .map_err(BoxedError::new)
184                .context(QueryExecutionSnafu)?;
185
186            match dml.op {
187                WriteOp::Insert(_) => {
188                    // We ignore the insert op.
189                    let output = self
190                        .insert(&table_name, column_vectors, query_ctx.clone())
191                        .await?;
192                    let (rows, cost) = output.extract_rows_and_cost();
193                    affected_rows += rows;
194                    insert_cost += cost;
195                }
196                WriteOp::Delete => {
197                    affected_rows += self
198                        .delete(&table_name, &table, column_vectors, query_ctx.clone())
199                        .await?;
200                }
201                _ => unreachable!("guarded by the 'ensure!' at the beginning"),
202            }
203        }
204        Ok(Output::new(
205            OutputData::AffectedRows(affected_rows),
206            OutputMeta::new(meta.plan, insert_cost),
207        ))
208    }
209
210    #[tracing::instrument(skip_all)]
211    async fn delete(
212        &self,
213        table_name: &ResolvedTableReference,
214        table: &TableRef,
215        column_vectors: HashMap<String, VectorRef>,
216        query_ctx: QueryContextRef,
217    ) -> Result<usize> {
218        let catalog_name = table_name.catalog.to_string();
219        let schema_name = table_name.schema.to_string();
220        let table_name = table_name.table.to_string();
221        let table_schema = table.schema();
222
223        ensure!(
224            !is_readonly_schema(&schema_name),
225            TableReadOnlySnafu { table: table_name }
226        );
227
228        let ts_column = table_schema
229            .timestamp_column()
230            .map(|x| &x.name)
231            .with_context(|| MissingTimestampColumnSnafu {
232                table_name: table_name.clone(),
233            })?;
234
235        let table_info = table.table_info();
236        let rowkey_columns = table_info
237            .meta
238            .row_key_column_names()
239            .collect::<Vec<&String>>();
240        let column_vectors = column_vectors
241            .into_iter()
242            .filter(|x| &x.0 == ts_column || rowkey_columns.contains(&&x.0))
243            .collect::<HashMap<_, _>>();
244
245        let request = DeleteRequest {
246            catalog_name,
247            schema_name,
248            table_name,
249            key_column_values: column_vectors,
250        };
251
252        self.state
253            .table_mutation_handler()
254            .context(MissingTableMutationHandlerSnafu)?
255            .delete(request, query_ctx)
256            .await
257            .context(TableMutationSnafu)
258    }
259
260    #[tracing::instrument(skip_all)]
261    async fn insert(
262        &self,
263        table_name: &ResolvedTableReference,
264        column_vectors: HashMap<String, VectorRef>,
265        query_ctx: QueryContextRef,
266    ) -> Result<Output> {
267        let catalog_name = table_name.catalog.to_string();
268        let schema_name = table_name.schema.to_string();
269        let table_name = table_name.table.to_string();
270
271        ensure!(
272            !is_readonly_schema(&schema_name),
273            TableReadOnlySnafu { table: table_name }
274        );
275
276        let request = InsertRequest {
277            catalog_name,
278            schema_name,
279            table_name,
280            columns_values: column_vectors,
281        };
282
283        self.state
284            .table_mutation_handler()
285            .context(MissingTableMutationHandlerSnafu)?
286            .insert(request, query_ctx)
287            .await
288            .context(TableMutationSnafu)
289    }
290
291    async fn find_table(
292        &self,
293        table_name: &ResolvedTableReference,
294        query_context: &QueryContextRef,
295    ) -> Result<TableRef> {
296        let catalog_name = table_name.catalog.as_ref();
297        let schema_name = table_name.schema.as_ref();
298        let table_name = table_name.table.as_ref();
299
300        self.state
301            .catalog_manager()
302            .table(catalog_name, schema_name, table_name, Some(query_context))
303            .await
304            .context(CatalogSnafu)?
305            .with_context(|| TableNotFoundSnafu { table: table_name })
306    }
307
308    #[tracing::instrument(skip_all)]
309    async fn create_physical_plan(
310        &self,
311        ctx: &mut QueryEngineContext,
312        logical_plan: &LogicalPlan,
313    ) -> Result<Arc<dyn ExecutionPlan>> {
314        /// Only print context on panic, to avoid cluttering logs.
315        ///
316        /// TODO(discord9): remove this once we catch the bug
317        #[derive(Debug)]
318        struct PanicLogger<'a> {
319            input_logical_plan: &'a LogicalPlan,
320            after_analyze: Option<LogicalPlan>,
321            after_optimize: Option<LogicalPlan>,
322            phy_plan: Option<Arc<dyn ExecutionPlan>>,
323        }
324        impl Drop for PanicLogger<'_> {
325            fn drop(&mut self) {
326                if std::thread::panicking() {
327                    common_telemetry::error!(
328                        "Panic while creating physical plan, input logical plan: {:?}, after analyze: {:?}, after optimize: {:?}, final physical plan: {:?}",
329                        self.input_logical_plan,
330                        self.after_analyze,
331                        self.after_optimize,
332                        self.phy_plan
333                    );
334                }
335            }
336        }
337
338        let mut logger = PanicLogger {
339            input_logical_plan: logical_plan,
340            after_analyze: None,
341            after_optimize: None,
342            phy_plan: None,
343        };
344
345        let _timer = metrics::CREATE_PHYSICAL_ELAPSED.start_timer();
346        let state = ctx.state();
347
348        common_telemetry::debug!("Create physical plan, input plan: {logical_plan}");
349
350        // special handle EXPLAIN plan
351        if matches!(logical_plan, DfLogicalPlan::Explain(_)) {
352            return state
353                .create_physical_plan(logical_plan)
354                .await
355                .map_err(Into::into);
356        }
357
358        // analyze first
359        let analyzed_plan = state.analyzer().execute_and_check(
360            logical_plan.clone(),
361            state.config_options(),
362            |_, _| {},
363        )?;
364
365        logger.after_analyze = Some(analyzed_plan.clone());
366
367        common_telemetry::debug!("Create physical plan, analyzed plan: {analyzed_plan}");
368
369        // skip optimize for MergeScan
370        let optimized_plan = if let DfLogicalPlan::Extension(ext) = &analyzed_plan
371            && ext.node.name() == MergeScanLogicalPlan::name()
372        {
373            analyzed_plan.clone()
374        } else {
375            state
376                .optimizer()
377                .optimize(analyzed_plan, state, |_, _| {})?
378        };
379
380        common_telemetry::debug!("Create physical plan, optimized plan: {optimized_plan}");
381        logger.after_optimize = Some(optimized_plan.clone());
382
383        let physical_plan = state
384            .query_planner()
385            .create_physical_plan(&optimized_plan, state)
386            .await?;
387
388        logger.phy_plan = Some(physical_plan.clone());
389        drop(logger);
390        Ok(physical_plan)
391    }
392
393    #[tracing::instrument(skip_all)]
394    fn optimize_physical_plan(
395        &self,
396        ctx: &mut QueryEngineContext,
397        plan: Arc<dyn ExecutionPlan>,
398    ) -> Result<Arc<dyn ExecutionPlan>> {
399        let _timer = metrics::OPTIMIZE_PHYSICAL_ELAPSED.start_timer();
400
401        // TODO(ruihang): `self.create_physical_plan()` already optimize the plan, check
402        // if we need to optimize it again here.
403        // let state = ctx.state();
404        // let config = state.config_options();
405
406        // skip optimize AnalyzeExec plan
407        let optimized_plan = if let Some(analyze_plan) = plan.as_any().downcast_ref::<AnalyzeExec>()
408        {
409            let format = if let Some(format) = ctx.query_ctx().explain_format()
410                && format.to_lowercase() == "json"
411            {
412                AnalyzeFormat::JSON
413            } else {
414                AnalyzeFormat::TEXT
415            };
416            // Sets the verbose flag of the query context.
417            // The MergeScanExec plan uses the verbose flag to determine whether to print the plan in verbose mode.
418            ctx.query_ctx().set_explain_verbose(analyze_plan.verbose());
419
420            Arc::new(DistAnalyzeExec::new(
421                analyze_plan.input().clone(),
422                analyze_plan.verbose(),
423                format,
424            ))
425            // let mut new_plan = analyze_plan.input().clone();
426            // for optimizer in state.physical_optimizers() {
427            //     new_plan = optimizer
428            //         .optimize(new_plan, config)
429            //         .context(DataFusionSnafu)?;
430            // }
431            // Arc::new(DistAnalyzeExec::new(new_plan))
432        } else {
433            plan
434            // let mut new_plan = plan;
435            // for optimizer in state.physical_optimizers() {
436            //     new_plan = optimizer
437            //         .optimize(new_plan, config)
438            //         .context(DataFusionSnafu)?;
439            // }
440            // new_plan
441        };
442
443        Ok(optimized_plan)
444    }
445}
446
447#[async_trait]
448impl QueryEngine for DatafusionQueryEngine {
449    fn as_any(&self) -> &dyn Any {
450        self
451    }
452
453    fn planner(&self) -> Arc<dyn LogicalPlanner> {
454        Arc::new(DfLogicalPlanner::new(self.state.clone()))
455    }
456
457    fn name(&self) -> &str {
458        "datafusion"
459    }
460
461    async fn describe(
462        &self,
463        plan: LogicalPlan,
464        _query_ctx: QueryContextRef,
465    ) -> Result<DescribeResult> {
466        Ok(DescribeResult { logical_plan: plan })
467    }
468
469    async fn execute(&self, plan: LogicalPlan, query_ctx: QueryContextRef) -> Result<Output> {
470        match plan {
471            LogicalPlan::Dml(dml) => self.exec_dml_statement(dml, query_ctx).await,
472            _ => self.exec_query_plan(plan, query_ctx).await,
473        }
474    }
475
476    /// Note in SQL queries, aggregate names are looked up using
477    /// lowercase unless the query uses quotes. For example,
478    ///
479    /// `SELECT MY_UDAF(x)...` will look for an aggregate named `"my_udaf"`
480    /// `SELECT "my_UDAF"(x)` will look for an aggregate named `"my_UDAF"`
481    ///
482    /// So it's better to make UDAF name lowercase when creating one.
483    fn register_aggregate_function(&self, func: AggregateUDF) {
484        self.state.register_aggr_function(func);
485    }
486
487    /// Register an scalar function.
488    /// Will override if the function with same name is already registered.
489    fn register_scalar_function(&self, func: ScalarFunctionFactory) {
490        self.state.register_scalar_function(func);
491    }
492
493    fn register_table_function(&self, func: Arc<TableFunction>) {
494        self.state.register_table_function(func);
495    }
496
497    fn register_window_function(&self, func: WindowUDF) {
498        self.state.register_window_function(func);
499    }
500
501    fn read_table(&self, table: TableRef) -> Result<DataFrame> {
502        self.state.read_table(table).map_err(Into::into)
503    }
504
505    fn engine_context(&self, query_ctx: QueryContextRef) -> QueryEngineContext {
506        let mut state = self.state.session_state();
507        state.config_mut().set_extension(query_ctx.clone());
508        state.config_mut().set_extension(self.state.clone());
509        // note that hints in "x-greptime-hints" is automatically parsed
510        // and set to query context's extension, so we can get it from query context.
511        if let Some(parallelism) = query_ctx.extension(QUERY_PARALLELISM_HINT) {
512            if let Ok(n) = parallelism.parse::<u64>() {
513                if n > 0 {
514                    let new_cfg = state.config().clone().with_target_partitions(n as usize);
515                    *state.config_mut() = new_cfg;
516                }
517            } else {
518                common_telemetry::warn!(
519                    "Failed to parse query_parallelism: {}, using default value",
520                    parallelism
521                );
522            }
523        }
524
525        // configure execution options
526        state.config_mut().options_mut().execution.time_zone =
527            Some(query_ctx.timezone().to_string());
528
529        // usually it's impossible to have both `set variable` set by sql client and
530        // hint in header by grpc client, so only need to deal with them separately
531        if query_ctx.configuration_parameter().allow_query_fallback() {
532            state
533                .config_mut()
534                .options_mut()
535                .extensions
536                .insert(DistPlannerOptions {
537                    allow_query_fallback: true,
538                });
539        } else if let Some(fallback) = query_ctx.extension(QUERY_FALLBACK_HINT) {
540            // also check the query context for fallback hint
541            // if it is set, we will enable the fallback
542            if fallback.to_lowercase().parse::<bool>().unwrap_or(false) {
543                state
544                    .config_mut()
545                    .options_mut()
546                    .extensions
547                    .insert(DistPlannerOptions {
548                        allow_query_fallback: true,
549                    });
550            }
551        }
552
553        state
554            .config_mut()
555            .options_mut()
556            .extensions
557            .insert(FunctionContext {
558                query_ctx: query_ctx.clone(),
559                state: self.engine_state().function_state(),
560            });
561
562        let config_options = state.config_options().clone();
563        let _ = state
564            .execution_props_mut()
565            .config_options
566            .insert(config_options);
567
568        QueryEngineContext::new(state, query_ctx)
569    }
570
571    fn engine_state(&self) -> &QueryEngineState {
572        &self.state
573    }
574}
575
576impl QueryExecutor for DatafusionQueryEngine {
577    #[tracing::instrument(skip_all)]
578    fn execute_stream(
579        &self,
580        ctx: &QueryEngineContext,
581        plan: &Arc<dyn ExecutionPlan>,
582    ) -> Result<SendableRecordBatchStream> {
583        let query_ctx = ctx.query_ctx();
584        let explain_verbose = query_ctx.explain_verbose();
585        let should_collect_region_watermark =
586            should_collect_region_watermark_from_query_ctx(&query_ctx)?;
587        let output_partitions = plan.properties().output_partitioning().partition_count();
588        if explain_verbose {
589            common_telemetry::info!("Executing query plan, output_partitions: {output_partitions}");
590        }
591
592        let exec_timer = metrics::EXEC_PLAN_ELAPSED.start_timer();
593        let task_ctx = ctx.build_task_ctx();
594        let span = Span::current();
595
596        match plan.properties().output_partitioning().partition_count() {
597            0 => {
598                let schema = Arc::new(
599                    Schema::try_from(plan.schema())
600                        .map_err(BoxedError::new)
601                        .context(QueryExecutionSnafu)?,
602                );
603                Ok(Box::pin(EmptyRecordBatchStream::new(schema)))
604            }
605            1 => {
606                let df_stream = plan.execute(0, task_ctx)?;
607                let mut stream = RecordBatchStreamAdapter::try_new_with_span(df_stream, span)
608                    .context(error::ConvertDfRecordBatchStreamSnafu)
609                    .map_err(BoxedError::new)
610                    .context(QueryExecutionSnafu)?;
611                stream.set_metrics2(plan.clone());
612                stream.set_query_load_region_id(query_load_region_id(plan));
613                stream.set_explain_verbose(explain_verbose);
614                let stream = OnDone::new(Box::pin(stream), move || {
615                    let exec_cost = exec_timer.stop_and_record();
616                    if explain_verbose {
617                        common_telemetry::info!(
618                            "DatafusionQueryEngine execute 1 stream, cost: {:?}s",
619                            exec_cost,
620                        );
621                    }
622                });
623                Ok(maybe_attach_region_watermark_metrics(
624                    Box::pin(stream),
625                    plan.clone(),
626                    should_collect_region_watermark,
627                ))
628            }
629            _ => {
630                // merge into a single partition
631                let merged_plan = CoalescePartitionsExec::new(plan.clone());
632                // CoalescePartitionsExec must produce a single partition
633                assert_eq!(
634                    1,
635                    merged_plan
636                        .properties()
637                        .output_partitioning()
638                        .partition_count()
639                );
640                let df_stream = merged_plan.execute(0, task_ctx)?;
641                let mut stream = RecordBatchStreamAdapter::try_new_with_span(df_stream, span)
642                    .context(error::ConvertDfRecordBatchStreamSnafu)
643                    .map_err(BoxedError::new)
644                    .context(QueryExecutionSnafu)?;
645                stream.set_metrics2(plan.clone());
646                stream.set_query_load_region_id(query_load_region_id(plan));
647                stream.set_explain_verbose(explain_verbose);
648                let stream = OnDone::new(Box::pin(stream), move || {
649                    let exec_cost = exec_timer.stop_and_record();
650                    if explain_verbose {
651                        common_telemetry::info!(
652                            "DatafusionQueryEngine execute {output_partitions} stream, cost: {:?}s",
653                            exec_cost
654                        );
655                    }
656                });
657                Ok(maybe_attach_region_watermark_metrics(
658                    Box::pin(stream),
659                    plan.clone(),
660                    should_collect_region_watermark,
661                ))
662            }
663        }
664    }
665}
666
667#[cfg(test)]
668mod tests {
669    use std::fmt;
670    use std::sync::Arc;
671    use std::sync::atomic::{AtomicUsize, Ordering};
672
673    use api::v1::SemanticType;
674    use arrow::array::{ArrayRef, UInt64Array};
675    use arrow_schema::SortOptions;
676    use catalog::RegisterTableRequest;
677    use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, NUMBERS_TABLE_ID};
678    use common_error::ext::BoxedError;
679    use common_recordbatch::{EmptyRecordBatchStream, SendableRecordBatchStream, util};
680    use datafusion::physical_plan::display::{DisplayAs, DisplayFormatType};
681    use datafusion::physical_plan::expressions::PhysicalSortExpr;
682    use datafusion::physical_plan::joins::{HashJoinExec, JoinOn, PartitionMode};
683    use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet;
684    use datafusion::physical_plan::{ExecutionPlan, PhysicalExpr};
685    use datafusion::prelude::{col, lit};
686    use datafusion_common::{JoinType, NullEquality};
687    use datafusion_physical_expr::expressions::Column;
688    use datatypes::prelude::ConcreteDataType;
689    use datatypes::schema::{ColumnSchema, SchemaRef};
690    use datatypes::vectors::{Helper, UInt32Vector, VectorRef};
691    use session::context::{QueryContext, QueryContextBuilder};
692    use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder, RegionMetadataRef};
693    use store_api::region_engine::{
694        PartitionRange, PrepareRequest, QueryScanContext, RegionScanner, ScannerProperties,
695    };
696    use store_api::storage::{RegionId, ScanRequest};
697    use table::table::numbers::{NUMBERS_TABLE_NAME, NumbersTable};
698    use table::table::scan::RegionScanExec;
699
700    use super::*;
701    use crate::options::QueryOptions;
702    use crate::parser::QueryLanguageParser;
703    use crate::part_sort::PartSortExec;
704    use crate::query_engine::{QueryEngineFactory, QueryEngineRef};
705
706    #[derive(Debug)]
707    struct RecordingScanner {
708        schema: SchemaRef,
709        metadata: RegionMetadataRef,
710        properties: ScannerProperties,
711        update_calls: Arc<AtomicUsize>,
712        last_filter_len: Arc<AtomicUsize>,
713    }
714
715    impl RecordingScanner {
716        fn new(
717            schema: SchemaRef,
718            metadata: RegionMetadataRef,
719            update_calls: Arc<AtomicUsize>,
720            last_filter_len: Arc<AtomicUsize>,
721        ) -> Self {
722            Self {
723                schema,
724                metadata,
725                properties: ScannerProperties::default(),
726                update_calls,
727                last_filter_len,
728            }
729        }
730    }
731
732    impl RegionScanner for RecordingScanner {
733        fn name(&self) -> &str {
734            "RecordingScanner"
735        }
736
737        fn properties(&self) -> &ScannerProperties {
738            &self.properties
739        }
740
741        fn schema(&self) -> SchemaRef {
742            self.schema.clone()
743        }
744
745        fn metadata(&self) -> RegionMetadataRef {
746            self.metadata.clone()
747        }
748
749        fn prepare(&mut self, request: PrepareRequest) -> std::result::Result<(), BoxedError> {
750            self.properties.prepare(request);
751            Ok(())
752        }
753
754        fn scan_partition(
755            &self,
756            _ctx: &QueryScanContext,
757            _metrics_set: &ExecutionPlanMetricsSet,
758            _partition: usize,
759        ) -> std::result::Result<SendableRecordBatchStream, BoxedError> {
760            Ok(Box::pin(EmptyRecordBatchStream::new(self.schema.clone())))
761        }
762
763        fn has_predicate_without_region(&self) -> bool {
764            true
765        }
766
767        fn add_dyn_filter_to_predicate(
768            &mut self,
769            filter_exprs: Vec<Arc<dyn PhysicalExpr>>,
770        ) -> Vec<bool> {
771            self.update_calls.fetch_add(1, Ordering::Relaxed);
772            self.last_filter_len
773                .store(filter_exprs.len(), Ordering::Relaxed);
774            vec![true; filter_exprs.len()]
775        }
776
777        fn set_logical_region(&mut self, logical_region: bool) {
778            self.properties.set_logical_region(logical_region);
779        }
780
781        fn set_query_load_region_id(&mut self, region_id: store_api::storage::RegionId) {
782            self.properties.set_query_load_region_id(region_id);
783        }
784    }
785
786    impl DisplayAs for RecordingScanner {
787        fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter<'_>) -> fmt::Result {
788            write!(f, "RecordingScanner")
789        }
790    }
791
792    fn build_query_load_region_scan(
793        query_load_region_id: Option<RegionId>,
794    ) -> Arc<dyn ExecutionPlan> {
795        let schema = Arc::new(datatypes::schema::Schema::new(vec![ColumnSchema::new(
796            "ts",
797            ConcreteDataType::timestamp_millisecond_datatype(),
798            false,
799        )]));
800
801        let mut metadata_builder = RegionMetadataBuilder::new(RegionId::new(1024, 1));
802        metadata_builder
803            .push_column_metadata(ColumnMetadata {
804                column_schema: ColumnSchema::new(
805                    "ts",
806                    ConcreteDataType::timestamp_millisecond_datatype(),
807                    false,
808                )
809                .with_time_index(true),
810                semantic_type: SemanticType::Timestamp,
811                column_id: 1,
812            })
813            .primary_key(vec![]);
814        let metadata = Arc::new(metadata_builder.build().unwrap());
815        let mut scanner = RecordingScanner::new(
816            schema,
817            metadata,
818            Arc::new(AtomicUsize::new(0)),
819            Arc::new(AtomicUsize::new(0)),
820        );
821        if let Some(region_id) = query_load_region_id {
822            scanner.set_query_load_region_id(region_id);
823        }
824
825        Arc::new(RegionScanExec::new(Box::new(scanner), ScanRequest::default(), None).unwrap())
826    }
827
828    #[test]
829    fn query_load_region_id_ignores_scans_without_region_id() {
830        let query_load_region_id = RegionId::new(1024, 42);
831        let scan_without_region_id = build_query_load_region_scan(None);
832        let scan_with_region_id = build_query_load_region_scan(Some(query_load_region_id));
833        let on: JoinOn = vec![(
834            Arc::new(Column::new("ts", 0)) as Arc<dyn PhysicalExpr>,
835            Arc::new(Column::new("ts", 0)) as Arc<dyn PhysicalExpr>,
836        )];
837        let plan: Arc<dyn ExecutionPlan> = Arc::new(
838            HashJoinExec::try_new(
839                scan_without_region_id,
840                scan_with_region_id,
841                on,
842                None,
843                &JoinType::Inner,
844                None,
845                PartitionMode::CollectLeft,
846                NullEquality::NullEqualsNull,
847                false,
848            )
849            .unwrap(),
850        );
851
852        assert_eq!(
853            super::query_load_region_id(&plan),
854            Some(query_load_region_id.as_u64())
855        );
856    }
857
858    async fn create_test_engine() -> QueryEngineRef {
859        let catalog_manager = catalog::memory::new_memory_catalog_manager().unwrap();
860        let req = RegisterTableRequest {
861            catalog: DEFAULT_CATALOG_NAME.to_string(),
862            schema: DEFAULT_SCHEMA_NAME.to_string(),
863            table_name: NUMBERS_TABLE_NAME.to_string(),
864            table_id: NUMBERS_TABLE_ID,
865            table: NumbersTable::table(NUMBERS_TABLE_ID),
866        };
867        catalog_manager.register_table_sync(req).unwrap();
868
869        QueryEngineFactory::new(
870            catalog_manager,
871            None,
872            None,
873            None,
874            None,
875            false,
876            QueryOptions::default(),
877        )
878        .query_engine()
879    }
880
881    #[tokio::test]
882    async fn test_sql_to_plan() {
883        let engine = create_test_engine().await;
884        let sql = "select sum(number) from numbers limit 20";
885
886        let stmt = QueryLanguageParser::parse_sql(sql, &QueryContext::arc()).unwrap();
887        let plan = engine
888            .planner()
889            .plan(&stmt, QueryContext::arc())
890            .await
891            .unwrap();
892
893        assert_eq!(
894            plan.to_string(),
895            r#"Limit: skip=0, fetch=20
896  Projection: sum(numbers.number)
897    Aggregate: groupBy=[[]], aggr=[[sum(numbers.number)]]
898      TableScan: numbers"#
899        );
900    }
901
902    #[tokio::test]
903    async fn test_execute() {
904        let engine = create_test_engine().await;
905        let sql = "select sum(number) from numbers limit 20";
906
907        let stmt = QueryLanguageParser::parse_sql(sql, &QueryContext::arc()).unwrap();
908        let plan = engine
909            .planner()
910            .plan(&stmt, QueryContext::arc())
911            .await
912            .unwrap();
913
914        let output = engine.execute(plan, QueryContext::arc()).await.unwrap();
915
916        match output.data {
917            OutputData::Stream(recordbatch) => {
918                let numbers = util::collect(recordbatch).await.unwrap();
919                assert_eq!(1, numbers.len());
920                assert_eq!(numbers[0].num_columns(), 1);
921                assert_eq!(1, numbers[0].schema.num_columns());
922                assert_eq!(
923                    "sum(numbers.number)",
924                    numbers[0].schema.column_schemas()[0].name
925                );
926
927                let batch = &numbers[0];
928                assert_eq!(1, batch.num_columns());
929                assert_eq!(batch.column(0).len(), 1);
930
931                let expected = Arc::new(UInt64Array::from_iter_values([4950])) as ArrayRef;
932                assert_eq!(batch.column(0), &expected);
933            }
934            _ => unreachable!(),
935        }
936    }
937
938    #[tokio::test]
939    async fn test_read_table() {
940        let engine = create_test_engine().await;
941
942        let engine = engine
943            .as_any()
944            .downcast_ref::<DatafusionQueryEngine>()
945            .unwrap();
946        let query_ctx = Arc::new(QueryContextBuilder::default().build());
947        let table = engine
948            .find_table(
949                &ResolvedTableReference {
950                    catalog: "greptime".into(),
951                    schema: "public".into(),
952                    table: "numbers".into(),
953                },
954                &query_ctx,
955            )
956            .await
957            .unwrap();
958
959        let df = engine.read_table(table).unwrap();
960        let df = df
961            .select_columns(&["number"])
962            .unwrap()
963            .filter(col("number").lt(lit(10)))
964            .unwrap();
965        let batches = df.collect().await.unwrap();
966        assert_eq!(1, batches.len());
967        let batch = &batches[0];
968
969        assert_eq!(1, batch.num_columns());
970        assert_eq!(batch.column(0).len(), 10);
971
972        assert_eq!(
973            Helper::try_into_vector(batch.column(0)).unwrap(),
974            Arc::new(UInt32Vector::from_slice([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])) as VectorRef
975        );
976    }
977
978    #[tokio::test]
979    async fn test_describe() {
980        let engine = create_test_engine().await;
981        let sql = "select sum(number) from numbers limit 20";
982
983        let stmt = QueryLanguageParser::parse_sql(sql, &QueryContext::arc()).unwrap();
984
985        let plan = engine
986            .planner()
987            .plan(&stmt, QueryContext::arc())
988            .await
989            .unwrap();
990
991        let DescribeResult { logical_plan } =
992            engine.describe(plan, QueryContext::arc()).await.unwrap();
993
994        let schema: Schema = logical_plan.schema().clone().try_into().unwrap();
995
996        assert_eq!(
997            schema.column_schemas()[0],
998            ColumnSchema::new(
999                "sum(numbers.number)",
1000                ConcreteDataType::uint64_datatype(),
1001                true
1002            )
1003        );
1004        assert_eq!(
1005            "Limit: skip=0, fetch=20\n  Projection: sum(numbers.number)\n    Aggregate: groupBy=[[]], aggr=[[sum(numbers.number)]]\n      TableScan: numbers",
1006            format!("{}", logical_plan.display_indent())
1007        );
1008    }
1009
1010    #[tokio::test]
1011    async fn test_topk_dynamic_filter_pushdown_reaches_region_scan() {
1012        let engine = create_test_engine().await;
1013        let engine = engine
1014            .as_any()
1015            .downcast_ref::<DatafusionQueryEngine>()
1016            .unwrap();
1017        let engine_ctx = engine.engine_context(QueryContext::arc());
1018        let state = engine_ctx.state();
1019
1020        let schema = Arc::new(datatypes::schema::Schema::new(vec![ColumnSchema::new(
1021            "ts",
1022            ConcreteDataType::timestamp_millisecond_datatype(),
1023            false,
1024        )]));
1025
1026        let mut metadata_builder = RegionMetadataBuilder::new(RegionId::new(1024, 1));
1027        metadata_builder
1028            .push_column_metadata(ColumnMetadata {
1029                column_schema: ColumnSchema::new(
1030                    "ts",
1031                    ConcreteDataType::timestamp_millisecond_datatype(),
1032                    false,
1033                )
1034                .with_time_index(true),
1035                semantic_type: SemanticType::Timestamp,
1036                column_id: 1,
1037            })
1038            .primary_key(vec![]);
1039        let metadata = Arc::new(metadata_builder.build().unwrap());
1040
1041        let update_calls = Arc::new(AtomicUsize::new(0));
1042        let last_filter_len = Arc::new(AtomicUsize::new(0));
1043        let scanner = Box::new(RecordingScanner::new(
1044            schema,
1045            metadata,
1046            update_calls.clone(),
1047            last_filter_len.clone(),
1048        ));
1049        let scan = Arc::new(RegionScanExec::new(scanner, ScanRequest::default(), None).unwrap());
1050
1051        let sort_expr = PhysicalSortExpr {
1052            expr: Arc::new(Column::new("ts", 0)),
1053            options: SortOptions {
1054                descending: true,
1055                ..Default::default()
1056            },
1057        };
1058        let partition_ranges: Vec<Vec<PartitionRange>> = vec![vec![]];
1059        let mut plan: Arc<dyn ExecutionPlan> =
1060            Arc::new(PartSortExec::try_new(sort_expr, Some(3), partition_ranges, scan).unwrap());
1061
1062        for optimizer in state.physical_optimizers() {
1063            plan = optimizer.optimize(plan, state.config_options()).unwrap();
1064        }
1065
1066        assert!(update_calls.load(Ordering::Relaxed) > 0);
1067        assert!(last_filter_len.load(Ordering::Relaxed) > 0);
1068    }
1069
1070    #[tokio::test]
1071    async fn test_join_dynamic_filter_pushdown_reaches_region_scan() {
1072        let engine = create_test_engine().await;
1073        let engine = engine
1074            .as_any()
1075            .downcast_ref::<DatafusionQueryEngine>()
1076            .unwrap();
1077        let engine_ctx = engine.engine_context(QueryContext::arc());
1078        let state = engine_ctx.state();
1079
1080        assert!(
1081            state
1082                .config_options()
1083                .optimizer
1084                .enable_join_dynamic_filter_pushdown
1085        );
1086
1087        let schema = Arc::new(datatypes::schema::Schema::new(vec![ColumnSchema::new(
1088            "ts",
1089            ConcreteDataType::timestamp_millisecond_datatype(),
1090            false,
1091        )]));
1092
1093        let mut left_metadata_builder = RegionMetadataBuilder::new(RegionId::new(2048, 1));
1094        left_metadata_builder
1095            .push_column_metadata(ColumnMetadata {
1096                column_schema: ColumnSchema::new(
1097                    "ts",
1098                    ConcreteDataType::timestamp_millisecond_datatype(),
1099                    false,
1100                )
1101                .with_time_index(true),
1102                semantic_type: SemanticType::Timestamp,
1103                column_id: 1,
1104            })
1105            .primary_key(vec![]);
1106        let left_metadata = Arc::new(left_metadata_builder.build().unwrap());
1107
1108        let mut right_metadata_builder = RegionMetadataBuilder::new(RegionId::new(2048, 2));
1109        right_metadata_builder
1110            .push_column_metadata(ColumnMetadata {
1111                column_schema: ColumnSchema::new(
1112                    "ts",
1113                    ConcreteDataType::timestamp_millisecond_datatype(),
1114                    false,
1115                )
1116                .with_time_index(true),
1117                semantic_type: SemanticType::Timestamp,
1118                column_id: 1,
1119            })
1120            .primary_key(vec![]);
1121        let right_metadata = Arc::new(right_metadata_builder.build().unwrap());
1122
1123        let left_update_calls = Arc::new(AtomicUsize::new(0));
1124        let left_last_filter_len = Arc::new(AtomicUsize::new(0));
1125        let right_update_calls = Arc::new(AtomicUsize::new(0));
1126        let right_last_filter_len = Arc::new(AtomicUsize::new(0));
1127
1128        let left_scan = Arc::new(
1129            RegionScanExec::new(
1130                Box::new(RecordingScanner::new(
1131                    schema.clone(),
1132                    left_metadata,
1133                    left_update_calls.clone(),
1134                    left_last_filter_len.clone(),
1135                )),
1136                ScanRequest::default(),
1137                None,
1138            )
1139            .unwrap(),
1140        );
1141        let right_scan = Arc::new(
1142            RegionScanExec::new(
1143                Box::new(RecordingScanner::new(
1144                    schema,
1145                    right_metadata,
1146                    right_update_calls.clone(),
1147                    right_last_filter_len.clone(),
1148                )),
1149                ScanRequest::default(),
1150                None,
1151            )
1152            .unwrap(),
1153        );
1154
1155        let on: JoinOn = vec![(
1156            Arc::new(Column::new("ts", 0)) as Arc<dyn PhysicalExpr>,
1157            Arc::new(Column::new("ts", 0)) as Arc<dyn PhysicalExpr>,
1158        )];
1159
1160        let mut plan: Arc<dyn ExecutionPlan> = Arc::new(
1161            HashJoinExec::try_new(
1162                left_scan,
1163                right_scan,
1164                on,
1165                None,
1166                &JoinType::Inner,
1167                None,
1168                PartitionMode::CollectLeft,
1169                NullEquality::NullEqualsNull,
1170                false,
1171            )
1172            .unwrap(),
1173        );
1174
1175        for optimizer in state.physical_optimizers() {
1176            plan = optimizer.optimize(plan, state.config_options()).unwrap();
1177        }
1178
1179        assert!(left_update_calls.load(Ordering::Relaxed) > 0);
1180        assert_eq!(0, left_last_filter_len.load(Ordering::Relaxed));
1181        assert!(right_update_calls.load(Ordering::Relaxed) > 0);
1182        assert!(right_last_filter_len.load(Ordering::Relaxed) > 0);
1183    }
1184}