forked from apache/datafusion
-
Notifications
You must be signed in to change notification settings - Fork 0
/
statistics.rs
291 lines (248 loc) · 8.54 KB
/
statistics.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
// 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.
//! This module contains end to end tests of statistics propagation
use std::{any::Any, sync::Arc};
use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
use datafusion::{
datasource::{TableProvider, TableType},
error::Result,
logical_expr::Expr,
physical_plan::{
expressions::PhysicalSortExpr, project_schema, ColumnStatistics,
DisplayFormatType, ExecutionPlan, Partitioning, SendableRecordBatchStream,
Statistics,
},
prelude::SessionContext,
scalar::ScalarValue,
};
use async_trait::async_trait;
use datafusion::execution::context::{SessionState, TaskContext};
/// This is a testing structure for statistics
/// It will act both as a table provider and execution plan
#[derive(Debug, Clone)]
struct StatisticsValidation {
stats: Statistics,
schema: Arc<Schema>,
}
impl StatisticsValidation {
fn new(stats: Statistics, schema: SchemaRef) -> Self {
assert!(
stats
.column_statistics
.as_ref()
.map(|cols| cols.len() == schema.fields().len())
.unwrap_or(true),
"if defined, the column statistics vector length should be the number of fields"
);
Self { stats, schema }
}
}
#[async_trait]
impl TableProvider for StatisticsValidation {
fn as_any(&self) -> &dyn Any {
self
}
fn schema(&self) -> SchemaRef {
Arc::clone(&self.schema)
}
fn table_type(&self) -> TableType {
TableType::Base
}
async fn scan(
&self,
_state: &SessionState,
projection: Option<&Vec<usize>>,
filters: &[Expr],
// limit is ignored because it is not mandatory for a `TableProvider` to honor it
_limit: Option<usize>,
) -> Result<Arc<dyn ExecutionPlan>> {
// Filters should not be pushed down as they are marked as unsupported by default.
assert_eq!(
0,
filters.len(),
"Unsupported expressions should not be pushed down"
);
let projection = match projection.cloned() {
Some(p) => p,
None => (0..self.schema.fields().len()).collect(),
};
let projected_schema = project_schema(&self.schema, Some(&projection))?;
let current_stat = self.stats.clone();
let proj_col_stats = current_stat
.column_statistics
.map(|col_stat| projection.iter().map(|i| col_stat[*i].clone()).collect());
Ok(Arc::new(Self::new(
Statistics {
is_exact: current_stat.is_exact,
num_rows: current_stat.num_rows,
column_statistics: proj_col_stats,
// TODO stats: knowing the type of the new columns we can guess the output size
total_byte_size: None,
},
projected_schema,
)))
}
}
impl ExecutionPlan for StatisticsValidation {
fn as_any(&self) -> &dyn Any {
self
}
fn schema(&self) -> SchemaRef {
Arc::clone(&self.schema)
}
fn output_partitioning(&self) -> Partitioning {
Partitioning::UnknownPartitioning(2)
}
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> {
unimplemented!("This plan only serves for testing statistics")
}
fn statistics(&self) -> Statistics {
self.stats.clone()
}
fn fmt_as(
&self,
t: DisplayFormatType,
f: &mut std::fmt::Formatter,
) -> std::fmt::Result {
match t {
DisplayFormatType::Default => {
write!(
f,
"StatisticsValidation: col_count={}, row_count={:?}",
self.schema.fields().len(),
self.stats.num_rows,
)
}
}
}
}
fn init_ctx(stats: Statistics, schema: Schema) -> Result<SessionContext> {
let ctx = SessionContext::new();
let provider: Arc<dyn TableProvider> =
Arc::new(StatisticsValidation::new(stats, Arc::new(schema)));
ctx.register_table("stats_table", provider)?;
Ok(ctx)
}
fn fully_defined() -> (Statistics, Schema) {
(
Statistics {
num_rows: Some(13),
is_exact: true,
total_byte_size: None, // ignore byte size for now
column_statistics: Some(vec![
ColumnStatistics {
distinct_count: Some(2),
max_value: Some(ScalarValue::Int32(Some(1023))),
min_value: Some(ScalarValue::Int32(Some(-24))),
null_count: Some(0),
},
ColumnStatistics {
distinct_count: Some(13),
max_value: Some(ScalarValue::Int64(Some(5486))),
min_value: Some(ScalarValue::Int64(Some(-6783))),
null_count: Some(5),
},
]),
},
Schema::new(vec![
Field::new("c1", DataType::Int32, false),
Field::new("c2", DataType::Int64, false),
]),
)
}
#[tokio::test]
async fn sql_basic() -> Result<()> {
let (stats, schema) = fully_defined();
let ctx = init_ctx(stats.clone(), schema)?;
let df = ctx.sql("SELECT * from stats_table").await.unwrap();
let physical_plan = df.create_physical_plan().await.unwrap();
// the statistics should be those of the source
assert_eq!(stats, physical_plan.statistics());
Ok(())
}
#[tokio::test]
async fn sql_filter() -> Result<()> {
let (stats, schema) = fully_defined();
let ctx = init_ctx(stats, schema)?;
let df = ctx
.sql("SELECT * FROM stats_table WHERE c1 = 5")
.await
.unwrap();
let physical_plan = df.create_physical_plan().await.unwrap();
let stats = physical_plan.statistics();
assert!(!stats.is_exact);
assert_eq!(stats.num_rows, Some(1));
Ok(())
}
#[tokio::test]
async fn sql_limit() -> Result<()> {
let (stats, schema) = fully_defined();
let ctx = init_ctx(stats.clone(), schema)?;
let df = ctx.sql("SELECT * FROM stats_table LIMIT 5").await.unwrap();
let physical_plan = df.create_physical_plan().await.unwrap();
// when the limit is smaller than the original number of lines
// we loose all statistics except the for number of rows which becomes the limit
assert_eq!(
Statistics {
num_rows: Some(5),
is_exact: true,
..Default::default()
},
physical_plan.statistics()
);
let df = ctx
.sql("SELECT * FROM stats_table LIMIT 100")
.await
.unwrap();
let physical_plan = df.create_physical_plan().await.unwrap();
// when the limit is larger than the original number of lines, statistics remain unchanged
assert_eq!(stats, physical_plan.statistics());
Ok(())
}
#[tokio::test]
async fn sql_window() -> Result<()> {
let (stats, schema) = fully_defined();
let ctx = init_ctx(stats.clone(), schema)?;
let df = ctx
.sql("SELECT c2, sum(c1) over (partition by c2) FROM stats_table")
.await
.unwrap();
let physical_plan = df.create_physical_plan().await.unwrap();
let result = physical_plan.statistics();
assert_eq!(stats.num_rows, result.num_rows);
assert!(result.column_statistics.is_some());
let col_stats = result.column_statistics.unwrap();
assert_eq!(2, col_stats.len());
assert_eq!(stats.column_statistics.unwrap()[1], col_stats[0]);
Ok(())
}