|
| 1 | +use crate::DefaultSessionBuilder; |
| 2 | +use crate::DistributedPhysicalOptimizerRule; |
| 3 | +use crate::test_utils::localhost::start_localhost_context; |
| 4 | +use crate::test_utils::parquet::register_parquet_tables; |
| 5 | +use async_trait::async_trait; |
| 6 | +use datafusion::arrow::array::RecordBatch; |
| 7 | +use datafusion::arrow::array::{ArrayRef, StringArray}; |
| 8 | +use datafusion::arrow::datatypes::{DataType, Field, Schema}; |
| 9 | +use datafusion::arrow::util::display::array_value_to_string; |
| 10 | +use datafusion::common::runtime::JoinSet; |
| 11 | +use datafusion::error::DataFusionError; |
| 12 | +use datafusion::execution::context::SessionContext; |
| 13 | +use datafusion::physical_optimizer::PhysicalOptimizerRule; |
| 14 | +use datafusion::physical_plan::ExecutionPlan; |
| 15 | +use datafusion::physical_plan::displayable; |
| 16 | +use datafusion::physical_plan::execution_plan::collect; |
| 17 | +use sqllogictest::{AsyncDB, DBOutput, DefaultColumnType}; |
| 18 | +use std::sync::Arc; |
| 19 | + |
| 20 | +pub struct DatafusionDistributedDB { |
| 21 | + ctx: SessionContext, |
| 22 | + _guard: JoinSet<()>, |
| 23 | +} |
| 24 | + |
| 25 | +impl DatafusionDistributedDB { |
| 26 | + pub async fn new(num_nodes: usize) -> Self { |
| 27 | + let (ctx, _guard) = start_localhost_context(num_nodes, DefaultSessionBuilder).await; |
| 28 | + register_parquet_tables(&ctx).await.unwrap(); |
| 29 | + Self { ctx, _guard } |
| 30 | + } |
| 31 | + |
| 32 | + pub fn optimize_distributed( |
| 33 | + plan: Arc<dyn ExecutionPlan>, |
| 34 | + ) -> Result<Arc<dyn ExecutionPlan>, DataFusionError> { |
| 35 | + DistributedPhysicalOptimizerRule::default() |
| 36 | + .with_network_shuffle_tasks(2) |
| 37 | + .with_network_coalesce_tasks(2) |
| 38 | + .optimize(plan, &Default::default()) |
| 39 | + } |
| 40 | + |
| 41 | + fn convert_batches_to_output( |
| 42 | + &self, |
| 43 | + batches: Vec<RecordBatch>, |
| 44 | + ) -> Result<DBOutput<DefaultColumnType>, datafusion::error::DataFusionError> { |
| 45 | + if batches.is_empty() { |
| 46 | + return Ok(DBOutput::Rows { |
| 47 | + types: vec![], |
| 48 | + rows: vec![], |
| 49 | + }); |
| 50 | + } |
| 51 | + |
| 52 | + let num_columns = batches[0].num_columns(); |
| 53 | + let column_types = vec![DefaultColumnType::Text; num_columns]; // Everything as text |
| 54 | + |
| 55 | + let mut rows = Vec::new(); |
| 56 | + for batch in batches { |
| 57 | + for row_idx in 0..batch.num_rows() { |
| 58 | + let mut row = Vec::new(); |
| 59 | + for col_idx in 0..batch.num_columns() { |
| 60 | + let column = batch.column(col_idx); |
| 61 | + let value = array_value_to_string(column, row_idx) |
| 62 | + .map_err(|e| DataFusionError::ArrowError(Box::new(e), None))?; |
| 63 | + row.push(value); |
| 64 | + } |
| 65 | + rows.push(row); |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + Ok(DBOutput::Rows { |
| 70 | + types: column_types, |
| 71 | + rows, |
| 72 | + }) |
| 73 | + } |
| 74 | + |
| 75 | + async fn handle_explain_analyze( |
| 76 | + &mut self, |
| 77 | + _sql: &str, |
| 78 | + ) -> Result<DBOutput<DefaultColumnType>, datafusion::error::DataFusionError> { |
| 79 | + unimplemented!(); |
| 80 | + } |
| 81 | + |
| 82 | + async fn handle_explain( |
| 83 | + &mut self, |
| 84 | + sql: &str, |
| 85 | + ) -> Result<DBOutput<DefaultColumnType>, datafusion::error::DataFusionError> { |
| 86 | + let query = sql.trim_start_matches("EXPLAIN").trim(); |
| 87 | + let df = self.ctx.sql(query).await?; |
| 88 | + let physical_plan = df.create_physical_plan().await?; |
| 89 | + |
| 90 | + let physical_distributed = Self::optimize_distributed(physical_plan)?; |
| 91 | + |
| 92 | + let physical_distributed_str = displayable(physical_distributed.as_ref()) |
| 93 | + .indent(true) |
| 94 | + .to_string(); |
| 95 | + |
| 96 | + let lines: Vec<String> = physical_distributed_str |
| 97 | + .lines() |
| 98 | + .map(|s| s.to_string()) |
| 99 | + .collect(); |
| 100 | + let schema = Arc::new(Schema::new(vec![Field::new("plan", DataType::Utf8, false)])); |
| 101 | + let batch = |
| 102 | + RecordBatch::try_new(schema, vec![Arc::new(StringArray::from(lines)) as ArrayRef])?; |
| 103 | + |
| 104 | + self.convert_batches_to_output(vec![batch]) |
| 105 | + } |
| 106 | +} |
| 107 | + |
| 108 | +#[async_trait] |
| 109 | +impl AsyncDB for DatafusionDistributedDB { |
| 110 | + type Error = datafusion::error::DataFusionError; |
| 111 | + type ColumnType = DefaultColumnType; |
| 112 | + |
| 113 | + async fn run(&mut self, sql: &str) -> Result<DBOutput<Self::ColumnType>, Self::Error> { |
| 114 | + let sql = sql.trim(); |
| 115 | + |
| 116 | + // Ignore DDL/DML |
| 117 | + if sql.to_uppercase().starts_with("CREATE") |
| 118 | + || sql.to_uppercase().starts_with("INSERT") |
| 119 | + || sql.to_uppercase().starts_with("DROP") |
| 120 | + { |
| 121 | + return Ok(DBOutput::StatementComplete(0)); |
| 122 | + } |
| 123 | + |
| 124 | + if sql.to_uppercase().starts_with("EXPLAIN ANALYZE") { |
| 125 | + return self.handle_explain_analyze(sql).await; |
| 126 | + } |
| 127 | + |
| 128 | + if sql.to_uppercase().starts_with("EXPLAIN") { |
| 129 | + return self.handle_explain(sql).await; |
| 130 | + } |
| 131 | + |
| 132 | + // Default: Execute SELECT statement |
| 133 | + let df = self.ctx.sql(sql).await?; |
| 134 | + let task_ctx = Arc::new(df.task_ctx()); |
| 135 | + let plan = df.create_physical_plan().await?; |
| 136 | + let distributed_plan = Self::optimize_distributed(plan)?; |
| 137 | + let batches = collect(distributed_plan, task_ctx).await?; |
| 138 | + |
| 139 | + self.convert_batches_to_output(batches) |
| 140 | + } |
| 141 | + |
| 142 | + fn engine_name(&self) -> &str { |
| 143 | + "datafusion-distributed" |
| 144 | + } |
| 145 | +} |
0 commit comments