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