|
| 1 | +// Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +// or more contributor license agreements. See the NOTICE file |
| 3 | +// distributed with this work for additional information |
| 4 | +// regarding copyright ownership. The ASF licenses this file |
| 5 | +// to you under the Apache License, Version 2.0 (the |
| 6 | +// "License"); you may not use this file except in compliance |
| 7 | +// with the License. You may obtain a copy of the License at |
| 8 | +// |
| 9 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +// |
| 11 | +// Unless required by applicable law or agreed to in writing, |
| 12 | +// software distributed under the License is distributed on an |
| 13 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +// KIND, either express or implied. See the License for the |
| 15 | +// specific language governing permissions and limitations |
| 16 | +// under the License. |
| 17 | + |
| 18 | +//! DataFusion `ExecutionPlan` that reads a Delta table natively via delta-kernel-rs. |
| 19 | +
|
| 20 | +use std::any::Any; |
| 21 | +use std::fmt; |
| 22 | +use std::sync::Arc; |
| 23 | + |
| 24 | +use datafusion::arrow::datatypes::SchemaRef; |
| 25 | +use datafusion::common::{DataFusionError, Result as DFResult}; |
| 26 | +use datafusion::execution::{SendableRecordBatchStream, TaskContext}; |
| 27 | +use datafusion::physical_expr::EquivalenceProperties; |
| 28 | +use datafusion::physical_plan::execution_plan::{Boundedness, EmissionType}; |
| 29 | +use datafusion::physical_plan::metrics::{ExecutionPlanMetricsSet, MetricsSet}; |
| 30 | +use datafusion::physical_plan::stream::RecordBatchStreamAdapter; |
| 31 | +use datafusion::physical_plan::{ |
| 32 | + DisplayAs, DisplayFormatType, ExecutionPlan, Partitioning, PlanProperties, |
| 33 | +}; |
| 34 | +use futures::TryStreamExt; |
| 35 | + |
| 36 | +use super::{scan_to_batches, snapshot_arrow_schema}; |
| 37 | + |
| 38 | +/// Leaf operator that reads a whole Delta table through the kernel default engine and emits the |
| 39 | +/// resulting Arrow batches. The kernel applies deletion vectors, column mapping, and partition |
| 40 | +/// values, so the output is Spark-correct. This v1 reads the table as a single partition; per-file |
| 41 | +/// split parallelism is a follow-up. |
| 42 | +#[derive(Debug)] |
| 43 | +pub struct DeltaScanExec { |
| 44 | + table_uri: String, |
| 45 | + output_schema: SchemaRef, |
| 46 | + plan_properties: Arc<PlanProperties>, |
| 47 | + metrics: ExecutionPlanMetricsSet, |
| 48 | +} |
| 49 | + |
| 50 | +impl DeltaScanExec { |
| 51 | + /// Build the operator, reading the table's logical schema from the Delta log. |
| 52 | + pub fn try_new(table_uri: String) -> DFResult<Self> { |
| 53 | + let output_schema = snapshot_arrow_schema(&table_uri).map_err(|e| { |
| 54 | + DataFusionError::Execution(format!("delta: failed to read schema: {e}")) |
| 55 | + })?; |
| 56 | + let plan_properties = Arc::new(PlanProperties::new( |
| 57 | + EquivalenceProperties::new(Arc::clone(&output_schema)), |
| 58 | + Partitioning::UnknownPartitioning(1), |
| 59 | + EmissionType::Incremental, |
| 60 | + Boundedness::Bounded, |
| 61 | + )); |
| 62 | + Ok(Self { |
| 63 | + table_uri, |
| 64 | + output_schema, |
| 65 | + plan_properties, |
| 66 | + metrics: ExecutionPlanMetricsSet::new(), |
| 67 | + }) |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +impl DisplayAs for DeltaScanExec { |
| 72 | + fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result { |
| 73 | + write!(f, "DeltaScanExec: table_uri={}", self.table_uri) |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +impl ExecutionPlan for DeltaScanExec { |
| 78 | + fn name(&self) -> &str { |
| 79 | + "DeltaScanExec" |
| 80 | + } |
| 81 | + |
| 82 | + fn as_any(&self) -> &dyn Any { |
| 83 | + self |
| 84 | + } |
| 85 | + |
| 86 | + fn schema(&self) -> SchemaRef { |
| 87 | + Arc::clone(&self.output_schema) |
| 88 | + } |
| 89 | + |
| 90 | + fn properties(&self) -> &Arc<PlanProperties> { |
| 91 | + &self.plan_properties |
| 92 | + } |
| 93 | + |
| 94 | + fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> { |
| 95 | + vec![] |
| 96 | + } |
| 97 | + |
| 98 | + fn with_new_children( |
| 99 | + self: Arc<Self>, |
| 100 | + _children: Vec<Arc<dyn ExecutionPlan>>, |
| 101 | + ) -> DFResult<Arc<dyn ExecutionPlan>> { |
| 102 | + Ok(self) |
| 103 | + } |
| 104 | + |
| 105 | + fn execute( |
| 106 | + &self, |
| 107 | + _partition: usize, |
| 108 | + _context: Arc<TaskContext>, |
| 109 | + ) -> DFResult<SendableRecordBatchStream> { |
| 110 | + let table_uri = self.table_uri.clone(); |
| 111 | + let schema = Arc::clone(&self.output_schema); |
| 112 | + |
| 113 | + // The kernel read is synchronous and blocking; run it on a blocking worker so it does not |
| 114 | + // stall the tokio reactor, then stream the resulting batches. |
| 115 | + let fut = async move { |
| 116 | + let batches = tokio::task::spawn_blocking(move || scan_to_batches(&table_uri)) |
| 117 | + .await |
| 118 | + .map_err(|e| DataFusionError::Execution(format!("delta: scan task failed: {e}")))? |
| 119 | + .map_err(|e| DataFusionError::Execution(format!("delta: scan failed: {e}")))?; |
| 120 | + Ok::<_, DataFusionError>(futures::stream::iter(batches.into_iter().map(Ok))) |
| 121 | + }; |
| 122 | + let stream = futures::stream::once(fut).try_flatten(); |
| 123 | + Ok(Box::pin(RecordBatchStreamAdapter::new(schema, stream))) |
| 124 | + } |
| 125 | + |
| 126 | + fn metrics(&self) -> Option<MetricsSet> { |
| 127 | + Some(self.metrics.clone_inner()) |
| 128 | + } |
| 129 | +} |
| 130 | + |
| 131 | +#[cfg(test)] |
| 132 | +mod tests { |
| 133 | + use super::*; |
| 134 | + use datafusion::physical_plan::collect; |
| 135 | + use datafusion::prelude::SessionContext; |
| 136 | + use delta_kernel::arrow::array::{Float64Array, Int64Array, RecordBatch}; |
| 137 | + use delta_kernel::arrow::datatypes::Schema as ArrowSchema; |
| 138 | + use delta_kernel::engine::arrow_conversion::TryIntoArrow; |
| 139 | + use delta_kernel::schema::{DataType, SchemaRef as KernelSchemaRef, StructField, StructType}; |
| 140 | + use tempfile::TempDir; |
| 141 | + |
| 142 | + #[test] |
| 143 | + fn delta_scan_exec_reads_table_through_datafusion() { |
| 144 | + let dir = TempDir::new().unwrap(); |
| 145 | + let uri = url::Url::from_directory_path(dir.path()) |
| 146 | + .unwrap() |
| 147 | + .to_string(); |
| 148 | + |
| 149 | + let kschema: KernelSchemaRef = Arc::new( |
| 150 | + StructType::try_new(vec![ |
| 151 | + StructField::nullable("id", DataType::LONG), |
| 152 | + StructField::nullable("score", DataType::DOUBLE), |
| 153 | + ]) |
| 154 | + .unwrap(), |
| 155 | + ); |
| 156 | + super::super::create_table(&uri, Arc::clone(&kschema)).unwrap(); |
| 157 | + |
| 158 | + let arrow_schema: ArrowSchema = kschema.as_ref().try_into_arrow().unwrap(); |
| 159 | + let batch = RecordBatch::try_new( |
| 160 | + Arc::new(arrow_schema), |
| 161 | + vec![ |
| 162 | + Arc::new(Int64Array::from(vec![0i64, 1, 2, 3])), |
| 163 | + Arc::new(Float64Array::from(vec![0.0f64, 1.5, 3.0, 4.5])), |
| 164 | + ], |
| 165 | + ) |
| 166 | + .unwrap(); |
| 167 | + |
| 168 | + let rt = tokio::runtime::Runtime::new().unwrap(); |
| 169 | + rt.block_on(super::super::append(&uri, batch)).unwrap(); |
| 170 | + |
| 171 | + let exec: Arc<dyn ExecutionPlan> = Arc::new(DeltaScanExec::try_new(uri).unwrap()); |
| 172 | + assert_eq!(exec.schema().fields().len(), 2); |
| 173 | + |
| 174 | + let ctx = SessionContext::new(); |
| 175 | + let batches = rt.block_on(collect(exec, ctx.task_ctx())).unwrap(); |
| 176 | + let rows: usize = batches.iter().map(|b| b.num_rows()).sum(); |
| 177 | + assert_eq!(rows, 4); |
| 178 | + } |
| 179 | +} |
0 commit comments