1mod error;
18mod json_expr_planner;
19mod planner;
20
21use std::any::Any;
22use std::collections::HashMap;
23use std::sync::Arc;
24
25use async_trait::async_trait;
26use common_base::Plugins;
27use common_catalog::consts::is_readonly_table;
28use common_error::ext::BoxedError;
29use common_function::function::FunctionContext;
30use common_function::function_factory::ScalarFunctionFactory;
31use common_query::{Output, OutputData, OutputMeta};
32use common_recordbatch::adapter::{RecordBatchStreamAdapter, RegionQueryStatCounters};
33use common_recordbatch::{EmptyRecordBatchStream, RecordBatch, SendableRecordBatchStream};
34use common_telemetry::tracing;
35use datafusion::catalog::TableFunction;
36use datafusion::dataframe::DataFrame;
37use datafusion::physical_plan::ExecutionPlan;
38use datafusion::physical_plan::analyze::AnalyzeExec;
39use datafusion::physical_plan::coalesce_partitions::CoalescePartitionsExec;
40use datafusion_common::ResolvedTableReference;
41use datafusion_expr::{
42 AggregateUDF, DmlStatement, LogicalPlan as DfLogicalPlan, LogicalPlan, WindowUDF, WriteOp,
43};
44use datatypes::prelude::VectorRef;
45use datatypes::schema::Schema;
46use futures_util::StreamExt;
47use futures_util::future::try_join;
48use session::context::QueryContextRef;
49use snafu::{OptionExt, ResultExt, ensure};
50use sqlparser::ast::AnalyzeFormat;
51use table::TableRef;
52use table::requests::{DeleteRequest, InsertRequest};
53use table::table::scan::{REGION_SCAN_EXEC_NAME, RegionScanExec};
54use tracing::Span;
55
56use crate::analyze::DistAnalyzeExec;
57pub use crate::datafusion::planner::DfContextProviderAdapter;
58use crate::dist_plan::{
59 DistPlannerOptions, MergeScanLogicalPlan, RemoteDynFilterReceiverInjectorRef,
60};
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::options::ScheduledTimeExtension;
72use crate::physical_wrapper::PhysicalPlanWrapperRef;
73use crate::planner::{DfLogicalPlanner, LogicalPlanner};
74use crate::query_engine::{DescribeResult, QueryEngineContext, QueryEngineState};
75use crate::{QueryEngine, metrics};
76
77pub const QUERY_PARALLELISM_HINT: &str = "query_parallelism";
80
81pub const QUERY_FALLBACK_HINT: &str = "query_fallback";
83
84async fn forward_record_batches(
87 mut stream: SendableRecordBatchStream,
88 batch_tx: tokio::sync::mpsc::UnboundedSender<Result<RecordBatch>>,
89) -> Result<()> {
90 while let Some(batch) = stream.next().await {
91 match batch.context(CreateRecordBatchSnafu) {
92 Ok(batch) => {
93 if batch_tx.send(Ok(batch)).is_err() {
94 break;
95 }
96 tokio::task::yield_now().await;
97 }
98 Err(error) => {
99 let _ = batch_tx.send(Err(error));
100 break;
101 }
102 }
103 }
104 Ok(())
105}
106
107fn query_load_region_id(plan: &Arc<dyn ExecutionPlan>) -> Option<u64> {
108 let mut region_id = None;
109 let mut stack = vec![plan.clone()];
110
111 while let Some(plan) = stack.pop() {
112 if plan.name() == REGION_SCAN_EXEC_NAME
113 && let Some(scan) = plan.as_any().downcast_ref::<RegionScanExec>()
114 && let Some(scan_region_id) = scan.query_load_region_id()
115 {
116 match region_id {
117 Some(region_id) if region_id != scan_region_id => return None,
118 Some(_) => {}
119 None => region_id = Some(scan_region_id),
120 }
121 }
122 stack.extend(plan.children().into_iter().cloned());
123 }
124
125 region_id
126}
127
128fn query_stat_counters(plan: &Arc<dyn ExecutionPlan>) -> Option<RegionQueryStatCounters> {
137 let mut counters: Option<RegionQueryStatCounters> = None;
138 let mut stack = vec![plan.clone()];
139
140 while let Some(plan) = stack.pop() {
141 if plan.name() == REGION_SCAN_EXEC_NAME
142 && let Some(scan) = plan.as_any().downcast_ref::<RegionScanExec>()
143 && let Some(scan_counters) = scan.query_stat_counters()
144 {
145 match &counters {
146 Some(counters)
147 if !Arc::ptr_eq(&counters.query_cpu_time, &scan_counters.query_cpu_time)
148 || !Arc::ptr_eq(
149 &counters.query_scanned_bytes,
150 &scan_counters.query_scanned_bytes,
151 ) =>
152 {
153 return None;
154 }
155 Some(_) => {}
156 None => counters = Some(scan_counters),
157 }
158 }
159 stack.extend(plan.children().into_iter().cloned());
160 }
161
162 counters
163}
164
165pub struct DatafusionQueryEngine {
166 state: Arc<QueryEngineState>,
167 plugins: Plugins,
168}
169
170impl DatafusionQueryEngine {
171 pub fn new(state: Arc<QueryEngineState>, plugins: Plugins) -> Self {
172 Self { state, plugins }
173 }
174
175 #[tracing::instrument(skip_all)]
176 async fn exec_query_plan(
177 &self,
178 plan: LogicalPlan,
179 query_ctx: QueryContextRef,
180 ) -> Result<Output> {
181 let mut ctx = self.engine_context(query_ctx.clone());
182 let plan = if let Some(receiver_injector) =
183 self.plugins.get::<RemoteDynFilterReceiverInjectorRef>()
184 {
185 receiver_injector.maybe_inject(plan, query_ctx.clone())
186 } else {
187 plan
188 };
189
190 let physical_plan = self.create_physical_plan(&mut ctx, &plan).await?;
192 let physical_plan = self.optimize_physical_plan(&mut ctx, physical_plan)?;
193 let physical_plan = if let Some(wrapper) = self.plugins.get::<PhysicalPlanWrapperRef>() {
194 wrapper.wrap(physical_plan, query_ctx)
195 } else {
196 physical_plan
197 };
198
199 let stream = self.execute_stream(&ctx, &physical_plan)?;
200
201 Ok(Output::new(
202 OutputData::Stream(stream),
203 OutputMeta::new_with_plan(physical_plan),
204 ))
205 }
206
207 #[tracing::instrument(skip_all)]
208 async fn exec_dml_statement(
209 &self,
210 dml: DmlStatement,
211 query_ctx: QueryContextRef,
212 ) -> Result<Output> {
213 ensure!(
214 matches!(dml.op, WriteOp::Insert(_) | WriteOp::Delete),
215 UnsupportedExprSnafu {
216 name: format!("DML op {}", dml.op),
217 }
218 );
219
220 let _timer = QUERY_STAGE_ELAPSED
221 .with_label_values(&[dml.op.name()])
222 .start_timer();
223
224 let default_catalog = &query_ctx.current_catalog().to_owned();
225 let default_schema = &query_ctx.current_schema();
226 let table_name = dml.table_name.resolve(default_catalog, default_schema);
227 let table = self.find_table(&table_name, &query_ctx).await?;
228
229 let Output { data, meta } = self
230 .exec_query_plan((*dml.input).clone(), query_ctx.clone())
231 .await?;
232 let stream = match data {
233 OutputData::RecordBatches(batches) => batches.as_stream(),
234 OutputData::Stream(stream) => stream,
235 _ => unreachable!(),
236 };
237
238 let mut affected_rows = 0;
239 let mut insert_cost = 0;
240
241 match dml.op {
242 WriteOp::Insert(_) => {
243 let (batch_tx, batch_rx) = tokio::sync::mpsc::unbounded_channel();
244 let producer = forward_record_batches(stream, batch_tx);
245 let consumer = self.consume_insert_record_batches(
246 batch_rx,
247 &table_name,
248 table.schema(),
249 query_ctx.clone(),
250 );
251 let ((), (rows, cost)) = try_join(producer, consumer).await?;
252 affected_rows += rows;
253 insert_cost += cost;
254 }
255 WriteOp::Delete => {
256 let (batch_tx, batch_rx) = tokio::sync::mpsc::unbounded_channel();
259 let producer = forward_record_batches(stream, batch_tx);
260 let consumer = self.consume_delete_record_batches(
261 batch_rx,
262 &table_name,
263 &table,
264 query_ctx.clone(),
265 );
266 let (rows, ()) = try_join(consumer, producer).await?;
267 affected_rows += rows;
268 }
269 _ => unreachable!("guarded by the 'ensure!' at the beginning"),
270 }
271 Ok(Output::new(
272 OutputData::AffectedRows(affected_rows),
273 OutputMeta::new(meta.plan, insert_cost),
274 ))
275 }
276
277 async fn consume_insert_record_batches(
278 &self,
279 mut batch_rx: tokio::sync::mpsc::UnboundedReceiver<Result<RecordBatch>>,
280 table_name: &ResolvedTableReference,
281 table_schema: Arc<Schema>,
282 query_ctx: QueryContextRef,
283 ) -> Result<(usize, usize)> {
284 let mut affected_rows = 0;
285 let mut insert_cost = 0;
286 while let Some(batch) = batch_rx.recv().await {
287 let batch = batch?;
288 let column_vectors = batch
289 .column_vectors(&table_name.to_string(), table_schema.clone())
290 .map_err(BoxedError::new)
291 .context(QueryExecutionSnafu)?;
292 let output = self
294 .insert(table_name, column_vectors, query_ctx.clone())
295 .await?;
296 let (rows, cost) = output.extract_rows_and_cost();
297 affected_rows += rows;
298 insert_cost += cost;
299 }
300 Ok((affected_rows, insert_cost))
301 }
302
303 async fn consume_delete_record_batches(
304 &self,
305 mut batch_rx: tokio::sync::mpsc::UnboundedReceiver<Result<RecordBatch>>,
306 table_name: &ResolvedTableReference,
307 table: &TableRef,
308 query_ctx: QueryContextRef,
309 ) -> Result<usize> {
310 let mut affected_rows = 0;
311 while let Some(batch) = batch_rx.recv().await {
312 let batch = batch?;
313 let column_vectors = batch
314 .column_vectors(&table_name.to_string(), table.schema())
315 .map_err(BoxedError::new)
316 .context(QueryExecutionSnafu)?;
317 affected_rows += self
318 .delete(table_name, table, column_vectors, query_ctx.clone())
319 .await?;
320 }
321 Ok(affected_rows)
322 }
323
324 #[tracing::instrument(skip_all)]
325 async fn delete(
326 &self,
327 table_name: &ResolvedTableReference,
328 table: &TableRef,
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 let table_schema = table.schema();
336
337 ensure!(
338 !is_readonly_table(&schema_name, &table_name),
339 TableReadOnlySnafu { table: table_name }
340 );
341
342 let ts_column = table_schema
343 .timestamp_column()
344 .map(|x| &x.name)
345 .with_context(|| MissingTimestampColumnSnafu {
346 table_name: table_name.clone(),
347 })?;
348
349 let table_info = table.table_info();
350 let rowkey_columns = table_info
351 .meta
352 .row_key_column_names()
353 .collect::<Vec<&String>>();
354 let column_vectors = column_vectors
355 .into_iter()
356 .filter(|x| &x.0 == ts_column || rowkey_columns.contains(&&x.0))
357 .collect::<HashMap<_, _>>();
358
359 let request = DeleteRequest {
360 catalog_name,
361 schema_name,
362 table_name,
363 key_column_values: column_vectors,
364 };
365
366 self.state
367 .table_mutation_handler()
368 .context(MissingTableMutationHandlerSnafu)?
369 .delete(request, query_ctx)
370 .await
371 .context(TableMutationSnafu)
372 }
373
374 #[tracing::instrument(skip_all)]
375 async fn insert(
376 &self,
377 table_name: &ResolvedTableReference,
378 column_vectors: HashMap<String, VectorRef>,
379 query_ctx: QueryContextRef,
380 ) -> Result<Output> {
381 let catalog_name = table_name.catalog.to_string();
382 let schema_name = table_name.schema.to_string();
383 let table_name = table_name.table.to_string();
384
385 ensure!(
386 !is_readonly_table(&schema_name, &table_name),
387 TableReadOnlySnafu { table: table_name }
388 );
389
390 let request = InsertRequest {
391 catalog_name,
392 schema_name,
393 table_name,
394 columns_values: column_vectors,
395 };
396
397 self.state
398 .table_mutation_handler()
399 .context(MissingTableMutationHandlerSnafu)?
400 .insert(request, query_ctx)
401 .await
402 .context(TableMutationSnafu)
403 }
404
405 async fn find_table(
406 &self,
407 table_name: &ResolvedTableReference,
408 query_context: &QueryContextRef,
409 ) -> Result<TableRef> {
410 let catalog_name = table_name.catalog.as_ref();
411 let schema_name = table_name.schema.as_ref();
412 let table_name = table_name.table.as_ref();
413
414 self.state
415 .catalog_manager()
416 .table(catalog_name, schema_name, table_name, Some(query_context))
417 .await
418 .context(CatalogSnafu)?
419 .with_context(|| TableNotFoundSnafu { table: table_name })
420 }
421
422 #[tracing::instrument(skip_all)]
423 async fn create_physical_plan(
424 &self,
425 ctx: &mut QueryEngineContext,
426 logical_plan: &LogicalPlan,
427 ) -> Result<Arc<dyn ExecutionPlan>> {
428 #[derive(Debug)]
432 struct PanicLogger<'a> {
433 input_logical_plan: &'a LogicalPlan,
434 after_analyze: Option<LogicalPlan>,
435 after_optimize: Option<LogicalPlan>,
436 phy_plan: Option<Arc<dyn ExecutionPlan>>,
437 }
438 impl Drop for PanicLogger<'_> {
439 fn drop(&mut self) {
440 if std::thread::panicking() {
441 common_telemetry::error!(
442 "Panic while creating physical plan, input logical plan: {:?}, after analyze: {:?}, after optimize: {:?}, final physical plan: {:?}",
443 self.input_logical_plan,
444 self.after_analyze,
445 self.after_optimize,
446 self.phy_plan
447 );
448 }
449 }
450 }
451
452 let mut logger = PanicLogger {
453 input_logical_plan: logical_plan,
454 after_analyze: None,
455 after_optimize: None,
456 phy_plan: None,
457 };
458
459 let _timer = metrics::CREATE_PHYSICAL_ELAPSED.start_timer();
460 let state = ctx.state();
461
462 common_telemetry::debug!("Create physical plan, input plan: {logical_plan}");
463
464 if matches!(logical_plan, DfLogicalPlan::Explain(_)) {
466 return state
467 .create_physical_plan(logical_plan)
468 .await
469 .map_err(Into::into);
470 }
471
472 let analyzed_plan = state.analyzer().execute_and_check(
474 logical_plan.clone(),
475 state.config_options(),
476 |_, _| {},
477 )?;
478
479 logger.after_analyze = Some(analyzed_plan.clone());
480
481 common_telemetry::debug!("Create physical plan, analyzed plan: {analyzed_plan}");
482
483 let optimized_plan = if let DfLogicalPlan::Extension(ext) = &analyzed_plan
485 && ext.node.name() == MergeScanLogicalPlan::name()
486 {
487 analyzed_plan.clone()
488 } else {
489 state
490 .optimizer()
491 .optimize(analyzed_plan, state, |_, _| {})?
492 };
493
494 common_telemetry::debug!("Create physical plan, optimized plan: {optimized_plan}");
495 logger.after_optimize = Some(optimized_plan.clone());
496
497 let physical_plan = state
498 .query_planner()
499 .create_physical_plan(&optimized_plan, state)
500 .await?;
501
502 logger.phy_plan = Some(physical_plan.clone());
503 drop(logger);
504 Ok(physical_plan)
505 }
506
507 #[tracing::instrument(skip_all)]
508 fn optimize_physical_plan(
509 &self,
510 ctx: &mut QueryEngineContext,
511 plan: Arc<dyn ExecutionPlan>,
512 ) -> Result<Arc<dyn ExecutionPlan>> {
513 let _timer = metrics::OPTIMIZE_PHYSICAL_ELAPSED.start_timer();
514
515 let optimized_plan = if let Some(analyze_plan) = plan.as_any().downcast_ref::<AnalyzeExec>()
522 {
523 let format = if let Some(format) = ctx.query_ctx().explain_format()
524 && format.to_lowercase() == "json"
525 {
526 AnalyzeFormat::JSON
527 } else {
528 AnalyzeFormat::TEXT
529 };
530 ctx.query_ctx().set_explain_verbose(analyze_plan.verbose());
533
534 Arc::new(DistAnalyzeExec::new(
535 analyze_plan.input().clone(),
536 analyze_plan.verbose(),
537 format,
538 ))
539 } else {
547 plan
548 };
556
557 Ok(optimized_plan)
558 }
559}
560
561#[async_trait]
562impl QueryEngine for DatafusionQueryEngine {
563 fn as_any(&self) -> &dyn Any {
564 self
565 }
566
567 fn planner(&self) -> Arc<dyn LogicalPlanner> {
568 Arc::new(DfLogicalPlanner::new(self.state.clone()))
569 }
570
571 fn name(&self) -> &str {
572 "datafusion"
573 }
574
575 async fn describe(
576 &self,
577 plan: LogicalPlan,
578 _query_ctx: QueryContextRef,
579 ) -> Result<DescribeResult> {
580 Ok(DescribeResult { logical_plan: plan })
581 }
582
583 async fn execute(&self, plan: LogicalPlan, query_ctx: QueryContextRef) -> Result<Output> {
584 match plan {
585 LogicalPlan::Dml(dml) => self.exec_dml_statement(dml, query_ctx).await,
586 _ => self.exec_query_plan(plan, query_ctx).await,
587 }
588 }
589
590 fn register_aggregate_function(&self, func: AggregateUDF) {
598 self.state.register_aggr_function(func);
599 }
600
601 fn register_scalar_function(&self, func: ScalarFunctionFactory) {
604 self.state.register_scalar_function(func);
605 }
606
607 fn register_table_function(&self, func: Arc<TableFunction>) {
608 self.state.register_table_function(func);
609 }
610
611 fn register_window_function(&self, func: WindowUDF) {
612 self.state.register_window_function(func);
613 }
614
615 fn read_table(&self, table: TableRef) -> Result<DataFrame> {
616 self.state.read_table(table).map_err(Into::into)
617 }
618
619 fn engine_context(&self, query_ctx: QueryContextRef) -> QueryEngineContext {
620 let mut state = self.state.session_state();
621 state.config_mut().set_extension(query_ctx.clone());
622 state.config_mut().set_extension(self.state.clone());
623 if let Some(parallelism) = query_ctx.extension(QUERY_PARALLELISM_HINT) {
626 if let Ok(n) = parallelism.parse::<u64>() {
627 if n > 0 {
628 let new_cfg = state.config().clone().with_target_partitions(n as usize);
629 *state.config_mut() = new_cfg;
630 }
631 } else {
632 common_telemetry::warn!(
633 "Failed to parse query_parallelism: {}, using default value",
634 parallelism
635 );
636 }
637 }
638
639 state.config_mut().options_mut().execution.time_zone =
641 Some(query_ctx.timezone().to_string());
642
643 if query_ctx.configuration_parameter().allow_query_fallback() {
646 state
647 .config_mut()
648 .options_mut()
649 .extensions
650 .insert(DistPlannerOptions {
651 allow_query_fallback: true,
652 });
653 } else if let Some(fallback) = query_ctx.extension(QUERY_FALLBACK_HINT) {
654 if fallback.to_lowercase().parse::<bool>().unwrap_or(false) {
657 state
658 .config_mut()
659 .options_mut()
660 .extensions
661 .insert(DistPlannerOptions {
662 allow_query_fallback: true,
663 });
664 }
665 }
666
667 state
668 .config_mut()
669 .options_mut()
670 .extensions
671 .insert(FunctionContext {
672 query_ctx: query_ctx.clone(),
673 state: self.engine_state().function_state(),
674 });
675
676 state
680 .config_mut()
681 .options_mut()
682 .extensions
683 .insert(ScheduledTimeExtension {
684 scheduled_time: crate::options::scheduled_time_from_ctx(&query_ctx),
685 });
686
687 let config_options = state.config_options().clone();
688 let _ = state
689 .execution_props_mut()
690 .config_options
691 .insert(config_options);
692
693 match crate::options::parse_scheduled_time_datetime(&query_ctx.extensions()) {
697 Ok(Some(scheduled_rt)) => {
698 state.execution_props_mut().query_execution_start_time = Some(scheduled_rt);
699 }
700 Ok(None) => {}
701 Err(err) => {
702 common_telemetry::warn!(err; "Ignoring invalid scheduled time query extension");
703 }
704 }
705
706 QueryEngineContext::new(state, query_ctx)
707 }
708
709 fn engine_state(&self) -> &QueryEngineState {
710 &self.state
711 }
712}
713
714impl QueryExecutor for DatafusionQueryEngine {
715 #[tracing::instrument(skip_all)]
716 fn execute_stream(
717 &self,
718 ctx: &QueryEngineContext,
719 plan: &Arc<dyn ExecutionPlan>,
720 ) -> Result<SendableRecordBatchStream> {
721 let query_ctx = ctx.query_ctx();
722 let explain_verbose = query_ctx.explain_verbose();
723 let should_collect_region_watermark =
724 should_collect_region_watermark_from_query_ctx(&query_ctx)?;
725 let output_partitions = plan.properties().output_partitioning().partition_count();
726 if explain_verbose {
727 common_telemetry::info!("Executing query plan, output_partitions: {output_partitions}");
728 }
729
730 let exec_timer = metrics::EXEC_PLAN_ELAPSED.start_timer();
731 let task_ctx = ctx.build_task_ctx();
732 let span = Span::current();
733
734 match plan.properties().output_partitioning().partition_count() {
735 0 => {
736 let schema = Arc::new(
737 Schema::try_from(plan.schema())
738 .map_err(BoxedError::new)
739 .context(QueryExecutionSnafu)?,
740 );
741 Ok(Box::pin(EmptyRecordBatchStream::new(schema)))
742 }
743 1 => {
744 let df_stream = plan.execute(0, task_ctx)?;
745 let mut stream = RecordBatchStreamAdapter::try_new_with_span(df_stream, span)
746 .context(error::ConvertDfRecordBatchStreamSnafu)
747 .map_err(BoxedError::new)
748 .context(QueryExecutionSnafu)?;
749 stream.set_metrics2(plan.clone());
750 stream.set_query_load_region_id(query_load_region_id(plan));
751 stream.set_query_stat_counters(query_stat_counters(plan));
752 stream.set_explain_verbose(explain_verbose);
753 let stream = OnDone::new(Box::pin(stream), move || {
754 let exec_cost = exec_timer.stop_and_record();
755 if explain_verbose {
756 common_telemetry::info!(
757 "DatafusionQueryEngine execute 1 stream, cost: {:?}s",
758 exec_cost,
759 );
760 }
761 });
762 Ok(maybe_attach_region_watermark_metrics(
763 Box::pin(stream),
764 plan.clone(),
765 should_collect_region_watermark,
766 ))
767 }
768 _ => {
769 let merged_plan = CoalescePartitionsExec::new(plan.clone());
771 assert_eq!(
773 1,
774 merged_plan
775 .properties()
776 .output_partitioning()
777 .partition_count()
778 );
779 let df_stream = merged_plan.execute(0, task_ctx)?;
780 let mut stream = RecordBatchStreamAdapter::try_new_with_span(df_stream, span)
781 .context(error::ConvertDfRecordBatchStreamSnafu)
782 .map_err(BoxedError::new)
783 .context(QueryExecutionSnafu)?;
784 stream.set_metrics2(plan.clone());
785 stream.set_query_load_region_id(query_load_region_id(plan));
786 stream.set_query_stat_counters(query_stat_counters(plan));
787 stream.set_explain_verbose(explain_verbose);
788 let stream = OnDone::new(Box::pin(stream), move || {
789 let exec_cost = exec_timer.stop_and_record();
790 if explain_verbose {
791 common_telemetry::info!(
792 "DatafusionQueryEngine execute {output_partitions} stream, cost: {:?}s",
793 exec_cost
794 );
795 }
796 });
797 Ok(maybe_attach_region_watermark_metrics(
798 Box::pin(stream),
799 plan.clone(),
800 should_collect_region_watermark,
801 ))
802 }
803 }
804 }
805}
806
807#[cfg(test)]
808mod tests {
809 use std::fmt;
810 use std::sync::Arc;
811 use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
812
813 use api::v1::SemanticType;
814 use arrow::array::{ArrayRef, UInt64Array};
815 use arrow_schema::SortOptions;
816 use catalog::RegisterTableRequest;
817 use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, NUMBERS_TABLE_ID};
818 use common_error::ext::BoxedError;
819 use common_recordbatch::{EmptyRecordBatchStream, SendableRecordBatchStream, util};
820 use datafusion::physical_plan::display::{DisplayAs, DisplayFormatType};
821 use datafusion::physical_plan::expressions::PhysicalSortExpr;
822 use datafusion::physical_plan::joins::{HashJoinExec, JoinOn, PartitionMode};
823 use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet;
824 use datafusion::physical_plan::{ExecutionPlan, PhysicalExpr};
825 use datafusion::prelude::{col, lit};
826 use datafusion_common::{JoinType, NullEquality};
827 use datafusion_physical_expr::expressions::Column;
828 use datatypes::prelude::ConcreteDataType;
829 use datatypes::schema::{ColumnSchema, SchemaRef};
830 use datatypes::vectors::{Helper, UInt32Vector, VectorRef};
831 use session::context::{QueryContext, QueryContextBuilder};
832 use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder, RegionMetadataRef};
833 use store_api::region_engine::{
834 PartitionRange, PrepareRequest, QueryScanContext, RegionScanner, ScannerProperties,
835 };
836 use store_api::storage::{RegionId, ScanRequest};
837 use table::table::numbers::{NUMBERS_TABLE_NAME, NumbersTable};
838 use table::table::scan::RegionScanExec;
839
840 use super::*;
841 use crate::options::QueryOptions;
842 use crate::parser::QueryLanguageParser;
843 use crate::part_sort::PartSortExec;
844 use crate::query_engine::{QueryEngineFactory, QueryEngineRef};
845
846 #[derive(Debug)]
847 struct RecordingScanner {
848 schema: SchemaRef,
849 metadata: RegionMetadataRef,
850 properties: ScannerProperties,
851 update_calls: Arc<AtomicUsize>,
852 last_filter_len: Arc<AtomicUsize>,
853 }
854
855 impl RecordingScanner {
856 fn new(
857 schema: SchemaRef,
858 metadata: RegionMetadataRef,
859 update_calls: Arc<AtomicUsize>,
860 last_filter_len: Arc<AtomicUsize>,
861 ) -> Self {
862 Self {
863 schema,
864 metadata,
865 properties: ScannerProperties::default(),
866 update_calls,
867 last_filter_len,
868 }
869 }
870 }
871
872 impl RegionScanner for RecordingScanner {
873 fn name(&self) -> &str {
874 "RecordingScanner"
875 }
876
877 fn properties(&self) -> &ScannerProperties {
878 &self.properties
879 }
880
881 fn schema(&self) -> SchemaRef {
882 self.schema.clone()
883 }
884
885 fn metadata(&self) -> RegionMetadataRef {
886 self.metadata.clone()
887 }
888
889 fn prepare(&mut self, request: PrepareRequest) -> std::result::Result<(), BoxedError> {
890 self.properties.prepare(request);
891 Ok(())
892 }
893
894 fn scan_partition(
895 &self,
896 _ctx: &QueryScanContext,
897 _metrics_set: &ExecutionPlanMetricsSet,
898 _partition: usize,
899 ) -> std::result::Result<SendableRecordBatchStream, BoxedError> {
900 Ok(Box::pin(EmptyRecordBatchStream::new(self.schema.clone())))
901 }
902
903 fn has_predicate_without_region(&self) -> bool {
904 true
905 }
906
907 fn add_dyn_filter_to_predicate(
908 &mut self,
909 filter_exprs: Vec<Arc<dyn PhysicalExpr>>,
910 ) -> Vec<bool> {
911 self.update_calls.fetch_add(1, Ordering::Relaxed);
912 self.last_filter_len
913 .store(filter_exprs.len(), Ordering::Relaxed);
914 vec![true; filter_exprs.len()]
915 }
916
917 fn set_logical_region(&mut self, logical_region: bool) {
918 self.properties.set_logical_region(logical_region);
919 }
920
921 fn set_query_load_region_id(&mut self, region_id: store_api::storage::RegionId) {
922 self.properties.set_query_load_region_id(region_id);
923 }
924 }
925
926 impl DisplayAs for RecordingScanner {
927 fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter<'_>) -> fmt::Result {
928 write!(f, "RecordingScanner")
929 }
930 }
931
932 fn build_query_load_region_scan(
933 query_load_region_id: Option<RegionId>,
934 ) -> Arc<dyn ExecutionPlan> {
935 build_region_scan(query_load_region_id, None)
936 }
937
938 fn build_query_stat_counter_region_scan(
939 counters: RegionQueryStatCounters,
940 ) -> Arc<dyn ExecutionPlan> {
941 build_region_scan(None, Some(counters))
942 }
943
944 fn build_region_scan(
945 query_load_region_id: Option<RegionId>,
946 query_stat_counters: Option<RegionQueryStatCounters>,
947 ) -> Arc<dyn ExecutionPlan> {
948 let schema = Arc::new(datatypes::schema::Schema::new(vec![ColumnSchema::new(
949 "ts",
950 ConcreteDataType::timestamp_millisecond_datatype(),
951 false,
952 )]));
953
954 let mut metadata_builder = RegionMetadataBuilder::new(RegionId::new(1024, 1));
955 metadata_builder
956 .push_column_metadata(ColumnMetadata {
957 column_schema: ColumnSchema::new(
958 "ts",
959 ConcreteDataType::timestamp_millisecond_datatype(),
960 false,
961 )
962 .with_time_index(true),
963 semantic_type: SemanticType::Timestamp,
964 column_id: 1,
965 })
966 .primary_key(vec![]);
967 let metadata = Arc::new(metadata_builder.build().unwrap());
968 let mut scanner = RecordingScanner::new(
969 schema,
970 metadata,
971 Arc::new(AtomicUsize::new(0)),
972 Arc::new(AtomicUsize::new(0)),
973 );
974 if let Some(region_id) = query_load_region_id {
975 scanner.set_query_load_region_id(region_id);
976 }
977 if let Some(counters) = query_stat_counters {
978 scanner.properties.set_query_stat_counters(counters);
979 }
980
981 Arc::new(RegionScanExec::new(Box::new(scanner), ScanRequest::default(), None).unwrap())
982 }
983
984 fn query_stat_counters_for_test() -> RegionQueryStatCounters {
985 RegionQueryStatCounters {
986 query_cpu_time: Arc::new(AtomicU64::new(0)),
987 query_scanned_bytes: Arc::new(AtomicU64::new(0)),
988 }
989 }
990
991 #[test]
992 fn query_load_region_id_ignores_scans_without_region_id() {
993 let query_load_region_id = RegionId::new(1024, 42);
994 let scan_without_region_id = build_query_load_region_scan(None);
995 let scan_with_region_id = build_query_load_region_scan(Some(query_load_region_id));
996 let on: JoinOn = vec![(
997 Arc::new(Column::new("ts", 0)) as Arc<dyn PhysicalExpr>,
998 Arc::new(Column::new("ts", 0)) as Arc<dyn PhysicalExpr>,
999 )];
1000 let plan: Arc<dyn ExecutionPlan> = Arc::new(
1001 HashJoinExec::try_new(
1002 scan_without_region_id,
1003 scan_with_region_id,
1004 on,
1005 None,
1006 &JoinType::Inner,
1007 None,
1008 PartitionMode::CollectLeft,
1009 NullEquality::NullEqualsNull,
1010 false,
1011 )
1012 .unwrap(),
1013 );
1014
1015 assert_eq!(
1016 super::query_load_region_id(&plan),
1017 Some(query_load_region_id.as_u64())
1018 );
1019 }
1020
1021 #[test]
1022 fn query_stat_counters_returns_shared_counter_for_multi_scan_plan() {
1023 let counters = query_stat_counters_for_test();
1024 let left = build_query_stat_counter_region_scan(counters.clone());
1025 let right = build_query_stat_counter_region_scan(counters.clone());
1026 let on: JoinOn = vec![(
1027 Arc::new(Column::new("ts", 0)) as Arc<dyn PhysicalExpr>,
1028 Arc::new(Column::new("ts", 0)) as Arc<dyn PhysicalExpr>,
1029 )];
1030 let plan: Arc<dyn ExecutionPlan> = Arc::new(
1031 HashJoinExec::try_new(
1032 left,
1033 right,
1034 on,
1035 None,
1036 &JoinType::Inner,
1037 None,
1038 PartitionMode::CollectLeft,
1039 NullEquality::NullEqualsNull,
1040 false,
1041 )
1042 .unwrap(),
1043 );
1044
1045 let actual = super::query_stat_counters(&plan).unwrap();
1046 assert!(Arc::ptr_eq(
1047 &actual.query_cpu_time,
1048 &counters.query_cpu_time
1049 ));
1050 assert!(Arc::ptr_eq(
1051 &actual.query_scanned_bytes,
1052 &counters.query_scanned_bytes
1053 ));
1054 }
1055
1056 #[test]
1057 fn query_stat_counters_ignores_mixed_counter_plan() {
1058 let left = build_query_stat_counter_region_scan(query_stat_counters_for_test());
1059 let right = build_query_stat_counter_region_scan(query_stat_counters_for_test());
1060 let on: JoinOn = vec![(
1061 Arc::new(Column::new("ts", 0)) as Arc<dyn PhysicalExpr>,
1062 Arc::new(Column::new("ts", 0)) as Arc<dyn PhysicalExpr>,
1063 )];
1064 let plan: Arc<dyn ExecutionPlan> = Arc::new(
1065 HashJoinExec::try_new(
1066 left,
1067 right,
1068 on,
1069 None,
1070 &JoinType::Inner,
1071 None,
1072 PartitionMode::CollectLeft,
1073 NullEquality::NullEqualsNull,
1074 false,
1075 )
1076 .unwrap(),
1077 );
1078
1079 assert!(super::query_stat_counters(&plan).is_none());
1080 }
1081
1082 async fn create_test_engine() -> QueryEngineRef {
1083 let catalog_manager = catalog::memory::new_memory_catalog_manager().unwrap();
1084 let req = RegisterTableRequest {
1085 catalog: DEFAULT_CATALOG_NAME.to_string(),
1086 schema: DEFAULT_SCHEMA_NAME.to_string(),
1087 table_name: NUMBERS_TABLE_NAME.to_string(),
1088 table_id: NUMBERS_TABLE_ID,
1089 table: NumbersTable::table(NUMBERS_TABLE_ID),
1090 };
1091 catalog_manager.register_table_sync(req).unwrap();
1092
1093 QueryEngineFactory::new(
1094 catalog_manager,
1095 None,
1096 None,
1097 None,
1098 None,
1099 false,
1100 QueryOptions::default(),
1101 )
1102 .query_engine()
1103 }
1104
1105 #[tokio::test]
1106 async fn test_sql_to_plan() {
1107 let engine = create_test_engine().await;
1108 let sql = "select sum(number) from numbers limit 20";
1109
1110 let stmt = QueryLanguageParser::parse_sql(sql, &QueryContext::arc()).unwrap();
1111 let plan = engine
1112 .planner()
1113 .plan(&stmt, QueryContext::arc())
1114 .await
1115 .unwrap();
1116
1117 assert_eq!(
1118 plan.to_string(),
1119 r#"Limit: skip=0, fetch=20
1120 Projection: sum(numbers.number)
1121 Aggregate: groupBy=[[]], aggr=[[sum(numbers.number)]]
1122 TableScan: numbers"#
1123 );
1124 }
1125
1126 #[tokio::test]
1127 async fn test_purge_table_is_not_available_to_select() {
1128 let engine = create_test_engine().await;
1129 let stmt =
1130 QueryLanguageParser::parse_sql("select purge_table('numbers')", &QueryContext::arc())
1131 .unwrap();
1132
1133 assert!(
1134 engine
1135 .planner()
1136 .plan(&stmt, QueryContext::arc())
1137 .await
1138 .is_err()
1139 );
1140 }
1141
1142 #[tokio::test]
1143 async fn test_execute() {
1144 let engine = create_test_engine().await;
1145 let sql = "select sum(number) from numbers limit 20";
1146
1147 let stmt = QueryLanguageParser::parse_sql(sql, &QueryContext::arc()).unwrap();
1148 let plan = engine
1149 .planner()
1150 .plan(&stmt, QueryContext::arc())
1151 .await
1152 .unwrap();
1153
1154 let output = engine.execute(plan, QueryContext::arc()).await.unwrap();
1155
1156 match output.data {
1157 OutputData::Stream(recordbatch) => {
1158 let numbers = util::collect(recordbatch).await.unwrap();
1159 assert_eq!(1, numbers.len());
1160 assert_eq!(numbers[0].num_columns(), 1);
1161 assert_eq!(1, numbers[0].schema.num_columns());
1162 assert_eq!(
1163 "sum(numbers.number)",
1164 numbers[0].schema.column_schemas()[0].name
1165 );
1166
1167 let batch = &numbers[0];
1168 assert_eq!(1, batch.num_columns());
1169 assert_eq!(batch.column(0).len(), 1);
1170
1171 let expected = Arc::new(UInt64Array::from_iter_values([4950])) as ArrayRef;
1172 assert_eq!(batch.column(0), &expected);
1173 }
1174 _ => unreachable!(),
1175 }
1176 }
1177
1178 #[tokio::test]
1179 async fn test_read_table() {
1180 let engine = create_test_engine().await;
1181
1182 let engine = engine
1183 .as_any()
1184 .downcast_ref::<DatafusionQueryEngine>()
1185 .unwrap();
1186 let query_ctx = Arc::new(QueryContextBuilder::default().build());
1187 let table = engine
1188 .find_table(
1189 &ResolvedTableReference {
1190 catalog: "greptime".into(),
1191 schema: "public".into(),
1192 table: "numbers".into(),
1193 },
1194 &query_ctx,
1195 )
1196 .await
1197 .unwrap();
1198
1199 let df = engine.read_table(table).unwrap();
1200 let df = df
1201 .select_columns(&["number"])
1202 .unwrap()
1203 .filter(col("number").lt(lit(10)))
1204 .unwrap();
1205 let batches = df.collect().await.unwrap();
1206 assert_eq!(1, batches.len());
1207 let batch = &batches[0];
1208
1209 assert_eq!(1, batch.num_columns());
1210 assert_eq!(batch.column(0).len(), 10);
1211
1212 assert_eq!(
1213 Helper::try_into_vector(batch.column(0)).unwrap(),
1214 Arc::new(UInt32Vector::from_slice([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])) as VectorRef
1215 );
1216 }
1217
1218 #[tokio::test]
1219 async fn test_describe() {
1220 let engine = create_test_engine().await;
1221 let sql = "select sum(number) from numbers limit 20";
1222
1223 let stmt = QueryLanguageParser::parse_sql(sql, &QueryContext::arc()).unwrap();
1224
1225 let plan = engine
1226 .planner()
1227 .plan(&stmt, QueryContext::arc())
1228 .await
1229 .unwrap();
1230
1231 let DescribeResult { logical_plan } =
1232 engine.describe(plan, QueryContext::arc()).await.unwrap();
1233
1234 let schema: Schema = logical_plan.schema().clone().try_into().unwrap();
1235
1236 assert_eq!(
1237 schema.column_schemas()[0],
1238 ColumnSchema::new(
1239 "sum(numbers.number)",
1240 ConcreteDataType::uint64_datatype(),
1241 true
1242 )
1243 );
1244 assert_eq!(
1245 "Limit: skip=0, fetch=20\n Projection: sum(numbers.number)\n Aggregate: groupBy=[[]], aggr=[[sum(numbers.number)]]\n TableScan: numbers",
1246 format!("{}", logical_plan.display_indent())
1247 );
1248 }
1249
1250 #[tokio::test]
1251 async fn test_topk_dynamic_filter_pushdown_reaches_region_scan() {
1252 let engine = create_test_engine().await;
1253 let engine = engine
1254 .as_any()
1255 .downcast_ref::<DatafusionQueryEngine>()
1256 .unwrap();
1257 let engine_ctx = engine.engine_context(QueryContext::arc());
1258 let state = engine_ctx.state();
1259
1260 let schema = Arc::new(datatypes::schema::Schema::new(vec![ColumnSchema::new(
1261 "ts",
1262 ConcreteDataType::timestamp_millisecond_datatype(),
1263 false,
1264 )]));
1265
1266 let mut metadata_builder = RegionMetadataBuilder::new(RegionId::new(1024, 1));
1267 metadata_builder
1268 .push_column_metadata(ColumnMetadata {
1269 column_schema: ColumnSchema::new(
1270 "ts",
1271 ConcreteDataType::timestamp_millisecond_datatype(),
1272 false,
1273 )
1274 .with_time_index(true),
1275 semantic_type: SemanticType::Timestamp,
1276 column_id: 1,
1277 })
1278 .primary_key(vec![]);
1279 let metadata = Arc::new(metadata_builder.build().unwrap());
1280
1281 let update_calls = Arc::new(AtomicUsize::new(0));
1282 let last_filter_len = Arc::new(AtomicUsize::new(0));
1283 let scanner = Box::new(RecordingScanner::new(
1284 schema,
1285 metadata,
1286 update_calls.clone(),
1287 last_filter_len.clone(),
1288 ));
1289 let scan = Arc::new(RegionScanExec::new(scanner, ScanRequest::default(), None).unwrap());
1290
1291 let sort_expr = PhysicalSortExpr {
1292 expr: Arc::new(Column::new("ts", 0)),
1293 options: SortOptions {
1294 descending: true,
1295 ..Default::default()
1296 },
1297 };
1298 let partition_ranges: Vec<Vec<PartitionRange>> = vec![vec![]];
1299 let mut plan: Arc<dyn ExecutionPlan> =
1300 Arc::new(PartSortExec::try_new(sort_expr, Some(3), partition_ranges, scan).unwrap());
1301
1302 for optimizer in state.physical_optimizers() {
1303 plan = optimizer.optimize(plan, state.config_options()).unwrap();
1304 }
1305
1306 assert!(update_calls.load(Ordering::Relaxed) > 0);
1307 assert!(last_filter_len.load(Ordering::Relaxed) > 0);
1308 }
1309
1310 #[tokio::test]
1311 async fn test_join_dynamic_filter_pushdown_reaches_region_scan() {
1312 let engine = create_test_engine().await;
1313 let engine = engine
1314 .as_any()
1315 .downcast_ref::<DatafusionQueryEngine>()
1316 .unwrap();
1317 let engine_ctx = engine.engine_context(QueryContext::arc());
1318 let state = engine_ctx.state();
1319
1320 assert!(
1321 state
1322 .config_options()
1323 .optimizer
1324 .enable_join_dynamic_filter_pushdown
1325 );
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 left_metadata_builder = RegionMetadataBuilder::new(RegionId::new(2048, 1));
1334 left_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 left_metadata = Arc::new(left_metadata_builder.build().unwrap());
1347
1348 let mut right_metadata_builder = RegionMetadataBuilder::new(RegionId::new(2048, 2));
1349 right_metadata_builder
1350 .push_column_metadata(ColumnMetadata {
1351 column_schema: ColumnSchema::new(
1352 "ts",
1353 ConcreteDataType::timestamp_millisecond_datatype(),
1354 false,
1355 )
1356 .with_time_index(true),
1357 semantic_type: SemanticType::Timestamp,
1358 column_id: 1,
1359 })
1360 .primary_key(vec![]);
1361 let right_metadata = Arc::new(right_metadata_builder.build().unwrap());
1362
1363 let left_update_calls = Arc::new(AtomicUsize::new(0));
1364 let left_last_filter_len = Arc::new(AtomicUsize::new(0));
1365 let right_update_calls = Arc::new(AtomicUsize::new(0));
1366 let right_last_filter_len = Arc::new(AtomicUsize::new(0));
1367
1368 let left_scan = Arc::new(
1369 RegionScanExec::new(
1370 Box::new(RecordingScanner::new(
1371 schema.clone(),
1372 left_metadata,
1373 left_update_calls.clone(),
1374 left_last_filter_len.clone(),
1375 )),
1376 ScanRequest::default(),
1377 None,
1378 )
1379 .unwrap(),
1380 );
1381 let right_scan = Arc::new(
1382 RegionScanExec::new(
1383 Box::new(RecordingScanner::new(
1384 schema,
1385 right_metadata,
1386 right_update_calls.clone(),
1387 right_last_filter_len.clone(),
1388 )),
1389 ScanRequest::default(),
1390 None,
1391 )
1392 .unwrap(),
1393 );
1394
1395 let on: JoinOn = vec![(
1396 Arc::new(Column::new("ts", 0)) as Arc<dyn PhysicalExpr>,
1397 Arc::new(Column::new("ts", 0)) as Arc<dyn PhysicalExpr>,
1398 )];
1399
1400 let mut plan: Arc<dyn ExecutionPlan> = Arc::new(
1401 HashJoinExec::try_new(
1402 left_scan,
1403 right_scan,
1404 on,
1405 None,
1406 &JoinType::Inner,
1407 None,
1408 PartitionMode::CollectLeft,
1409 NullEquality::NullEqualsNull,
1410 false,
1411 )
1412 .unwrap(),
1413 );
1414
1415 for optimizer in state.physical_optimizers() {
1416 plan = optimizer.optimize(plan, state.config_options()).unwrap();
1417 }
1418
1419 assert!(left_update_calls.load(Ordering::Relaxed) > 0);
1420 assert_eq!(0, left_last_filter_len.load(Ordering::Relaxed));
1421 assert!(right_update_calls.load(Ordering::Relaxed) > 0);
1422 assert!(right_last_filter_len.load(Ordering::Relaxed) > 0);
1423 }
1424}