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 pg_oid_alias_expr_planner;
20mod planner;
21
22use std::any::Any;
23use std::collections::HashMap;
24use std::sync::Arc;
25
26use async_trait::async_trait;
27use common_base::Plugins;
28use common_catalog::consts::is_readonly_table;
29use common_error::ext::BoxedError;
30use common_function::function::FunctionContext;
31use common_function::function_factory::ScalarFunctionFactory;
32use common_query::{Output, OutputData, OutputMeta};
33use common_recordbatch::adapter::{
34    RecordBatchStreamAdapter, RegionQueryStatCounters, SERIES_SCAN_EXEC_NAME,
35};
36use common_recordbatch::{EmptyRecordBatchStream, SendableRecordBatchStream};
37use common_telemetry::tracing;
38use datafusion::catalog::TableFunction;
39use datafusion::dataframe::DataFrame;
40use datafusion::physical_plan::ExecutionPlan;
41use datafusion::physical_plan::analyze::AnalyzeExec;
42use datafusion::physical_plan::coalesce_partitions::CoalescePartitionsExec;
43use datafusion_common::ResolvedTableReference;
44use datafusion_expr::{
45    AggregateUDF, DmlStatement, LogicalPlan as DfLogicalPlan, LogicalPlan, WindowUDF, WriteOp,
46};
47use datatypes::prelude::VectorRef;
48use datatypes::schema::Schema;
49use futures_util::StreamExt;
50use session::context::QueryContextRef;
51use snafu::{OptionExt, ResultExt, ensure};
52use sqlparser::ast::AnalyzeFormat;
53use table::TableRef;
54use table::requests::{DeleteRequest, InsertRequest};
55use table::table::scan::{REGION_SCAN_EXEC_NAME, RegionScanExec, SeriesScanExec};
56use tracing::Span;
57
58use crate::analyze::DistAnalyzeExec;
59pub use crate::datafusion::planner::DfContextProviderAdapter;
60use crate::dist_plan::{MergeScanLogicalPlan, RemoteDynFilterReceiverInjectorRef};
61use crate::error::{
62    CatalogSnafu, CreateRecordBatchSnafu, MissingTableMutationHandlerSnafu,
63    MissingTimestampColumnSnafu, QueryExecutionSnafu, Result, TableMutationSnafu,
64    TableNotFoundSnafu, TableReadOnlySnafu, UnsupportedExprSnafu,
65};
66use crate::executor::QueryExecutor;
67use crate::metrics::{
68    OnDone, QUERY_STAGE_ELAPSED, maybe_attach_region_watermark_metrics,
69    should_collect_region_watermark_from_query_ctx,
70};
71use crate::optimizer::expr_depth;
72use crate::options::ScheduledTimeExtension;
73use crate::physical_wrapper::PhysicalPlanWrapperRef;
74use crate::planner::{DfLogicalPlanner, LogicalPlanner};
75use crate::query_engine::{DescribeResult, QueryEngineContext, QueryEngineState};
76use crate::region_query::RegionReadLimiter;
77use crate::{QueryEngine, metrics};
78
79/// Query parallelism hint key.
80/// This hint can be set in the query context to control the parallelism of the query execution.
81pub const QUERY_PARALLELISM_HINT: &str = "query_parallelism";
82
83/// Whether to fallback to the original plan when failed to push down.
84pub const QUERY_FALLBACK_HINT: &str = "query_fallback";
85
86fn query_load_region_id(plan: &Arc<dyn ExecutionPlan>) -> Option<u64> {
87    let mut region_id = None;
88    let mut stack = vec![plan.clone()];
89
90    while let Some(plan) = stack.pop() {
91        let scan_region_id = if plan.name() == REGION_SCAN_EXEC_NAME {
92            plan.downcast_ref::<RegionScanExec>()
93                .and_then(RegionScanExec::query_load_region_id)
94        } else if plan.name() == SERIES_SCAN_EXEC_NAME {
95            plan.downcast_ref::<SeriesScanExec>()
96                .and_then(SeriesScanExec::query_load_region_id)
97        } else {
98            None
99        };
100        if let Some(scan_region_id) = scan_region_id {
101            match region_id {
102                Some(region_id) if region_id != scan_region_id => return None,
103                Some(_) => {}
104                None => region_id = Some(scan_region_id),
105            }
106        }
107        stack.extend(plan.children().into_iter().cloned());
108    }
109
110    region_id
111}
112
113// Finds the region-owned query statistic counters from the local datanode scan plan.
114//
115// Unlike the Prometheus read-load reporting in `MergeScanExec`, the heartbeat
116// counters must be updated before metrics leave the datanode process. The
117// `RecordBatchStreamAdapter` that resolves `RecordBatchMetrics` does not know
118// the owning `MitoRegion`, so we extract the counters from the scan execs and
119// pass them to the adapter. If a plan contains scans from different regions,
120// return `None` to avoid charging the whole plan metrics to one region.
121fn query_stat_counters(plan: &Arc<dyn ExecutionPlan>) -> Option<RegionQueryStatCounters> {
122    let mut counters: Option<RegionQueryStatCounters> = None;
123    let mut stack = vec![plan.clone()];
124
125    while let Some(plan) = stack.pop() {
126        let scan_counters = if plan.name() == REGION_SCAN_EXEC_NAME {
127            plan.downcast_ref::<RegionScanExec>()
128                .and_then(RegionScanExec::query_stat_counters)
129        } else if plan.name() == SERIES_SCAN_EXEC_NAME {
130            plan.downcast_ref::<SeriesScanExec>()
131                .and_then(SeriesScanExec::query_stat_counters)
132        } else {
133            None
134        };
135        if let Some(scan_counters) = scan_counters {
136            match &counters {
137                Some(counters)
138                    if !Arc::ptr_eq(&counters.query_cpu_time, &scan_counters.query_cpu_time)
139                        || !Arc::ptr_eq(
140                            &counters.query_scanned_bytes,
141                            &scan_counters.query_scanned_bytes,
142                        ) =>
143                {
144                    return None;
145                }
146                Some(_) => {}
147                None => counters = Some(scan_counters),
148            }
149        }
150        stack.extend(plan.children().into_iter().cloned());
151    }
152
153    counters
154}
155
156pub struct DatafusionQueryEngine {
157    state: Arc<QueryEngineState>,
158    plugins: Plugins,
159}
160
161impl DatafusionQueryEngine {
162    pub fn new(state: Arc<QueryEngineState>, plugins: Plugins) -> Self {
163        Self { state, plugins }
164    }
165
166    /// Crate-visible view of the per-query engine context, for tests that
167    /// assert configuration propagation through the real query path.
168    #[cfg(test)]
169    pub(crate) fn engine_context_for_tests(
170        &self,
171        query_ctx: QueryContextRef,
172    ) -> QueryEngineContext {
173        self.engine_context(query_ctx).unwrap()
174    }
175
176    #[tracing::instrument(skip_all)]
177    async fn exec_query_plan(
178        &self,
179        plan: LogicalPlan,
180        query_ctx: QueryContextRef,
181    ) -> Result<Output> {
182        let mut ctx = self.engine_context(query_ctx)?;
183        let query_ctx = ctx.query_ctx();
184        let plan = if let Some(receiver_injector) =
185            self.plugins.get::<RemoteDynFilterReceiverInjectorRef>()
186        {
187            receiver_injector.maybe_inject(plan, query_ctx.clone())
188        } else {
189            plan
190        };
191
192        // `create_physical_plan` will optimize logical plan internally
193        let physical_plan = self.create_physical_plan(&mut ctx, &plan).await?;
194        let physical_plan = self.optimize_physical_plan(&mut ctx, physical_plan)?;
195        let physical_plan = if let Some(wrapper) = self.plugins.get::<PhysicalPlanWrapperRef>() {
196            wrapper.wrap(physical_plan, query_ctx)
197        } else {
198            physical_plan
199        };
200
201        // A region read is a remote body that streams until drained, so a query reading several
202        // sources would otherwise run one body per source and partition. Bound the reads of the
203        // plan shape that can hold the budget: the native raw PromQL topology, whose only
204        // multi-input node polls every input at once. A plan with any other multi-input node (a
205        // join, or the union a discovered selector builds) keeps its per-scan bounds only rather
206        // than take a query-wide budget its topology has not been checked against.
207        if crate::promql::planner::native::native_raw_plan_bounds_region_reads(&physical_plan) {
208            let target_partitions = ctx.state().config().target_partitions();
209            ctx.config_mut()
210                .set_extension(Arc::new(RegionReadLimiter::new(target_partitions)));
211        }
212
213        let stream = self.execute_stream(&ctx, &physical_plan)?;
214
215        Ok(Output::new(
216            OutputData::Stream(stream),
217            OutputMeta::new_with_plan(physical_plan),
218        ))
219    }
220
221    #[tracing::instrument(skip_all)]
222    async fn exec_dml_statement(
223        &self,
224        dml: DmlStatement,
225        query_ctx: QueryContextRef,
226    ) -> Result<Output> {
227        ensure!(
228            matches!(dml.op, WriteOp::Insert(_) | WriteOp::Delete),
229            UnsupportedExprSnafu {
230                name: format!("DML op {}", dml.op),
231            }
232        );
233
234        let _timer = QUERY_STAGE_ELAPSED
235            .with_label_values(&[dml.op.name()])
236            .start_timer();
237
238        let default_catalog = &query_ctx.current_catalog().to_owned();
239        let default_schema = &query_ctx.current_schema();
240        let table_name = dml.table_name.resolve(default_catalog, default_schema);
241        let table = self.find_table(&table_name, &query_ctx).await?;
242
243        let Output { data, meta } = self
244            .exec_query_plan((*dml.input).clone(), query_ctx.clone())
245            .await?;
246        let mut stream = match data {
247            OutputData::RecordBatches(batches) => batches.as_stream(),
248            OutputData::Stream(stream) => stream,
249            _ => unreachable!(),
250        };
251
252        let mut affected_rows = 0;
253        let mut insert_cost = 0;
254
255        match dml.op {
256            WriteOp::Insert(_) => {
257                while let Some(batch) = stream.next().await {
258                    let batch = batch.context(CreateRecordBatchSnafu)?;
259                    let column_vectors = batch
260                        .column_vectors(&table_name.to_string(), table.schema())
261                        .map_err(BoxedError::new)
262                        .context(QueryExecutionSnafu)?;
263                    // We ignore the insert op.
264                    let output = self
265                        .insert(&table_name, column_vectors, query_ctx.clone())
266                        .await?;
267                    let (rows, cost) = output.extract_rows_and_cost();
268                    affected_rows += rows;
269                    insert_cost += cost;
270                }
271            }
272            WriteOp::Delete => {
273                // Read-only system tables may have no time index; reject DELETE before key lookup.
274                ensure!(
275                    !is_readonly_table(&table_name.schema, &table_name.table),
276                    TableReadOnlySnafu {
277                        table: table_name.table.to_string(),
278                    }
279                );
280                let table_info = table.table_info();
281                let table_schema = table.schema();
282                let ts_column = table_schema.timestamp_column().with_context(|| {
283                    MissingTimestampColumnSnafu {
284                        table_name: table_info.name.clone(),
285                    }
286                })?;
287                let key_indices = stream
288                    .schema()
289                    .column_schemas()
290                    .iter()
291                    .enumerate()
292                    .filter(|(_, column)| {
293                        ts_column.name == column.name
294                            || table_info
295                                .meta
296                                .row_key_column_names()
297                                .any(|name| name == &column.name)
298                    })
299                    .map(|(index, _)| index)
300                    .collect::<Vec<_>>();
301                while let Some(batch) = stream.next().await {
302                    // The input plan already evaluated WHERE; storage deletes need only keys/time.
303                    // Project before vector conversion because JSON2's logical Struct is a placeholder.
304                    let batch = batch
305                        .context(CreateRecordBatchSnafu)?
306                        .try_project(&key_indices)
307                        .context(CreateRecordBatchSnafu)?;
308                    let column_vectors = batch
309                        .column_vectors(&table_name.to_string(), table.schema())
310                        .map_err(BoxedError::new)
311                        .context(QueryExecutionSnafu)?;
312                    affected_rows += self
313                        .delete(&table_name, column_vectors, query_ctx.clone())
314                        .await?;
315                }
316            }
317            _ => unreachable!("guarded by the 'ensure!' at the beginning"),
318        }
319        Ok(Output::new(
320            OutputData::AffectedRows(affected_rows),
321            OutputMeta::new(meta.plan, insert_cost),
322        ))
323    }
324
325    #[tracing::instrument(skip_all)]
326    async fn delete(
327        &self,
328        table_name: &ResolvedTableReference,
329        column_vectors: HashMap<String, VectorRef>,
330        query_ctx: QueryContextRef,
331    ) -> Result<usize> {
332        let catalog_name = table_name.catalog.to_string();
333        let schema_name = table_name.schema.to_string();
334        let table_name = table_name.table.to_string();
335
336        let request = DeleteRequest {
337            catalog_name,
338            schema_name,
339            table_name,
340            key_column_values: column_vectors,
341        };
342
343        self.state
344            .table_mutation_handler()
345            .context(MissingTableMutationHandlerSnafu)?
346            .delete(request, query_ctx)
347            .await
348            .context(TableMutationSnafu)
349    }
350
351    #[tracing::instrument(skip_all)]
352    async fn insert(
353        &self,
354        table_name: &ResolvedTableReference,
355        column_vectors: HashMap<String, VectorRef>,
356        query_ctx: QueryContextRef,
357    ) -> Result<Output> {
358        let catalog_name = table_name.catalog.to_string();
359        let schema_name = table_name.schema.to_string();
360        let table_name = table_name.table.to_string();
361
362        ensure!(
363            !is_readonly_table(&schema_name, &table_name),
364            TableReadOnlySnafu { table: table_name }
365        );
366
367        let request = InsertRequest {
368            catalog_name,
369            schema_name,
370            table_name,
371            columns_values: column_vectors,
372            skip_wal: query_ctx.skip_wal(),
373        };
374
375        self.state
376            .table_mutation_handler()
377            .context(MissingTableMutationHandlerSnafu)?
378            .insert(request, query_ctx)
379            .await
380            .context(TableMutationSnafu)
381    }
382
383    async fn find_table(
384        &self,
385        table_name: &ResolvedTableReference,
386        query_context: &QueryContextRef,
387    ) -> Result<TableRef> {
388        let catalog_name = table_name.catalog.as_ref();
389        let schema_name = table_name.schema.as_ref();
390        let table_name = table_name.table.as_ref();
391
392        self.state
393            .catalog_manager()
394            .table(catalog_name, schema_name, table_name, Some(query_context))
395            .await
396            .context(CatalogSnafu)?
397            .with_context(|| TableNotFoundSnafu { table: table_name })
398    }
399
400    #[tracing::instrument(skip_all)]
401    async fn create_physical_plan(
402        &self,
403        ctx: &mut QueryEngineContext,
404        logical_plan: &LogicalPlan,
405    ) -> Result<Arc<dyn ExecutionPlan>> {
406        /// Only print context on panic, to avoid cluttering logs.
407        ///
408        /// TODO(discord9): remove this once we catch the bug
409        #[derive(Debug)]
410        struct PanicLogger<'a> {
411            input_logical_plan: &'a LogicalPlan,
412            after_analyze: Option<LogicalPlan>,
413            after_optimize: Option<LogicalPlan>,
414            phy_plan: Option<Arc<dyn ExecutionPlan>>,
415        }
416        impl Drop for PanicLogger<'_> {
417            fn drop(&mut self) {
418                if std::thread::panicking() {
419                    common_telemetry::error!(
420                        "Panic while creating physical plan, input logical plan: {:?}, after analyze: {:?}, after optimize: {:?}, final physical plan: {:?}",
421                        self.input_logical_plan,
422                        self.after_analyze,
423                        self.after_optimize,
424                        self.phy_plan
425                    );
426                }
427            }
428        }
429
430        expr_depth::validate_plan(logical_plan)?;
431
432        let mut logger = PanicLogger {
433            input_logical_plan: logical_plan,
434            after_analyze: None,
435            after_optimize: None,
436            phy_plan: None,
437        };
438
439        let _timer = metrics::CREATE_PHYSICAL_ELAPSED.start_timer();
440        let state = ctx.state();
441
442        common_telemetry::debug!("Create physical plan, input plan: {logical_plan}");
443
444        // special handle EXPLAIN plan
445        if matches!(logical_plan, DfLogicalPlan::Explain(_)) {
446            return state
447                .create_physical_plan(logical_plan)
448                .await
449                .map_err(Into::into);
450        }
451
452        // analyze first
453        let analyzed_plan = state.analyzer().execute_and_check(
454            logical_plan.clone(),
455            state.config_options(),
456            |_, _| {},
457        )?;
458
459        expr_depth::validate_plan(&analyzed_plan)?;
460        logger.after_analyze = Some(analyzed_plan.clone());
461
462        common_telemetry::debug!("Create physical plan, analyzed plan: {analyzed_plan}");
463
464        // skip optimize for MergeScan
465        let optimized_plan = if let DfLogicalPlan::Extension(ext) = &analyzed_plan
466            && ext.node.name() == MergeScanLogicalPlan::name()
467        {
468            analyzed_plan.clone()
469        } else {
470            state
471                .optimizer()
472                .optimize(analyzed_plan, state, |_, _| {})?
473        };
474
475        expr_depth::validate_plan(&optimized_plan)?;
476        common_telemetry::debug!("Create physical plan, optimized plan: {optimized_plan}");
477        logger.after_optimize = Some(optimized_plan.clone());
478
479        let physical_plan = state
480            .query_planner()
481            .create_physical_plan(&optimized_plan, state)
482            .await?;
483
484        logger.phy_plan = Some(physical_plan.clone());
485        drop(logger);
486        Ok(physical_plan)
487    }
488
489    #[tracing::instrument(skip_all)]
490    fn optimize_physical_plan(
491        &self,
492        ctx: &mut QueryEngineContext,
493        plan: Arc<dyn ExecutionPlan>,
494    ) -> Result<Arc<dyn ExecutionPlan>> {
495        let _timer = metrics::OPTIMIZE_PHYSICAL_ELAPSED.start_timer();
496
497        // TODO(ruihang): `self.create_physical_plan()` already optimize the plan, check
498        // if we need to optimize it again here.
499        // let state = ctx.state();
500        // let config = state.config_options();
501
502        // skip optimize AnalyzeExec plan
503        let optimized_plan = if let Some(analyze_plan) = plan.downcast_ref::<AnalyzeExec>() {
504            let format = if let Some(format) = ctx.query_ctx().explain_format()
505                && format.to_lowercase() == "json"
506            {
507                AnalyzeFormat::JSON
508            } else {
509                AnalyzeFormat::TEXT
510            };
511            // Sets the verbose flag of the query context.
512            // The MergeScanExec plan uses the verbose flag to determine whether to print the plan in verbose mode.
513            ctx.query_ctx().set_explain_verbose(analyze_plan.verbose());
514
515            Arc::new(DistAnalyzeExec::new(
516                analyze_plan.input().clone(),
517                analyze_plan.verbose(),
518                format,
519            ))
520            // let mut new_plan = analyze_plan.input().clone();
521            // for optimizer in state.physical_optimizers() {
522            //     new_plan = optimizer
523            //         .optimize(new_plan, config)
524            //         .context(DataFusionSnafu)?;
525            // }
526            // Arc::new(DistAnalyzeExec::new(new_plan))
527        } else {
528            plan
529            // let mut new_plan = plan;
530            // for optimizer in state.physical_optimizers() {
531            //     new_plan = optimizer
532            //         .optimize(new_plan, config)
533            //         .context(DataFusionSnafu)?;
534            // }
535            // new_plan
536        };
537
538        Ok(optimized_plan)
539    }
540}
541
542#[async_trait]
543impl QueryEngine for DatafusionQueryEngine {
544    fn as_any(&self) -> &dyn Any {
545        self
546    }
547
548    fn planner(&self) -> Arc<dyn LogicalPlanner> {
549        Arc::new(DfLogicalPlanner::new(self.state.clone()))
550    }
551
552    fn name(&self) -> &str {
553        "datafusion"
554    }
555
556    async fn describe(
557        &self,
558        plan: LogicalPlan,
559        _query_ctx: QueryContextRef,
560    ) -> Result<DescribeResult> {
561        Ok(DescribeResult { logical_plan: plan })
562    }
563
564    async fn execute(&self, plan: LogicalPlan, query_ctx: QueryContextRef) -> Result<Output> {
565        match plan {
566            LogicalPlan::Dml(dml) => self.exec_dml_statement(dml, query_ctx).await,
567            _ => self.exec_query_plan(plan, query_ctx).await,
568        }
569    }
570
571    /// Note in SQL queries, aggregate names are looked up using
572    /// lowercase unless the query uses quotes. For example,
573    ///
574    /// `SELECT MY_UDAF(x)...` will look for an aggregate named `"my_udaf"`
575    /// `SELECT "my_UDAF"(x)` will look for an aggregate named `"my_UDAF"`
576    ///
577    /// So it's better to make UDAF name lowercase when creating one.
578    fn register_aggregate_function(&self, func: AggregateUDF) {
579        self.state.register_aggr_function(func);
580    }
581
582    /// Register an scalar function.
583    /// Will override if the function with same name is already registered.
584    fn register_scalar_function(&self, func: ScalarFunctionFactory) {
585        self.state.register_scalar_function(func);
586    }
587
588    fn register_table_function(&self, func: Arc<TableFunction>) {
589        self.state.register_table_function(func);
590    }
591
592    fn register_window_function(&self, func: WindowUDF) {
593        self.state.register_window_function(func);
594    }
595
596    fn read_table(&self, table: TableRef) -> Result<DataFrame> {
597        self.state.read_table(table).map_err(Into::into)
598    }
599
600    fn engine_context(&self, query_ctx: QueryContextRef) -> Result<QueryEngineContext> {
601        let mut state = self.state.session_state();
602        let query_ctx = self.state.apply_query_options(&mut state, query_ctx)?;
603        state.config_mut().set_extension(query_ctx.clone());
604        state.config_mut().set_extension(self.state.clone());
605        // configure execution options
606        state.config_mut().options_mut().execution.time_zone =
607            Some(query_ctx.timezone().to_string());
608
609        state
610            .config_mut()
611            .options_mut()
612            .extensions
613            .insert(FunctionContext {
614                query_ctx: query_ctx.clone(),
615                state: self.engine_state().function_state(),
616            });
617
618        // The PromQL planner registers the query's annotation collector in the session state it
619        // planned with. Execution builds its task context from a fresh state, so the same
620        // collector is looked up again by query id here; without it a native kernel's warnings
621        // and infos would be recorded into an object nobody reads.
622        if let Some(collector) = query_ctx
623            .remote_query_id()
624            .map(common_query::promql_annotations::promql_annotation_collector)
625        {
626            state
627                .config_mut()
628                .options_mut()
629                .extensions
630                .insert(collector);
631        }
632
633        // Carry scheduled Flow time through ConfigOptions.extensions so that
634        // the distributed plan analyzer can read it during expression
635        // simplification (preventing wall-clock constant-folding of `now()`).
636        state
637            .config_mut()
638            .options_mut()
639            .extensions
640            .insert(ScheduledTimeExtension {
641                scheduled_time: crate::options::scheduled_time_from_ctx(&query_ctx),
642            });
643
644        let config_options = state.config_options().clone();
645        let _ = state
646            .execution_props_mut()
647            .config_options
648            .insert(config_options);
649
650        // Apply scheduled time from query context if present, so that `now()` /
651        // `current_timestamp()` functions evaluate against the logical scheduled time
652        // rather than wall-clock.
653        match crate::options::parse_scheduled_time_datetime(&query_ctx.extensions()) {
654            Ok(Some(scheduled_rt)) => {
655                state.execution_props_mut().query_execution_start_time = Some(scheduled_rt);
656            }
657            Ok(None) => {}
658            Err(err) => {
659                common_telemetry::warn!(err; "Ignoring invalid scheduled time query extension");
660            }
661        }
662
663        Ok(QueryEngineContext::new(state, query_ctx))
664    }
665
666    fn engine_state(&self) -> &QueryEngineState {
667        &self.state
668    }
669}
670
671impl QueryExecutor for DatafusionQueryEngine {
672    #[tracing::instrument(skip_all)]
673    fn execute_stream(
674        &self,
675        ctx: &QueryEngineContext,
676        plan: &Arc<dyn ExecutionPlan>,
677    ) -> Result<SendableRecordBatchStream> {
678        let query_ctx = ctx.query_ctx();
679        let explain_verbose = query_ctx.explain_verbose();
680        let should_collect_region_watermark =
681            should_collect_region_watermark_from_query_ctx(&query_ctx)?;
682        let output_partitions = plan.properties().output_partitioning().partition_count();
683        if explain_verbose {
684            common_telemetry::info!("Executing query plan, output_partitions: {output_partitions}");
685        }
686
687        let exec_timer = metrics::EXEC_PLAN_ELAPSED.start_timer();
688        let task_ctx = ctx.build_task_ctx();
689        let span = Span::current();
690
691        match plan.properties().output_partitioning().partition_count() {
692            0 => {
693                let schema = Arc::new(
694                    Schema::try_from(plan.schema())
695                        .map_err(BoxedError::new)
696                        .context(QueryExecutionSnafu)?,
697                );
698                Ok(Box::pin(EmptyRecordBatchStream::new(schema)))
699            }
700            1 => {
701                let df_stream = plan.execute(0, task_ctx)?;
702                let mut stream = RecordBatchStreamAdapter::try_new_with_span(df_stream, span)
703                    .context(error::ConvertDfRecordBatchStreamSnafu)
704                    .map_err(BoxedError::new)
705                    .context(QueryExecutionSnafu)?;
706                stream.set_metrics2(plan.clone());
707                stream.set_query_load_region_id(query_load_region_id(plan));
708                stream.set_query_stat_counters(query_stat_counters(plan));
709                stream.set_explain_verbose(explain_verbose);
710                let stream = OnDone::new(Box::pin(stream), move || {
711                    let exec_cost = exec_timer.stop_and_record();
712                    if explain_verbose {
713                        common_telemetry::info!(
714                            "DatafusionQueryEngine execute 1 stream, cost: {:?}s",
715                            exec_cost,
716                        );
717                    }
718                });
719                Ok(maybe_attach_region_watermark_metrics(
720                    Box::pin(stream),
721                    plan.clone(),
722                    should_collect_region_watermark,
723                ))
724            }
725            _ => {
726                // merge into a single partition
727                let merged_plan = CoalescePartitionsExec::new(plan.clone());
728                // CoalescePartitionsExec must produce a single partition
729                assert_eq!(
730                    1,
731                    merged_plan
732                        .properties()
733                        .output_partitioning()
734                        .partition_count()
735                );
736                let df_stream = merged_plan.execute(0, task_ctx)?;
737                let mut stream = RecordBatchStreamAdapter::try_new_with_span(df_stream, span)
738                    .context(error::ConvertDfRecordBatchStreamSnafu)
739                    .map_err(BoxedError::new)
740                    .context(QueryExecutionSnafu)?;
741                stream.set_metrics2(plan.clone());
742                stream.set_query_load_region_id(query_load_region_id(plan));
743                stream.set_query_stat_counters(query_stat_counters(plan));
744                stream.set_explain_verbose(explain_verbose);
745                let stream = OnDone::new(Box::pin(stream), move || {
746                    let exec_cost = exec_timer.stop_and_record();
747                    if explain_verbose {
748                        common_telemetry::info!(
749                            "DatafusionQueryEngine execute {output_partitions} stream, cost: {:?}s",
750                            exec_cost
751                        );
752                    }
753                });
754                Ok(maybe_attach_region_watermark_metrics(
755                    Box::pin(stream),
756                    plan.clone(),
757                    should_collect_region_watermark,
758                ))
759            }
760        }
761    }
762}
763
764#[cfg(test)]
765mod tests {
766    use std::fmt;
767    use std::sync::Arc;
768    use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
769
770    use api::v1::SemanticType;
771    use arrow::array::{ArrayRef, UInt64Array};
772    use arrow_schema::SortOptions;
773    use async_trait::async_trait;
774    use catalog::RegisterTableRequest;
775    use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, NUMBERS_TABLE_ID};
776    use common_error::ext::BoxedError;
777    use common_recordbatch::{
778        EmptyRecordBatchStream, RecordBatch, SendableRecordBatchStream, util,
779    };
780    use datafusion::physical_plan::display::{DisplayAs, DisplayFormatType};
781    use datafusion::physical_plan::expressions::PhysicalSortExpr;
782    use datafusion::physical_plan::joins::{CrossJoinExec, HashJoinExec, JoinOn, PartitionMode};
783    use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet;
784    use datafusion::physical_plan::{ExecutionPlan, PhysicalExpr};
785    use datafusion::prelude::{col, lit};
786    use datafusion_common::{JoinType, NullEquality, ScalarValue};
787    use datafusion_physical_expr::expressions::Column;
788    use datatypes::prelude::ConcreteDataType;
789    use datatypes::schema::{ColumnSchema, SchemaRef};
790    use datatypes::vectors::{Helper, UInt32Vector, VectorRef};
791    use session::context::{QueryContext, QueryContextBuilder};
792    use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder, RegionMetadataRef};
793    use store_api::region_engine::{
794        PartitionRange, PrepareRequest, QueryScanContext, RawLabelSource, RegionScanner,
795        ScannerProperties,
796    };
797    use store_api::storage::{RegionId, ScanRequest};
798    use table::metadata::{TableInfoBuilder, TableMetaBuilder};
799    use table::table::numbers::{NUMBERS_TABLE_NAME, NumbersTable};
800    use table::table::scan::RegionScanExec;
801
802    use super::*;
803    use crate::options::QueryOptions;
804    use crate::parser::{QueryLanguageParser, QueryStatement};
805    use crate::part_sort::PartSortExec;
806    use crate::query_engine::{QueryEngineFactory, QueryEngineRef};
807
808    #[derive(Debug)]
809    struct RecordingScanner {
810        schema: SchemaRef,
811        metadata: RegionMetadataRef,
812        properties: ScannerProperties,
813        update_calls: Arc<AtomicUsize>,
814        last_filter_len: Arc<AtomicUsize>,
815    }
816
817    impl RecordingScanner {
818        fn new(
819            schema: SchemaRef,
820            metadata: RegionMetadataRef,
821            update_calls: Arc<AtomicUsize>,
822            last_filter_len: Arc<AtomicUsize>,
823        ) -> Self {
824            Self {
825                schema,
826                metadata,
827                properties: ScannerProperties::default(),
828                update_calls,
829                last_filter_len,
830            }
831        }
832    }
833
834    impl RegionScanner for RecordingScanner {
835        fn name(&self) -> &str {
836            "RecordingScanner"
837        }
838
839        fn properties(&self) -> &ScannerProperties {
840            &self.properties
841        }
842
843        fn schema(&self) -> SchemaRef {
844            self.schema.clone()
845        }
846
847        fn metadata(&self) -> RegionMetadataRef {
848            self.metadata.clone()
849        }
850
851        fn prepare(&mut self, request: PrepareRequest) -> std::result::Result<(), BoxedError> {
852            self.properties.prepare(request);
853            Ok(())
854        }
855
856        fn scan_partition(
857            &self,
858            _ctx: &QueryScanContext,
859            _metrics_set: &ExecutionPlanMetricsSet,
860            _partition: usize,
861        ) -> std::result::Result<SendableRecordBatchStream, BoxedError> {
862            Ok(Box::pin(EmptyRecordBatchStream::new(self.schema.clone())))
863        }
864
865        fn has_predicate_without_region(&self) -> bool {
866            true
867        }
868
869        fn raw_series_schema(
870            &self,
871            _label_source: &RawLabelSource,
872        ) -> std::result::Result<Option<Arc<datatypes::series::samples::SeriesSchema>>, BoxedError>
873        {
874            Ok(Some(Arc::new(datatypes::series::samples::SeriesSchema {
875                fields: Arc::from([datatypes::series::samples::FieldSpec { name: "ts".into() }]),
876                eval_grid: None,
877            })))
878        }
879
880        fn add_dyn_filter_to_predicate(
881            &mut self,
882            filter_exprs: Vec<Arc<dyn PhysicalExpr>>,
883        ) -> Vec<bool> {
884            self.update_calls.fetch_add(1, Ordering::Relaxed);
885            self.last_filter_len
886                .store(filter_exprs.len(), Ordering::Relaxed);
887            vec![true; filter_exprs.len()]
888        }
889
890        fn set_logical_region(&mut self, logical_region: bool) {
891            self.properties.set_logical_region(logical_region);
892        }
893
894        fn set_query_load_region_id(&mut self, region_id: store_api::storage::RegionId) {
895            self.properties.set_query_load_region_id(region_id);
896        }
897    }
898
899    impl DisplayAs for RecordingScanner {
900        fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter<'_>) -> fmt::Result {
901            write!(f, "RecordingScanner")
902        }
903    }
904
905    fn build_query_load_region_scan(
906        query_load_region_id: Option<RegionId>,
907    ) -> Arc<dyn ExecutionPlan> {
908        build_region_scan(query_load_region_id, None)
909    }
910
911    fn build_query_stat_counter_region_scan(
912        counters: RegionQueryStatCounters,
913    ) -> Arc<dyn ExecutionPlan> {
914        build_region_scan(None, Some(counters))
915    }
916
917    fn build_region_scan(
918        query_load_region_id: Option<RegionId>,
919        query_stat_counters: Option<RegionQueryStatCounters>,
920    ) -> Arc<dyn ExecutionPlan> {
921        build_region_scan_exec(query_load_region_id, query_stat_counters)
922    }
923
924    fn build_region_scan_exec(
925        query_load_region_id: Option<RegionId>,
926        query_stat_counters: Option<RegionQueryStatCounters>,
927    ) -> Arc<RegionScanExec> {
928        let schema = Arc::new(datatypes::schema::Schema::new(vec![ColumnSchema::new(
929            "ts",
930            ConcreteDataType::timestamp_millisecond_datatype(),
931            false,
932        )]));
933
934        let mut metadata_builder = RegionMetadataBuilder::new(RegionId::new(1024, 1));
935        metadata_builder
936            .push_column_metadata(ColumnMetadata {
937                column_schema: ColumnSchema::new(
938                    "ts",
939                    ConcreteDataType::timestamp_millisecond_datatype(),
940                    false,
941                )
942                .with_time_index(true),
943                semantic_type: SemanticType::Timestamp,
944                column_id: 1,
945            })
946            .primary_key(vec![]);
947        let metadata = Arc::new(metadata_builder.build().unwrap());
948        let mut scanner = RecordingScanner::new(
949            schema,
950            metadata,
951            Arc::new(AtomicUsize::new(0)),
952            Arc::new(AtomicUsize::new(0)),
953        );
954        if let Some(region_id) = query_load_region_id {
955            scanner.set_query_load_region_id(region_id);
956        }
957        if let Some(counters) = query_stat_counters {
958            scanner.properties.set_query_stat_counters(counters);
959        }
960
961        Arc::new(RegionScanExec::new(Box::new(scanner), ScanRequest::default(), None).unwrap())
962    }
963
964    fn build_series_scan(
965        query_load_region_id: Option<RegionId>,
966        query_stat_counters: Option<RegionQueryStatCounters>,
967    ) -> Arc<dyn ExecutionPlan> {
968        build_region_scan_exec(query_load_region_id, query_stat_counters)
969            .try_to_series_scan(RawLabelSource::Explicit)
970            .unwrap()
971            .expect("RecordingScanner supports a native series scan")
972    }
973
974    fn build_mixed_scan_plan(
975        left: Arc<dyn ExecutionPlan>,
976        right: Arc<dyn ExecutionPlan>,
977    ) -> Arc<dyn ExecutionPlan> {
978        Arc::new(CrossJoinExec::new(left, right))
979    }
980
981    fn query_stat_counters_for_test() -> RegionQueryStatCounters {
982        RegionQueryStatCounters {
983            query_cpu_time: Arc::new(AtomicU64::new(0)),
984            query_scanned_bytes: Arc::new(AtomicU64::new(0)),
985        }
986    }
987
988    #[test]
989    fn query_load_region_id_reads_native_series_scan() {
990        let region_id = RegionId::new(1024, 42);
991        let scan = build_series_scan(Some(region_id), None);
992
993        assert_eq!(super::query_load_region_id(&scan), Some(region_id.as_u64()));
994    }
995
996    #[test]
997    fn query_load_region_id_accepts_mixed_scans_for_same_region() {
998        let region_id = RegionId::new(1024, 42);
999        let left = build_query_load_region_scan(Some(region_id));
1000        let right = build_series_scan(Some(region_id), None);
1001        let plan = build_mixed_scan_plan(left, right);
1002
1003        assert_eq!(super::query_load_region_id(&plan), Some(region_id.as_u64()));
1004    }
1005
1006    #[test]
1007    fn query_load_region_id_rejects_mixed_region_scans() {
1008        let left = build_query_load_region_scan(Some(RegionId::new(1024, 42)));
1009        let right = build_series_scan(Some(RegionId::new(1024, 43)), None);
1010        let plan = build_mixed_scan_plan(left, right);
1011
1012        assert!(super::query_load_region_id(&plan).is_none());
1013    }
1014
1015    #[test]
1016    fn query_load_region_id_ignores_scans_without_region_id() {
1017        let query_load_region_id = RegionId::new(1024, 42);
1018        let scan_without_region_id = build_query_load_region_scan(None);
1019        let scan_with_region_id = build_query_load_region_scan(Some(query_load_region_id));
1020        let on: JoinOn = vec![(
1021            Arc::new(Column::new("ts", 0)) as Arc<dyn PhysicalExpr>,
1022            Arc::new(Column::new("ts", 0)) as Arc<dyn PhysicalExpr>,
1023        )];
1024        let plan: Arc<dyn ExecutionPlan> = Arc::new(
1025            HashJoinExec::try_new(
1026                scan_without_region_id,
1027                scan_with_region_id,
1028                on,
1029                None,
1030                &JoinType::Inner,
1031                None,
1032                PartitionMode::CollectLeft,
1033                NullEquality::NullEqualsNull,
1034                false,
1035            )
1036            .unwrap(),
1037        );
1038
1039        assert_eq!(
1040            super::query_load_region_id(&plan),
1041            Some(query_load_region_id.as_u64())
1042        );
1043    }
1044
1045    #[test]
1046    fn query_stat_counters_reads_native_series_scan() {
1047        let counters = query_stat_counters_for_test();
1048        let scan = build_series_scan(None, Some(counters.clone()));
1049
1050        let actual = super::query_stat_counters(&scan).unwrap();
1051        assert!(Arc::ptr_eq(
1052            &actual.query_cpu_time,
1053            &counters.query_cpu_time
1054        ));
1055        assert!(Arc::ptr_eq(
1056            &actual.query_scanned_bytes,
1057            &counters.query_scanned_bytes
1058        ));
1059    }
1060
1061    #[test]
1062    fn query_stat_counters_returns_shared_counter_for_mixed_scan_plan() {
1063        let counters = query_stat_counters_for_test();
1064        let left = build_query_stat_counter_region_scan(counters.clone());
1065        let right = build_series_scan(None, Some(counters.clone()));
1066        let plan = build_mixed_scan_plan(left, right);
1067
1068        let actual = super::query_stat_counters(&plan).unwrap();
1069        assert!(Arc::ptr_eq(
1070            &actual.query_cpu_time,
1071            &counters.query_cpu_time
1072        ));
1073        assert!(Arc::ptr_eq(
1074            &actual.query_scanned_bytes,
1075            &counters.query_scanned_bytes
1076        ));
1077    }
1078
1079    #[test]
1080    fn query_stat_counters_rejects_mixed_counter_plan_with_series_scan() {
1081        let left = build_query_stat_counter_region_scan(query_stat_counters_for_test());
1082        let right = build_series_scan(None, Some(query_stat_counters_for_test()));
1083        let plan = build_mixed_scan_plan(left, right);
1084
1085        assert!(super::query_stat_counters(&plan).is_none());
1086    }
1087
1088    #[test]
1089    fn query_stat_counters_returns_shared_counter_for_multi_scan_plan() {
1090        let counters = query_stat_counters_for_test();
1091        let left = build_query_stat_counter_region_scan(counters.clone());
1092        let right = build_query_stat_counter_region_scan(counters.clone());
1093        let on: JoinOn = vec![(
1094            Arc::new(Column::new("ts", 0)) as Arc<dyn PhysicalExpr>,
1095            Arc::new(Column::new("ts", 0)) as Arc<dyn PhysicalExpr>,
1096        )];
1097        let plan: Arc<dyn ExecutionPlan> = Arc::new(
1098            HashJoinExec::try_new(
1099                left,
1100                right,
1101                on,
1102                None,
1103                &JoinType::Inner,
1104                None,
1105                PartitionMode::CollectLeft,
1106                NullEquality::NullEqualsNull,
1107                false,
1108            )
1109            .unwrap(),
1110        );
1111
1112        let actual = super::query_stat_counters(&plan).unwrap();
1113        assert!(Arc::ptr_eq(
1114            &actual.query_cpu_time,
1115            &counters.query_cpu_time
1116        ));
1117        assert!(Arc::ptr_eq(
1118            &actual.query_scanned_bytes,
1119            &counters.query_scanned_bytes
1120        ));
1121    }
1122
1123    #[test]
1124    fn query_stat_counters_ignores_mixed_counter_plan() {
1125        let left = build_query_stat_counter_region_scan(query_stat_counters_for_test());
1126        let right = build_query_stat_counter_region_scan(query_stat_counters_for_test());
1127        let on: JoinOn = vec![(
1128            Arc::new(Column::new("ts", 0)) as Arc<dyn PhysicalExpr>,
1129            Arc::new(Column::new("ts", 0)) as Arc<dyn PhysicalExpr>,
1130        )];
1131        let plan: Arc<dyn ExecutionPlan> = Arc::new(
1132            HashJoinExec::try_new(
1133                left,
1134                right,
1135                on,
1136                None,
1137                &JoinType::Inner,
1138                None,
1139                PartitionMode::CollectLeft,
1140                NullEquality::NullEqualsNull,
1141                false,
1142            )
1143            .unwrap(),
1144        );
1145
1146        assert!(super::query_stat_counters(&plan).is_none());
1147    }
1148
1149    async fn create_test_engine() -> QueryEngineRef {
1150        let catalog_manager = catalog::memory::new_memory_catalog_manager().unwrap();
1151        let req = RegisterTableRequest {
1152            catalog: DEFAULT_CATALOG_NAME.to_string(),
1153            schema: DEFAULT_SCHEMA_NAME.to_string(),
1154            table_name: NUMBERS_TABLE_NAME.to_string(),
1155            table_id: NUMBERS_TABLE_ID,
1156            table: NumbersTable::table(NUMBERS_TABLE_ID),
1157        };
1158        catalog_manager.register_table_sync(req).unwrap();
1159
1160        QueryEngineFactory::new(
1161            catalog_manager,
1162            None,
1163            None,
1164            None,
1165            None,
1166            false,
1167            QueryOptions::default(),
1168        )
1169        .query_engine()
1170    }
1171
1172    #[tokio::test]
1173    async fn test_sql_to_plan() {
1174        let engine = create_test_engine().await;
1175        let sql = "select sum(number) from numbers limit 20";
1176
1177        let stmt = QueryLanguageParser::parse_sql(sql, &QueryContext::arc()).unwrap();
1178        let plan = engine
1179            .planner()
1180            .plan(&stmt, QueryContext::arc())
1181            .await
1182            .unwrap();
1183
1184        assert_eq!(
1185            plan.to_string(),
1186            r#"Limit: skip=0, fetch=20
1187  Projection: sum(numbers.number)
1188    Aggregate: groupBy=[[]], aggr=[[sum(numbers.number)]]
1189      TableScan: numbers"#
1190        );
1191    }
1192
1193    #[tokio::test]
1194    async fn test_purge_table_is_not_available_to_select() {
1195        let engine = create_test_engine().await;
1196        let stmt =
1197            QueryLanguageParser::parse_sql("select purge_table('numbers')", &QueryContext::arc())
1198                .unwrap();
1199
1200        assert!(
1201            engine
1202                .planner()
1203                .plan(&stmt, QueryContext::arc())
1204                .await
1205                .is_err()
1206        );
1207    }
1208
1209    #[tokio::test]
1210    async fn test_execute() {
1211        let engine = create_test_engine().await;
1212        let sql = "select sum(number) from numbers limit 20";
1213
1214        let stmt = QueryLanguageParser::parse_sql(sql, &QueryContext::arc()).unwrap();
1215        let plan = engine
1216            .planner()
1217            .plan(&stmt, QueryContext::arc())
1218            .await
1219            .unwrap();
1220
1221        let output = engine.execute(plan, QueryContext::arc()).await.unwrap();
1222
1223        match output.data {
1224            OutputData::Stream(recordbatch) => {
1225                let numbers = util::collect(recordbatch).await.unwrap();
1226                assert_eq!(1, numbers.len());
1227                assert_eq!(numbers[0].num_columns(), 1);
1228                assert_eq!(1, numbers[0].schema.num_columns());
1229                assert_eq!(
1230                    "sum(numbers.number)",
1231                    numbers[0].schema.column_schemas()[0].name
1232                );
1233
1234                let batch = &numbers[0];
1235                assert_eq!(1, batch.num_columns());
1236                assert_eq!(batch.column(0).len(), 1);
1237
1238                let expected = Arc::new(UInt64Array::from_iter_values([4950])) as ArrayRef;
1239                assert_eq!(batch.column(0), &expected);
1240            }
1241            _ => unreachable!(),
1242        }
1243    }
1244
1245    #[tokio::test]
1246    async fn test_read_table() {
1247        let engine = create_test_engine().await;
1248
1249        let engine = engine
1250            .as_any()
1251            .downcast_ref::<DatafusionQueryEngine>()
1252            .unwrap();
1253        let query_ctx = Arc::new(QueryContextBuilder::default().build());
1254        let table = engine
1255            .find_table(
1256                &ResolvedTableReference {
1257                    catalog: "greptime".into(),
1258                    schema: "public".into(),
1259                    table: "numbers".into(),
1260                },
1261                &query_ctx,
1262            )
1263            .await
1264            .unwrap();
1265
1266        let df = engine.read_table(table).unwrap();
1267        let df = df
1268            .select_columns(&["number"])
1269            .unwrap()
1270            .filter(col("number").lt(lit(10)))
1271            .unwrap();
1272        let batches = df.collect().await.unwrap();
1273        assert_eq!(1, batches.len());
1274        let batch = &batches[0];
1275
1276        assert_eq!(1, batch.num_columns());
1277        assert_eq!(batch.column(0).len(), 10);
1278
1279        assert_eq!(
1280            Helper::try_into_vector(batch.column(0)).unwrap(),
1281            Arc::new(UInt32Vector::from_slice([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])) as VectorRef
1282        );
1283    }
1284
1285    #[tokio::test]
1286    async fn test_describe() {
1287        let engine = create_test_engine().await;
1288        let sql = "select sum(number) from numbers limit 20";
1289
1290        let stmt = QueryLanguageParser::parse_sql(sql, &QueryContext::arc()).unwrap();
1291
1292        let plan = engine
1293            .planner()
1294            .plan(&stmt, QueryContext::arc())
1295            .await
1296            .unwrap();
1297
1298        let DescribeResult { logical_plan } =
1299            engine.describe(plan, QueryContext::arc()).await.unwrap();
1300
1301        let schema: Schema = logical_plan.schema().clone().try_into().unwrap();
1302
1303        assert_eq!(
1304            schema.column_schemas()[0],
1305            ColumnSchema::new(
1306                "sum(numbers.number)",
1307                ConcreteDataType::uint64_datatype(),
1308                true
1309            )
1310        );
1311        assert_eq!(
1312            "Limit: skip=0, fetch=20\n  Projection: sum(numbers.number)\n    Aggregate: groupBy=[[]], aggr=[[sum(numbers.number)]]\n      TableScan: numbers",
1313            format!("{}", logical_plan.display_indent())
1314        );
1315    }
1316
1317    #[tokio::test]
1318    async fn test_topk_dynamic_filter_pushdown_reaches_region_scan() {
1319        let engine = create_test_engine().await;
1320        let engine = engine
1321            .as_any()
1322            .downcast_ref::<DatafusionQueryEngine>()
1323            .unwrap();
1324        let engine_ctx = engine.engine_context(QueryContext::arc()).unwrap();
1325        let state = engine_ctx.state();
1326
1327        let schema = Arc::new(datatypes::schema::Schema::new(vec![ColumnSchema::new(
1328            "ts",
1329            ConcreteDataType::timestamp_millisecond_datatype(),
1330            false,
1331        )]));
1332
1333        let mut metadata_builder = RegionMetadataBuilder::new(RegionId::new(1024, 1));
1334        metadata_builder
1335            .push_column_metadata(ColumnMetadata {
1336                column_schema: ColumnSchema::new(
1337                    "ts",
1338                    ConcreteDataType::timestamp_millisecond_datatype(),
1339                    false,
1340                )
1341                .with_time_index(true),
1342                semantic_type: SemanticType::Timestamp,
1343                column_id: 1,
1344            })
1345            .primary_key(vec![]);
1346        let metadata = Arc::new(metadata_builder.build().unwrap());
1347
1348        let update_calls = Arc::new(AtomicUsize::new(0));
1349        let last_filter_len = Arc::new(AtomicUsize::new(0));
1350        let scanner = Box::new(RecordingScanner::new(
1351            schema,
1352            metadata,
1353            update_calls.clone(),
1354            last_filter_len.clone(),
1355        ));
1356        let scan = Arc::new(RegionScanExec::new(scanner, ScanRequest::default(), None).unwrap());
1357
1358        let sort_expr = PhysicalSortExpr {
1359            expr: Arc::new(Column::new("ts", 0)),
1360            options: SortOptions {
1361                descending: true,
1362                ..Default::default()
1363            },
1364        };
1365        let partition_ranges: Vec<Vec<PartitionRange>> = vec![vec![]];
1366        let mut plan: Arc<dyn ExecutionPlan> =
1367            Arc::new(PartSortExec::try_new(sort_expr, Some(3), partition_ranges, scan).unwrap());
1368
1369        for optimizer in state.physical_optimizers() {
1370            plan = optimizer.optimize(plan, state.config_options()).unwrap();
1371        }
1372
1373        assert!(update_calls.load(Ordering::Relaxed) > 0);
1374        assert!(last_filter_len.load(Ordering::Relaxed) > 0);
1375    }
1376
1377    #[tokio::test]
1378    async fn test_join_dynamic_filter_pushdown_reaches_region_scan() {
1379        let engine = create_test_engine().await;
1380        let engine = engine
1381            .as_any()
1382            .downcast_ref::<DatafusionQueryEngine>()
1383            .unwrap();
1384        let engine_ctx = engine.engine_context(QueryContext::arc()).unwrap();
1385        let state = engine_ctx.state();
1386
1387        assert!(
1388            state
1389                .config_options()
1390                .optimizer
1391                .enable_join_dynamic_filter_pushdown
1392        );
1393
1394        let schema = Arc::new(datatypes::schema::Schema::new(vec![ColumnSchema::new(
1395            "ts",
1396            ConcreteDataType::timestamp_millisecond_datatype(),
1397            false,
1398        )]));
1399
1400        let mut left_metadata_builder = RegionMetadataBuilder::new(RegionId::new(2048, 1));
1401        left_metadata_builder
1402            .push_column_metadata(ColumnMetadata {
1403                column_schema: ColumnSchema::new(
1404                    "ts",
1405                    ConcreteDataType::timestamp_millisecond_datatype(),
1406                    false,
1407                )
1408                .with_time_index(true),
1409                semantic_type: SemanticType::Timestamp,
1410                column_id: 1,
1411            })
1412            .primary_key(vec![]);
1413        let left_metadata = Arc::new(left_metadata_builder.build().unwrap());
1414
1415        let mut right_metadata_builder = RegionMetadataBuilder::new(RegionId::new(2048, 2));
1416        right_metadata_builder
1417            .push_column_metadata(ColumnMetadata {
1418                column_schema: ColumnSchema::new(
1419                    "ts",
1420                    ConcreteDataType::timestamp_millisecond_datatype(),
1421                    false,
1422                )
1423                .with_time_index(true),
1424                semantic_type: SemanticType::Timestamp,
1425                column_id: 1,
1426            })
1427            .primary_key(vec![]);
1428        let right_metadata = Arc::new(right_metadata_builder.build().unwrap());
1429
1430        let left_update_calls = Arc::new(AtomicUsize::new(0));
1431        let left_last_filter_len = Arc::new(AtomicUsize::new(0));
1432        let right_update_calls = Arc::new(AtomicUsize::new(0));
1433        let right_last_filter_len = Arc::new(AtomicUsize::new(0));
1434
1435        let left_scan = Arc::new(
1436            RegionScanExec::new(
1437                Box::new(RecordingScanner::new(
1438                    schema.clone(),
1439                    left_metadata,
1440                    left_update_calls.clone(),
1441                    left_last_filter_len.clone(),
1442                )),
1443                ScanRequest::default(),
1444                None,
1445            )
1446            .unwrap(),
1447        );
1448        let right_scan = Arc::new(
1449            RegionScanExec::new(
1450                Box::new(RecordingScanner::new(
1451                    schema,
1452                    right_metadata,
1453                    right_update_calls.clone(),
1454                    right_last_filter_len.clone(),
1455                )),
1456                ScanRequest::default(),
1457                None,
1458            )
1459            .unwrap(),
1460        );
1461
1462        let on: JoinOn = vec![(
1463            Arc::new(Column::new("ts", 0)) as Arc<dyn PhysicalExpr>,
1464            Arc::new(Column::new("ts", 0)) as Arc<dyn PhysicalExpr>,
1465        )];
1466
1467        let mut plan: Arc<dyn ExecutionPlan> = Arc::new(
1468            HashJoinExec::try_new(
1469                left_scan,
1470                right_scan,
1471                on,
1472                None,
1473                &JoinType::Inner,
1474                None,
1475                PartitionMode::CollectLeft,
1476                NullEquality::NullEqualsNull,
1477                false,
1478            )
1479            .unwrap(),
1480        );
1481
1482        for optimizer in state.physical_optimizers() {
1483            plan = optimizer.optimize(plan, state.config_options()).unwrap();
1484        }
1485
1486        assert!(left_update_calls.load(Ordering::Relaxed) > 0);
1487        assert_eq!(0, left_last_filter_len.load(Ordering::Relaxed));
1488        assert!(right_update_calls.load(Ordering::Relaxed) > 0);
1489        assert!(right_last_filter_len.load(Ordering::Relaxed) > 0);
1490    }
1491    #[derive(Default)]
1492    struct RecordingMutationHandler {
1493        inserts: std::sync::Mutex<Vec<table::requests::InsertRequest>>,
1494    }
1495
1496    #[async_trait]
1497    impl common_function::handlers::TableMutationHandler for RecordingMutationHandler {
1498        async fn insert(
1499            &self,
1500            request: table::requests::InsertRequest,
1501            _ctx: session::context::QueryContextRef,
1502        ) -> common_query::error::Result<common_query::Output> {
1503            self.inserts.lock().unwrap().push(request);
1504            Ok(common_query::Output::new_with_affected_rows(1))
1505        }
1506
1507        async fn delete(
1508            &self,
1509            _request: table::requests::DeleteRequest,
1510            _ctx: session::context::QueryContextRef,
1511        ) -> common_query::error::Result<common_base::AffectedRows> {
1512            unimplemented!("unexpected delete")
1513        }
1514
1515        async fn flush(
1516            &self,
1517            _request: table::requests::FlushTableRequest,
1518            _ctx: session::context::QueryContextRef,
1519        ) -> common_query::error::Result<common_base::AffectedRows> {
1520            unimplemented!("unexpected flush")
1521        }
1522
1523        async fn compact(
1524            &self,
1525            _request: table::requests::CompactTableRequest,
1526            _ctx: session::context::QueryContextRef,
1527        ) -> common_query::error::Result<common_base::AffectedRows> {
1528            unimplemented!("unexpected compact")
1529        }
1530
1531        async fn build_index(
1532            &self,
1533            _request: table::requests::BuildIndexTableRequest,
1534            _ctx: session::context::QueryContextRef,
1535        ) -> common_query::error::Result<common_base::AffectedRows> {
1536            unimplemented!("unexpected build_index")
1537        }
1538
1539        async fn flush_region(
1540            &self,
1541            _region_id: store_api::storage::RegionId,
1542            _ctx: session::context::QueryContextRef,
1543        ) -> common_query::error::Result<common_base::AffectedRows> {
1544            unimplemented!("unexpected flush_region")
1545        }
1546
1547        async fn compact_region(
1548            &self,
1549            _region_id: store_api::storage::RegionId,
1550            _ctx: session::context::QueryContextRef,
1551        ) -> common_query::error::Result<common_base::AffectedRows> {
1552            unimplemented!("unexpected compact_region")
1553        }
1554
1555        async fn cancel_region_compaction(
1556            &self,
1557            _region_id: store_api::storage::RegionId,
1558            _task_id: String,
1559            _ctx: session::context::QueryContextRef,
1560        ) -> common_query::error::Result<common_base::AffectedRows> {
1561            unimplemented!("unexpected cancel_region_compaction")
1562        }
1563
1564        async fn discard_unflushed_data(
1565            &self,
1566            _region_id: store_api::storage::RegionId,
1567            _ctx: session::context::QueryContextRef,
1568        ) -> common_query::error::Result<common_base::AffectedRows> {
1569            unimplemented!("unexpected discard_unflushed_data")
1570        }
1571
1572        async fn discard_unflushed_data_by_table(
1573            &self,
1574            _table_name: table::table_name::TableName,
1575            _ctx: session::context::QueryContextRef,
1576        ) -> common_query::error::Result<common_base::AffectedRows> {
1577            unimplemented!("unexpected discard_unflushed_data_by_table")
1578        }
1579
1580        async fn discard_pending_tails(
1581            &self,
1582            _region_id: store_api::storage::RegionId,
1583            _node_id: u64,
1584            _ctx: session::context::QueryContextRef,
1585        ) -> common_query::error::Result<common_base::AffectedRows> {
1586            unimplemented!("unexpected discard_pending_tails")
1587        }
1588
1589        async fn discard_pending_tails_by_table(
1590            &self,
1591            _table_name: table::table_name::TableName,
1592            _node_id: u64,
1593            _ctx: session::context::QueryContextRef,
1594        ) -> common_query::error::Result<common_base::AffectedRows> {
1595            unimplemented!("unexpected discard_pending_tails_by_table")
1596        }
1597    }
1598
1599    fn native_schema() -> Arc<Schema> {
1600        Arc::new(Schema::new(vec![
1601            ColumnSchema::new("dim", ConcreteDataType::date_datatype(), true),
1602            ColumnSchema::new("amount", ConcreteDataType::decimal128_datatype(30, 2), true),
1603            ColumnSchema::new(
1604                "elapsed",
1605                ConcreteDataType::duration_millisecond_datatype(),
1606                true,
1607            ),
1608            ColumnSchema::new(
1609                "ts",
1610                ConcreteDataType::timestamp_millisecond_datatype(),
1611                false,
1612            )
1613            .with_time_index(true),
1614            ColumnSchema::new(
1615                "updated_at",
1616                ConcreteDataType::timestamp_millisecond_datatype(),
1617                true,
1618            ),
1619            ColumnSchema::new("marker", ConcreteDataType::uint8_datatype(), true),
1620            ColumnSchema::new("payload", ConcreteDataType::binary_datatype(), true),
1621            ColumnSchema::new("epoch", ConcreteDataType::uint64_datatype(), true),
1622        ]))
1623    }
1624
1625    fn register_native_tables(catalog: &catalog::memory::MemoryCatalogManager) {
1626        let schema = native_schema();
1627        let meta = TableMetaBuilder::empty()
1628            .schema(schema.clone())
1629            .primary_key_indices(vec![])
1630            .value_indices((0..schema.num_columns()).collect())
1631            .next_column_id(8)
1632            .build()
1633            .unwrap();
1634        let info = TableInfoBuilder::default()
1635            .name("native_regression")
1636            .table_id(9001)
1637            .table_version(0)
1638            .meta(meta)
1639            .build()
1640            .unwrap();
1641        catalog
1642            .register_table_sync(RegisterTableRequest {
1643                catalog: DEFAULT_CATALOG_NAME.to_string(),
1644                schema: DEFAULT_SCHEMA_NAME.to_string(),
1645                table_name: "native_regression".to_string(),
1646                table_id: 9001,
1647                table: table::test_util::EmptyTable::from_table_info(&info),
1648            })
1649            .unwrap();
1650
1651        let schema = Arc::new(Schema::new(vec![
1652            ColumnSchema::new("dim", ConcreteDataType::date_datatype(), true),
1653            ColumnSchema::new("amount", ConcreteDataType::decimal128_datatype(20, 2), true),
1654            ColumnSchema::new(
1655                "elapsed",
1656                ConcreteDataType::duration_millisecond_datatype(),
1657                true,
1658            ),
1659            ColumnSchema::new(
1660                "ts",
1661                ConcreteDataType::timestamp_millisecond_datatype(),
1662                false,
1663            )
1664            .with_time_index(true),
1665        ]));
1666        let rows = RecordBatch::new(
1667            schema,
1668            vec![
1669                Arc::new(datatypes::vectors::DateVector::from_slice([0, 2])) as VectorRef,
1670                Arc::new(
1671                    datatypes::vectors::Decimal128Vector::from_slice([10000, 20000])
1672                        .with_precision_and_scale(20, 2)
1673                        .unwrap(),
1674                ) as VectorRef,
1675                Arc::new(datatypes::vectors::DurationMillisecondVector::from_values(
1676                    [10, 20],
1677                )) as VectorRef,
1678                Arc::new(datatypes::vectors::TimestampMillisecondVector::from_slice(
1679                    [1, 2],
1680                )) as VectorRef,
1681            ],
1682        )
1683        .unwrap();
1684        catalog
1685            .register_table_sync(RegisterTableRequest {
1686                catalog: DEFAULT_CATALOG_NAME.to_string(),
1687                schema: DEFAULT_SCHEMA_NAME.to_string(),
1688                table_name: "native_aggregate".to_string(),
1689                table_id: 9002,
1690                table: table::test_util::MemTable::table("native_aggregate", rows),
1691            })
1692            .unwrap();
1693    }
1694
1695    async fn run_sql(engine: &QueryEngineRef, sql: &str) -> Vec<RecordBatch> {
1696        let stmt = QueryLanguageParser::parse_sql(sql, &QueryContext::arc()).unwrap();
1697        let plan = engine
1698            .planner()
1699            .plan(&stmt, QueryContext::arc())
1700            .await
1701            .unwrap();
1702        match engine
1703            .execute(plan, QueryContext::arc())
1704            .await
1705            .unwrap()
1706            .data
1707        {
1708            OutputData::Stream(stream) => util::collect(stream).await.unwrap(),
1709            _ => unreachable!(),
1710        }
1711    }
1712
1713    #[tokio::test]
1714    async fn test_native_executor_null_insert_and_aggregates() {
1715        let catalog = catalog::memory::new_memory_catalog_manager().unwrap();
1716        register_native_tables(&catalog);
1717        let handler = Arc::new(RecordingMutationHandler::default());
1718        let engine = QueryEngineFactory::new(
1719            catalog,
1720            None,
1721            Some(handler.clone()),
1722            None,
1723            None,
1724            false,
1725            QueryOptions::default(),
1726        )
1727        .query_engine();
1728
1729        // The CASTs force Insert::can_extract_values false. This records the
1730        // QueryEngine DML path selected by operator/src/statement/dml.rs.
1731        let insert_sql = "INSERT INTO native_regression (dim, amount, elapsed, ts, updated_at, marker, payload, epoch) VALUES (NULL, NULL, NULL, CAST(-62135596799999 AS TIMESTAMP(3)), CAST(NULL AS TIMESTAMP(3)), CAST(1 AS UInt8), X'0102', CAST(1 AS UInt64))";
1732        let stmt = QueryLanguageParser::parse_sql(insert_sql, &QueryContext::arc()).unwrap();
1733        let QueryStatement::Sql(sql::statements::statement::Statement::Insert(insert)) = &stmt
1734        else {
1735            unreachable!()
1736        };
1737        assert!(!insert.can_extract_values());
1738        let plan = engine
1739            .planner()
1740            .plan(&stmt, QueryContext::arc())
1741            .await
1742            .unwrap();
1743        assert!(matches!(
1744            engine
1745                .execute(plan, QueryContext::arc())
1746                .await
1747                .unwrap()
1748                .data,
1749            OutputData::AffectedRows(1)
1750        ));
1751
1752        let request = handler.inserts.lock().unwrap().pop().unwrap();
1753        for (name, data_type) in [
1754            ("dim", ConcreteDataType::date_datatype()),
1755            ("amount", ConcreteDataType::decimal128_datatype(30, 2)),
1756            ("elapsed", ConcreteDataType::duration_millisecond_datatype()),
1757            (
1758                "updated_at",
1759                ConcreteDataType::timestamp_millisecond_datatype(),
1760            ),
1761        ] {
1762            let vector = request.columns_values.get(name).unwrap();
1763            assert_eq!(vector.len(), 1, "{name}");
1764            assert_eq!(vector.data_type(), data_type, "{name}");
1765            assert!(vector.is_null(0), "{name}");
1766        }
1767        assert!(!request.columns_values["ts"].is_null(0));
1768        for (name, data_type) in [
1769            ("marker", ConcreteDataType::uint8_datatype()),
1770            ("payload", ConcreteDataType::binary_datatype()),
1771            ("epoch", ConcreteDataType::uint64_datatype()),
1772        ] {
1773            assert_eq!(
1774                request.columns_values[name].data_type(),
1775                data_type,
1776                "{name}"
1777            );
1778        }
1779
1780        let batches = run_sql(
1781            &engine,
1782            "SELECT MIN(dim), MAX(dim), SUM(amount), SUM(elapsed) FROM native_aggregate",
1783        )
1784        .await;
1785        let batch = &batches[0];
1786        assert_eq!(batch.num_rows(), 1);
1787        for (index, (data_type, value)) in [
1788            (
1789                ConcreteDataType::date_datatype(),
1790                ScalarValue::Date32(Some(0)),
1791            ),
1792            (
1793                ConcreteDataType::date_datatype(),
1794                ScalarValue::Date32(Some(2)),
1795            ),
1796            (
1797                ConcreteDataType::decimal128_datatype(30, 2),
1798                ScalarValue::Decimal128(Some(30000), 30, 2),
1799            ),
1800            (
1801                ConcreteDataType::duration_millisecond_datatype(),
1802                ScalarValue::DurationMillisecond(Some(30)),
1803            ),
1804        ]
1805        .into_iter()
1806        .enumerate()
1807        {
1808            assert_eq!(batch.schema.column_schemas()[index].data_type, data_type);
1809            assert_eq!(
1810                ScalarValue::try_from_array(batch.column(index).as_ref(), 0).unwrap(),
1811                value
1812            );
1813        }
1814
1815        let batches = run_sql(
1816            &engine,
1817            "SELECT aggregate.amount_sum + aggregate.amount_sum AS amount_add, \
1818                    aggregate.elapsed_sum + aggregate.elapsed_sum AS elapsed_add, \
1819                    CASE WHEN aggregate.min_dim < CAST('1970-01-02' AS DATE) THEN true ELSE false END AS min_before, \
1820                    CASE WHEN aggregate.max_dim > CAST('1970-01-01' AS DATE) THEN true ELSE false END AS max_after \
1821             FROM (SELECT MIN(dim) AS min_dim, MAX(dim) AS max_dim, SUM(amount) AS amount_sum, SUM(elapsed) AS elapsed_sum \
1822                   FROM native_aggregate) AS aggregate",
1823        )
1824        .await;
1825        let batch = &batches[0];
1826        assert_eq!(batch.num_rows(), 1);
1827        for (index, (data_type, value)) in [
1828            (
1829                ConcreteDataType::decimal128_datatype(31, 2),
1830                ScalarValue::Decimal128(Some(60000), 31, 2),
1831            ),
1832            (
1833                ConcreteDataType::duration_millisecond_datatype(),
1834                ScalarValue::DurationMillisecond(Some(60)),
1835            ),
1836            (
1837                ConcreteDataType::boolean_datatype(),
1838                ScalarValue::Boolean(Some(true)),
1839            ),
1840            (
1841                ConcreteDataType::boolean_datatype(),
1842                ScalarValue::Boolean(Some(true)),
1843            ),
1844        ]
1845        .into_iter()
1846        .enumerate()
1847        {
1848            assert_eq!(batch.schema.column_schemas()[index].data_type, data_type);
1849            assert_eq!(
1850                ScalarValue::try_from_array(batch.column(index).as_ref(), 0).unwrap(),
1851                value
1852            );
1853        }
1854    }
1855}