forked from apache/datafusion
-
Notifications
You must be signed in to change notification settings - Fork 0
/
custom_sources.rs
293 lines (256 loc) · 8.81 KB
/
custom_sources.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
use arrow::array::{Int32Array, Int64Array};
use arrow::compute::kernels::aggregate;
use arrow::datatypes::{DataType, Field, Int32Type, Schema, SchemaRef};
use arrow::record_batch::RecordBatch;
use datafusion::execution::context::{SessionContext, SessionState, TaskContext};
use datafusion::from_slice::FromSlice;
use datafusion::logical_expr::{
col, Expr, LogicalPlan, LogicalPlanBuilder, TableScan, UNNAMED_TABLE,
};
use datafusion::physical_plan::empty::EmptyExec;
use datafusion::physical_plan::expressions::PhysicalSortExpr;
use datafusion::physical_plan::{
project_schema, ColumnStatistics, ExecutionPlan, Partitioning, RecordBatchStream,
SendableRecordBatchStream, Statistics,
};
use datafusion::scalar::ScalarValue;
use datafusion::{
datasource::{TableProvider, TableType},
physical_plan::collect,
};
use datafusion::{error::Result, physical_plan::DisplayFormatType};
use datafusion_common::cast::as_primitive_array;
use futures::stream::Stream;
use std::any::Any;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use async_trait::async_trait;
//// Custom source dataframe tests ////
struct CustomTableProvider;
#[derive(Debug, Clone)]
struct CustomExecutionPlan {
projection: Option<Vec<usize>>,
}
struct TestCustomRecordBatchStream {
/// the nb of batches of TEST_CUSTOM_RECORD_BATCH generated
nb_batch: i32,
}
macro_rules! TEST_CUSTOM_SCHEMA_REF {
() => {
Arc::new(Schema::new(vec![
Field::new("c1", DataType::Int32, false),
Field::new("c2", DataType::Int32, false),
]))
};
}
macro_rules! TEST_CUSTOM_RECORD_BATCH {
() => {
RecordBatch::try_new(
TEST_CUSTOM_SCHEMA_REF!(),
vec![
Arc::new(Int32Array::from_slice(&[1, 10, 10, 100])),
Arc::new(Int32Array::from_slice(&[2, 12, 12, 120])),
],
)
};
}
impl RecordBatchStream for TestCustomRecordBatchStream {
fn schema(&self) -> SchemaRef {
TEST_CUSTOM_SCHEMA_REF!()
}
}
impl Stream for TestCustomRecordBatchStream {
type Item = Result<RecordBatch>;
fn poll_next(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
if self.nb_batch > 0 {
self.get_mut().nb_batch -= 1;
Poll::Ready(Some(TEST_CUSTOM_RECORD_BATCH!().map_err(Into::into)))
} else {
Poll::Ready(None)
}
}
}
impl ExecutionPlan for CustomExecutionPlan {
fn as_any(&self) -> &dyn Any {
self
}
fn schema(&self) -> SchemaRef {
let schema = TEST_CUSTOM_SCHEMA_REF!();
project_schema(&schema, self.projection.as_ref()).expect("projected schema")
}
fn output_partitioning(&self) -> Partitioning {
Partitioning::UnknownPartitioning(1)
}
fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {
None
}
fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {
vec![]
}
fn with_new_children(
self: Arc<Self>,
_: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {
Ok(self)
}
fn execute(
&self,
_partition: usize,
_context: Arc<TaskContext>,
) -> Result<SendableRecordBatchStream> {
Ok(Box::pin(TestCustomRecordBatchStream { nb_batch: 1 }))
}
fn fmt_as(
&self,
t: DisplayFormatType,
f: &mut std::fmt::Formatter,
) -> std::fmt::Result {
match t {
DisplayFormatType::Default => {
write!(f, "CustomExecutionPlan: projection={:#?}", self.projection)
}
}
}
fn statistics(&self) -> Statistics {
let batch = TEST_CUSTOM_RECORD_BATCH!().unwrap();
Statistics {
is_exact: true,
num_rows: Some(batch.num_rows()),
total_byte_size: None,
column_statistics: Some(
self.projection
.clone()
.unwrap_or_else(|| (0..batch.columns().len()).collect())
.iter()
.map(|i| ColumnStatistics {
null_count: Some(batch.column(*i).null_count()),
min_value: Some(ScalarValue::Int32(aggregate::min(
as_primitive_array::<Int32Type>(batch.column(*i)).unwrap(),
))),
max_value: Some(ScalarValue::Int32(aggregate::max(
as_primitive_array::<Int32Type>(batch.column(*i)).unwrap(),
))),
..Default::default()
})
.collect(),
),
}
}
}
#[async_trait]
impl TableProvider for CustomTableProvider {
fn as_any(&self) -> &dyn Any {
self
}
fn schema(&self) -> SchemaRef {
TEST_CUSTOM_SCHEMA_REF!()
}
fn table_type(&self) -> TableType {
TableType::Base
}
async fn scan(
&self,
_state: &SessionState,
projection: Option<&Vec<usize>>,
_filters: &[Expr],
_limit: Option<usize>,
) -> Result<Arc<dyn ExecutionPlan>> {
Ok(Arc::new(CustomExecutionPlan {
projection: projection.cloned(),
}))
}
}
#[tokio::test]
async fn custom_source_dataframe() -> Result<()> {
let ctx = SessionContext::new();
let table = ctx.read_table(Arc::new(CustomTableProvider))?;
let (state, plan) = table.into_parts();
let logical_plan = LogicalPlanBuilder::from(plan)
.project(vec![col("c2")])?
.build()?;
let optimized_plan = state.optimize(&logical_plan)?;
match &optimized_plan {
LogicalPlan::TableScan(TableScan {
source,
projected_schema,
..
}) => {
assert_eq!(source.schema().fields().len(), 2);
assert_eq!(projected_schema.fields().len(), 1);
}
_ => panic!("input to projection should be TableScan"),
}
let expected = format!("TableScan: {UNNAMED_TABLE} projection=[c2]");
assert_eq!(format!("{optimized_plan:?}"), expected);
let physical_plan = state.create_physical_plan(&optimized_plan).await?;
assert_eq!(1, physical_plan.schema().fields().len());
assert_eq!("c2", physical_plan.schema().field(0).name().as_str());
let batches = collect(physical_plan, state.task_ctx()).await?;
let origin_rec_batch = TEST_CUSTOM_RECORD_BATCH!()?;
assert_eq!(1, batches.len());
assert_eq!(2, batches[0].num_columns());
assert_eq!(origin_rec_batch.num_rows(), batches[0].num_rows());
Ok(())
}
#[tokio::test]
async fn optimizers_catch_all_statistics() {
let ctx = SessionContext::new();
ctx.register_table("test", Arc::new(CustomTableProvider))
.unwrap();
let df = ctx
.sql("SELECT count(*), min(c1), max(c1) from test")
.await
.unwrap();
let physical_plan = df.create_physical_plan().await.unwrap();
// when the optimization kicks in, the source is replaced by an EmptyExec
assert!(
contains_empty_exec(Arc::clone(&physical_plan)),
"Expected aggregate_statistics optimizations missing: {physical_plan:?}"
);
let expected = RecordBatch::try_new(
Arc::new(Schema::new(vec![
Field::new("COUNT(UInt8(1))", DataType::Int64, false),
Field::new("MIN(test.c1)", DataType::Int32, false),
Field::new("MAX(test.c1)", DataType::Int32, false),
])),
vec![
Arc::new(Int64Array::from_slice([4])),
Arc::new(Int32Array::from_slice([1])),
Arc::new(Int32Array::from_slice([100])),
],
)
.unwrap();
let task_ctx = ctx.task_ctx();
let actual = collect(physical_plan, task_ctx).await.unwrap();
assert_eq!(actual.len(), 1);
assert_eq!(format!("{:?}", actual[0]), format!("{expected:?}"));
}
fn contains_empty_exec(plan: Arc<dyn ExecutionPlan>) -> bool {
if plan.as_any().is::<EmptyExec>() {
true
} else if plan.children().len() != 1 {
false
} else {
contains_empty_exec(Arc::clone(&plan.children()[0]))
}
}