forked from uwheel/datafusion-uwheel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
1774 lines (1532 loc) · 61.6 KB
/
lib.rs
File metadata and controls
1774 lines (1532 loc) · 61.6 KB
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! datafusion-uwheel is a DataFusion query optimizer that indexes data using [µWheel](https://github.com/uwheel/uwheel) to accelerate temporal query processing.
//!
//! Learn more about the project [here](https://github.com/uwheel/datafusion-wheel).
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![deny(nonstandard_style, missing_copy_implementations, missing_docs)]
#![forbid(unsafe_code)]
use std::{
collections::HashMap,
fmt::Debug,
sync::{Arc, Mutex},
};
use chrono::{DateTime, NaiveDate, Utc};
use datafusion::error::Result;
use datafusion::prelude::*;
use datafusion::{
arrow::{
array::{
Array, Date32Array, Date64Array, Float64Array, Int64Array, RecordBatch,
TimestampMicrosecondArray, TimestampMillisecondArray, TimestampNanosecondArray,
TimestampSecondArray,
},
datatypes::{DataType, SchemaRef, TimeUnit},
},
common::{tree_node::Transformed, DFSchema, DFSchemaRef},
datasource::{provider_as_source, MemTable, TableProvider},
error::DataFusionError,
logical_expr::{
expr::AggregateFunction, Aggregate, AggregateUDF, Filter, LogicalPlan, LogicalPlanBuilder,
Operator, Projection, TableScan,
},
optimizer::{optimizer::ApplyOrder, OptimizerConfig, OptimizerRule},
scalar::ScalarValue,
sql::TableReference,
};
use expr::{
extract_filter_expr, extract_uwheel_expr, extract_wheel_range, MinMaxFilter, UWheelExpr,
};
use uwheel::{
aggregator::{
all::AllAggregator,
avg::F64AvgAggregator,
max::F64MaxAggregator,
min::F64MinAggregator,
min_max::{F64MinMaxAggregator, MinMaxState},
sum::{F64SumAggregator, U32SumAggregator},
},
wheels::read::ReaderWheel,
Aggregator, Conf, Duration, Entry, HawConf, RwWheel, WheelRange,
};
/// Custom aggregator implementations that are used by this crate.
mod aggregator;
/// Various expressions that the optimizer supports
mod expr;
/// Supported Built-in wheels
mod wheels;
/// Builder for creating a UWheelOptimizer
pub mod builder;
/// Module containing util for creating wheel indices
pub mod index;
pub use index::{IndexBuilder, UWheelAggregate};
use wheels::BuiltInWheels;
const COUNT_STAR_ALIAS: &str = "count(*)";
const STAR_AGGREGATION_ALIAS: &str = "*_AGG";
/// A µWheel optimizer for DataFusion that indexes wheels for time-based analytical queries.
///
/// See [builder::Builder] for how to build an optimizer instance
pub struct UWheelOptimizer {
/// Name of the table
name: String,
/// The column that contains the time
time_column: String,
/// Set of built-in aggregation wheels
wheels: BuiltInWheels,
/// Table provider which UWheelOptimizer builds indexes on top of
provider: Arc<dyn TableProvider>,
/// The minimum timestamp in milliseconds for the underlying data using `time_column`
min_timestamp_ms: u64,
/// The maximum timestamp in milliseconds for the underlying data using `time_column`
max_timestamp_ms: u64,
}
impl UWheelOptimizer {
/// Create a new UWheelOptimizer
async fn try_new(
name: impl Into<String>,
time_column: impl Into<String>,
min_max_columns: Vec<String>,
provider: Arc<dyn TableProvider>,
haw_conf: HawConf,
time_range: Option<(ScalarValue, ScalarValue)>,
) -> Result<Self> {
let time_column = time_column.into();
// Create an initial instance of the UWheelOptimizer
let (min_timestamp_ms, max_timestamp_ms, count, min_max_wheels) = build(
provider.clone(),
&time_column,
min_max_columns,
&haw_conf,
time_range,
)
.await?;
let min_max_wheels = Arc::new(Mutex::new(min_max_wheels));
let wheels = BuiltInWheels::new(count, min_max_wheels);
Ok(Self {
name: name.into(),
time_column,
wheels,
provider,
min_timestamp_ms,
max_timestamp_ms,
})
}
/// Count the number of rows in the given time range
///
/// Returns `None` if the count is not available
#[inline]
pub fn count(&self, range: WheelRange) -> Option<u32> {
self.wheels.count.combine_range_and_lower(range)
}
/// Returns the inner TableProvider
pub fn provider(&self) -> Arc<dyn TableProvider> {
self.provider.clone()
}
/// Returns a reference to the table's COUNT(*) wheel
#[inline]
pub fn count_wheel(&self) -> &ReaderWheel<U32SumAggregator> {
&self.wheels.count
}
/// Returns the total number of bytes used by all wheel indices
pub fn index_usage_bytes(&self) -> usize {
self.wheels.index_usage_bytes()
}
/// Returns a reference to a MIN/MAX wheel for a specified column
pub fn min_max_wheel(&self, column: &str) -> Option<ReaderWheel<F64MinMaxAggregator>> {
self.wheels.min_max.lock().unwrap().get(column).cloned()
}
/// Builds an index using the specified [IndexBuilder]
pub async fn build_index(&self, builder: IndexBuilder) -> Result<()> {
let batches = prep_index_data(
&self.time_column,
self.provider.clone(),
&builder.filter,
&builder.time_range,
)
.await?;
let schema = self.provider.schema();
// Create a key for this wheel index either using the filter expression or a default STAR_AGGREGATION_ALIAS key
let expr_key = builder
.filter
.as_ref()
.map(|f| f.to_string())
.unwrap_or(STAR_AGGREGATION_ALIAS.to_string());
let col = builder.col.to_string();
// Build Key for the wheel (table_name.column_name.expr)
let expr_key = format!("{}.{}.{}", self.name, col, expr_key);
match builder.agg_type {
UWheelAggregate::Sum => {
let wheel = build_uwheel::<F64SumAggregator>(
schema,
&batches,
self.min_timestamp_ms,
self.max_timestamp_ms,
&self.time_column,
&builder,
)
.await?;
self.wheels.sum.lock().unwrap().insert(expr_key, wheel);
}
UWheelAggregate::Avg => {
let wheel = build_uwheel::<F64AvgAggregator>(
schema,
&batches,
self.min_timestamp_ms,
self.max_timestamp_ms,
&self.time_column,
&builder,
)
.await?;
self.wheels.avg.lock().unwrap().insert(expr_key, wheel);
}
UWheelAggregate::Min => {
let wheel = build_uwheel::<F64MinAggregator>(
schema,
&batches,
self.min_timestamp_ms,
self.max_timestamp_ms,
&self.time_column,
&builder,
)
.await?;
self.wheels.min.lock().unwrap().insert(expr_key, wheel);
}
UWheelAggregate::Max => {
let wheel = build_uwheel::<F64MaxAggregator>(
schema,
&batches,
self.min_timestamp_ms,
self.max_timestamp_ms,
&self.time_column,
&builder,
)
.await?;
self.wheels.max.lock().unwrap().insert(expr_key, wheel);
}
UWheelAggregate::All => {
let wheel = build_uwheel::<AllAggregator>(
schema,
&batches,
self.min_timestamp_ms,
self.max_timestamp_ms,
&self.time_column,
&builder,
)
.await?;
self.wheels.all.lock().unwrap().insert(expr_key, wheel);
}
_ => unimplemented!(),
}
Ok(())
}
}
impl UWheelOptimizer {
/// This function takes a logical plan and checks whether it can be rewritten using `uwheel`
///
/// Returns `Some(LogicalPlan)` with the rewritten plan, otherwise None.
pub fn try_rewrite(&self, plan: &LogicalPlan) -> Option<LogicalPlan> {
match plan {
LogicalPlan::Filter(filter) => self.try_rewrite_filter(filter, plan),
LogicalPlan::Projection(projection) => self.try_rewrite_projection(projection, plan),
_ => None, // cannot rewrite
}
}
/// This function is used to determine if the Aggregate has a filter applied to its input.
fn has_filter(agg: &Aggregate) -> bool {
matches!(agg.input.as_ref(), LogicalPlan::Filter(_))
}
// Returns true if the aggregate contains an input Filter and has only one aggr expr
fn single_aggregate_with_filter(agg: &Aggregate) -> bool {
Self::has_filter(agg) && Self::single_agg(agg)
}
/// Checks whether the Aggregate has no group_expr and aggr_expr has a length of 1
fn single_agg(agg: &Aggregate) -> bool {
agg.group_expr.is_empty() && agg.aggr_expr.len() == 1
}
/// checks whether the Aggregate has a single group_by expression
fn single_group_by(agg: &Aggregate) -> bool {
agg.group_expr.len() == 1
}
/// check whether the Aggregate has no group_expr and aggr_expr has a length greater than 1
fn multiple_aggregates(agg: &Aggregate) -> bool {
agg.group_expr.is_empty() && agg.aggr_expr.len() > 1
}
// Attemps to rewrite a top-level Projection plan
fn try_rewrite_projection(
&self,
projection: &Projection,
plan: &LogicalPlan,
) -> Option<LogicalPlan> {
match projection.input.as_ref() {
// SELECT AGG FROM X WHERE TIME >= X AND TIME <= Y
LogicalPlan::Aggregate(agg) if Self::single_aggregate_with_filter(agg) => {
// Only continue if the aggregation has a filter
let LogicalPlan::Filter(filter) = agg.input.as_ref() else {
return None;
};
let agg_expr = agg.aggr_expr.first().unwrap();
match agg_expr {
// COUNT(*)
Expr::Alias(alias) if alias.name == COUNT_STAR_ALIAS => {
self.try_count_rewrite(filter, plan)
}
// Also check
Expr::AggregateFunction(agg) if is_count_star_aggregate(agg) => {
self.try_count_rewrite(filter, plan)
}
// Single Aggregate Function (e.g., SUM(col))
Expr::AggregateFunction(agg) if agg.args.len() == 1 => {
if let Expr::Column(col) = &agg.args[0] {
// Fetch temporal filter range and expr key which is used to identify a wheel
let (range, expr_key) =
match extract_filter_expr(&filter.predicate, &self.time_column)? {
(range, Some(expr)) => {
(range, maybe_replace_table_name(&expr, &self.name))
}
(range, None) => (range, STAR_AGGREGATION_ALIAS.to_string()),
};
// build the key for the wheel
let wheel_key = format!("{}.{}.{}", self.name, col.name, expr_key);
let agg_type = func_def_to_aggregate_type(&agg.func)?;
let schema = Arc::new(plan.schema().clone().as_arrow().clone());
self.create_uwheel_plan(agg_type, &wheel_key, range, schema)
} else {
None
}
}
_ => None,
}
}
LogicalPlan::Aggregate(agg) if Self::single_group_by(agg) => {
let group_expr = agg.group_expr.first()?;
// Only continue if the aggregation has a filter
let LogicalPlan::Filter(filter) = agg.input.as_ref() else {
return None;
};
let (wheel_range, _) = extract_filter_expr(&filter.predicate, &self.time_column)?;
match group_expr {
Expr::ScalarFunction(func) if func.name() == "date_trunc" => {
let interval = func.args.first()?;
if let Expr::Literal(ScalarValue::Utf8(duration)) = interval {
match duration.as_ref()?.as_str() {
"second" => {
unimplemented!("date_trunc('second') group by is not supported")
}
"minute" => {
unimplemented!("date_trunc('minute') group by is not supported")
}
"hour" => {
unimplemented!("date_trunc('hour') group by is not supported")
}
"day" => {
let res = self
.wheels
.count
.group_by(wheel_range, Duration::DAY)
.unwrap_or_default()
.iter()
.map(|(k, v)| ((*k * 1_000) as i64, *v as i64)) // transform milliseconds to microseconds by multiplying by 1_000
.collect();
let schema = Arc::new(plan.schema().clone().as_arrow().clone());
return uwheel_group_by_to_table_scan(res, schema).ok();
}
"week" => {
unimplemented!("date_trunc('week') group by is not supported")
}
"month" => {
unimplemented!("date_trunc('month') group by is not supported")
}
"year" => {
unimplemented!("date_trunc('year') group by is not supported")
}
_ => {}
}
}
}
_ => {
unimplemented!("We only support scalar function date_trunc for group by expression now")
}
}
None
}
LogicalPlan::Aggregate(agg) if Self::multiple_aggregates(agg) => {
// Only continue if the aggregation has a filter
let LogicalPlan::Filter(filter) = agg.input.as_ref() else {
return None;
};
let agg_exprs = &agg.aggr_expr;
let mut agg_results = Vec::new();
for agg_expr in agg_exprs {
match agg_expr {
// Single Aggregate Function (e.g., SUM(col))
Expr::AggregateFunction(agg) if agg.args.len() == 1 => {
if let Expr::Column(col) = &agg.args[0] {
// Fetch temporal filter range and expr key which is used to identify a wheel
let (range, expr_key) = match extract_filter_expr(
&filter.predicate,
&self.time_column,
)? {
(range, Some(expr)) => {
(range, maybe_replace_table_name(&expr, &self.name))
}
(range, None) => (range, STAR_AGGREGATION_ALIAS.to_string()),
};
// build the key for the wheel
let wheel_key = format!("{}.{}.{}", self.name, col.name, expr_key);
let agg_type = func_def_to_aggregate_type(&agg.func)?;
// get aggregation result
let result =
self.get_aggregate_result(agg_type, &wheel_key, range)?;
agg_results.push(result);
} else {
return None;
}
}
_ => {
return None;
}
}
}
let schema = Arc::new(plan.schema().clone().as_arrow().clone());
uwheel_multiple_aggregations_to_table_scan(agg_results, schema).ok()
}
// Check whether it follows the pattern: SELECT * FROM X WHERE TIME >= X AND TIME <= Y
LogicalPlan::Filter(filter) => self.try_rewrite_filter(filter, plan),
_ => None,
}
}
// Attemps to rewrite a top-level Filter plan
fn try_rewrite_filter(&self, filter: &Filter, plan: &LogicalPlan) -> Option<LogicalPlan> {
// The optimizer supports two types of filtering
// 1. count-based using the Count wheel
// 2. min-max filtering using a MinMax wheel
match extract_uwheel_expr(&filter.predicate, &self.time_column) {
// Matches a COUNT(*) filter
Some(UWheelExpr::WheelRange(range)) => self.maybe_count_filter(range, plan),
// Matches a MinMax filter
Some(UWheelExpr::MinMaxFilter(min_max)) => self.maybe_min_max_filter(min_max, plan),
_ => None,
}
}
fn try_count_rewrite(&self, filter: &Filter, plan: &LogicalPlan) -> Option<LogicalPlan> {
let range = extract_wheel_range(&filter.predicate, &self.time_column)?;
let count = self.count(range)?; // early return if range is not queryable
let schema = Arc::new(plan.schema().clone().as_arrow().clone());
count_scan(count, schema).ok()
}
// Queries the range using the count wheel, returning a empty table scan if the count is 0
// avoiding the need to generate a regular execution plan..
fn maybe_count_filter(&self, range: WheelRange, plan: &LogicalPlan) -> Option<LogicalPlan> {
let count = self.count(range)?; // early return if range can't be queried
if count == 0 {
let schema = Arc::new(plan.schema().clone().as_arrow().clone());
let table_ref = extract_table_reference(plan)?;
empty_table_scan(table_ref, schema).ok()
} else {
None
}
}
// Takes a MinMax filter and possibly returns an empty TableScan if the filter indicates that the result is empty
fn maybe_min_max_filter(
&self,
min_max: MinMaxFilter,
plan: &LogicalPlan,
) -> Option<LogicalPlan> {
// First check whether there is a matching min max wheel
let wheel = self.min_max_wheel(min_max.predicate.name.as_ref())?;
// Cast the literal scalar value to f64
let Ok(cast_scalar) = min_max.predicate.scalar.cast_to(&DataType::Float64) else {
return None;
};
// extract the f64 value from the scalar
let ScalarValue::Float64(Some(value)) = cast_scalar else {
return None;
};
// query the MinMax state from our wheel
let min_max_agg = wheel.combine_range_and_lower(min_max.range)?;
// If the value is outside the range of the MinMax state, we can return an empty table scan
if is_empty_range(value, &min_max.predicate.op, min_max_agg) {
let schema = Arc::new(plan.schema().clone().as_arrow().clone());
let table_ref = extract_table_reference(plan)?;
empty_table_scan(table_ref, schema).ok()
} else {
None
}
}
// Takes a wheel range and returns a plan-time aggregate result using a `TableScan(MemTable)`
fn create_uwheel_plan(
&self,
agg_type: UWheelAggregate,
wheel_key: &str,
range: WheelRange,
schema: SchemaRef,
) -> Option<LogicalPlan> {
let result = self.get_aggregate_result(agg_type, wheel_key, range)?;
uwheel_agg_to_table_scan(result, schema).ok()
}
fn get_aggregate_result(
&self,
agg_type: UWheelAggregate,
wheel_key: &str,
range: WheelRange,
) -> Option<f64> {
match agg_type {
UWheelAggregate::Sum => {
let wheel = self.wheels.sum.lock().unwrap().get(wheel_key)?.clone();
wheel.combine_range_and_lower(range)
}
UWheelAggregate::Avg => {
let wheel = self.wheels.avg.lock().unwrap().get(wheel_key)?.clone();
wheel.combine_range_and_lower(range)
}
UWheelAggregate::Min => {
let wheel = self.wheels.min.lock().unwrap().get(wheel_key)?.clone();
wheel.combine_range_and_lower(range)
}
UWheelAggregate::Max => {
let wheel = self.wheels.max.lock().unwrap().get(wheel_key)?.clone();
wheel.combine_range_and_lower(range)
}
_ => unimplemented!(),
}
}
}
fn count_scan(count: u32, schema: SchemaRef) -> Result<LogicalPlan> {
let data = Int64Array::from(vec![count as i64]);
let record_batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(data)])?;
let df_schema = Arc::new(DFSchema::try_from(schema.clone())?);
let mem_table = MemTable::try_new(schema, vec![vec![record_batch]])?;
mem_table_as_table_scan(mem_table, df_schema)
}
// Converts a uwheel aggregate result to a TableScan with a MemTable as source
fn uwheel_agg_to_table_scan(result: f64, schema: SchemaRef) -> Result<LogicalPlan> {
let data = Float64Array::from(vec![result]);
let record_batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(data)])?;
let df_schema = Arc::new(DFSchema::try_from(schema.clone())?);
let mem_table = MemTable::try_new(schema, vec![vec![record_batch]])?;
mem_table_as_table_scan(mem_table, df_schema)
}
// Converts a uwheel group by result to a TableScan with a MemTable as source
// currently only supports timestamp group by
fn uwheel_group_by_to_table_scan(
result: Vec<(i64, i64)>,
schema: SchemaRef,
) -> Result<LogicalPlan> {
let group_by =
TimestampMicrosecondArray::from(result.iter().map(|(k, _)| *k).collect::<Vec<_>>());
let agg = Int64Array::from(result.iter().map(|(_, v)| *v).collect::<Vec<_>>());
let record_batch =
RecordBatch::try_new(schema.clone(), vec![Arc::new(group_by), Arc::new(agg)])?;
let df_schema = Arc::new(DFSchema::try_from(schema.clone())?);
let mem_table = MemTable::try_new(schema, vec![vec![record_batch]])?;
mem_table_as_table_scan(mem_table, df_schema)
}
fn uwheel_multiple_aggregations_to_table_scan(
agg_results: Vec<f64>,
schema: SchemaRef,
) -> Result<LogicalPlan> {
let mut columns = Vec::new();
for result in agg_results {
let data = Float64Array::from(vec![result]);
columns.push(Arc::new(data) as Arc<dyn Array>);
}
let record_batch = RecordBatch::try_new(schema.clone(), columns)?;
let df_schema = Arc::new(DFSchema::try_from(schema.clone())?);
let mem_table = MemTable::try_new(schema, vec![vec![record_batch]])?;
mem_table_as_table_scan(mem_table, df_schema)
}
// helper for possibly removing the table name from the expression key
fn maybe_replace_table_name(expr: &Expr, table_name: &str) -> String {
let expr_str = expr.to_string();
let replace_key = format!("{}.", table_name);
expr_str.replace(&replace_key, "")
}
// helper method to extract a table reference from a logical plan
fn extract_table_reference(filter: &LogicalPlan) -> Option<TableReference> {
match filter {
LogicalPlan::Projection(projection) => extract_table_reference(projection.input.as_ref()),
LogicalPlan::Filter(filter) => {
// Recursively search the input plan
extract_table_reference(&filter.input)
}
LogicalPlan::TableScan(scan) => {
// We've found a table scan, return the table name
Some(scan.table_name.clone())
}
// Add other cases as needed
_ => None,
}
}
// helper function to check whether execution can be skipped based on min/max pruning
fn is_empty_range(value: f64, op: &Operator, min_max_agg: MinMaxState<f64>) -> bool {
let max = min_max_agg.max_value();
let min = min_max_agg.min_value();
op == &Operator::Gt && max < value
|| op == &Operator::GtEq && max <= value
|| op == &Operator::Lt && min > value
|| op == &Operator::LtEq && min >= value
}
// helper fn to create an empty table scan
fn empty_table_scan(
table_ref: impl Into<TableReference>,
schema: SchemaRef,
) -> Result<LogicalPlan> {
let mem_table = MemTable::try_new(schema, vec![])?;
let source = provider_as_source(Arc::new(mem_table));
LogicalPlanBuilder::scan(table_ref.into(), source, None)?.build()
}
fn func_def_to_aggregate_type(func_def: &Arc<AggregateUDF>) -> Option<UWheelAggregate> {
match func_def.name() {
"max" => Some(UWheelAggregate::Max),
"min" => Some(UWheelAggregate::Min),
"avg" => Some(UWheelAggregate::Avg),
"sum" => Some(UWheelAggregate::Sum),
"count" => Some(UWheelAggregate::Count),
_ => None,
}
}
impl Debug for UWheelOptimizer {
fn fmt(&self, _f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Ok(())
}
}
impl OptimizerRule for UWheelOptimizer {
fn name(&self) -> &str {
"uwheel_optimizer_rewriter"
}
fn supports_rewrite(&self) -> bool {
true
}
fn apply_order(&self) -> Option<ApplyOrder> {
None
}
fn rewrite(
&self,
plan: LogicalPlan,
_config: &dyn OptimizerConfig,
) -> Result<Transformed<LogicalPlan>> {
// Attemps to rewrite a logical plan to a uwheel-based plan that either provides
// plan-time aggregates or skips execution based on min/max pruning.
if let Some(rewritten) = self.try_rewrite(&plan) {
Ok(Transformed::yes(rewritten))
} else {
Ok(Transformed::no(plan))
}
}
}
// Turns a MemTable into a TableScan which contains pre-computed uwheel aggregates available at plan time
fn mem_table_as_table_scan(table: MemTable, original_schema: DFSchemaRef) -> Result<LogicalPlan> {
// Convert MemTable to a TableSource
let source = provider_as_source(Arc::new(table));
// Create a TableScan using a dummmy table reference name
let mut table_scan = TableScan::try_new("dummy", source, None, Vec::new(), None)?;
// Replace the schema with the original schema since we are forced to create a table reference
// for the TableScan which may be empty in the original plan.
table_scan.projected_schema = original_schema;
Ok(LogicalPlan::TableScan(table_scan))
}
fn is_wildcard(expr: &Expr) -> bool {
matches!(
expr,
Expr::Wildcard {
qualifier: None,
..
}
)
}
/// Determines if the given aggregate function is a COUNT(*) aggregate.
///
/// An aggregate function is a COUNT(*) aggregate if its function name is "COUNT" and it either has a single argument that is a wildcard (`*`), or it has no arguments.
///
/// # Arguments
///
/// * `aggregate_function` - The aggregate function to check.
///
/// # Returns
///
/// `true` if the aggregate function is a COUNT(*) aggregate, `false` otherwise.
fn is_count_star_aggregate(aggregate_function: &AggregateFunction) -> bool {
matches!(aggregate_function,
AggregateFunction {
func,
args,
..
} if (func.name() == "COUNT" || func.name() == "count") && (args.len() == 1 && is_wildcard(&args[0]) || args.is_empty()))
}
// Helper methods to build the UWheelOptimizer
// Uses the provided TableProvider to build the UWheelOptimizer
async fn build(
provider: Arc<dyn TableProvider>,
time_column: &str,
min_max_columns: Vec<String>,
haw_conf: &HawConf,
time_range: Option<(ScalarValue, ScalarValue)>,
) -> Result<(
u64,
u64,
ReaderWheel<U32SumAggregator>,
HashMap<String, ReaderWheel<F64MinMaxAggregator>>,
)> {
let batches = prep_index_data(time_column, provider.clone(), &None, &time_range).await?;
let mut timestamps = Vec::new();
for batch in batches.iter() {
// Verify the time column exists in the parquet file
let time_column_exists = batch.schema().index_of(time_column).is_ok();
assert!(
time_column_exists,
"Specified Time column does not exist in the provided data"
);
let time_array = batch.column_by_name(time_column).unwrap();
let batch_timestamps = extract_timestamps_from_array(time_array)?;
timestamps.extend_from_slice(&batch_timestamps);
}
// Build a COUNT(*) wheel over the timestamps
let (count_wheel, min_timestamp_ms, max_timestamp_ms) = build_count_wheel(timestamps, haw_conf);
// Build MinMax wheels for specified columns
let mut min_max_map = HashMap::new();
for column in min_max_columns.iter() {
let min_max_wheel = build_min_max_wheel(
provider.schema(),
&batches,
min_timestamp_ms,
max_timestamp_ms,
time_column,
column,
haw_conf,
)
.await?;
min_max_map.insert(column.to_string(), min_max_wheel);
}
Ok((
min_timestamp_ms,
max_timestamp_ms,
count_wheel.read().clone(),
min_max_map,
))
}
async fn build_min_max_wheel(
schema: SchemaRef,
batches: &[RecordBatch],
min_timestamp_ms: u64,
max_timestamp_ms: u64,
time_col: &str,
min_max_col: &str,
haw_conf: &HawConf,
) -> Result<ReaderWheel<F64MinMaxAggregator>> {
let conf = haw_conf.with_watermark(min_timestamp_ms);
let mut wheel: RwWheel<F64MinMaxAggregator> = RwWheel::with_conf(
Conf::default()
.with_haw_conf(conf)
.with_write_ahead(64000usize.next_power_of_two()),
);
let column_index = schema.index_of(min_max_col)?;
let column_field = schema.field(column_index);
if is_numeric_type(column_field.data_type()) {
for batch in batches {
let time_array = batch.column_by_name(time_col).unwrap();
let time_values = extract_timestamps_from_array(time_array)?;
let min_max_column_array = batch
.column_by_name(min_max_col)
.unwrap()
.as_any()
.downcast_ref::<Float64Array>()
.unwrap();
for (timestamp, value) in time_values
.iter()
.copied()
.zip(min_max_column_array.values().iter().copied())
{
let entry = Entry::new(value, timestamp);
wheel.insert(entry);
}
}
// Once all data is inserted, advance the wheel to the max timestamp
wheel.advance_to(max_timestamp_ms);
} else {
// TODO: return Datafusion Error?
panic!("Min/Max column must be a numeric type");
}
Ok(wheel.read().clone())
}
async fn build_uwheel<A>(
schema: SchemaRef,
batches: &[RecordBatch],
min_timestamp_ms: u64,
max_timestamp_ms: u64,
time_col: &str,
builder: &IndexBuilder,
) -> Result<ReaderWheel<A>>
where
A: Aggregator<Input = f64>,
{
let target_col = builder.col.to_string();
let haw_conf = builder.conf;
// Define the start time for the wheel index
let (start_ms, end_ms) = builder
.time_range
.as_ref()
.map(|(start, end)| {
(
scalar_to_timestamp(start).unwrap() as u64,
scalar_to_timestamp(end).unwrap() as u64,
)
})
.unwrap_or((min_timestamp_ms, max_timestamp_ms));
let conf = haw_conf.with_watermark(start_ms);
let mut wheel: RwWheel<A> = RwWheel::with_conf(
Conf::default()
.with_haw_conf(conf)
.with_write_ahead(64000usize.next_power_of_two()),
);
let column_index = schema.index_of(&target_col)?;
let column_field = schema.field(column_index);
if is_numeric_type(column_field.data_type()) {
for batch in batches {
let time_array = batch.column_by_name(time_col).unwrap();
let time_values = extract_timestamps_from_array(time_array)?;
let column_array = batch
.column_by_name(&target_col)
.unwrap()
.as_any()
.downcast_ref::<Float64Array>()
.unwrap();
for (timestamp, value) in time_values
.iter()
.copied()
.zip(column_array.values().iter().copied())
{
let entry = Entry::new(value, timestamp);
wheel.insert(entry);
}
}
// Once all data is inserted, advance the wheel to the max timestamp + 1 second
wheel.advance_to(end_ms + 1000);
// convert wheel to index
wheel.read().to_simd_wheels();
// TODO: make this configurable
if A::invertible() {
wheel.read().to_prefix_wheels();
}
} else {
// TODO: return Datafusion Error?
panic!("Min/Max column must be a numeric type");
}
Ok(wheel.read().clone())
}
/// Builds a COUNT(*) wheel over the given timestamps
///
/// Uses a U32SumAggregator internally with prefix-sum optimization
fn build_count_wheel(
timestamps: Vec<u64>,
haw_conf: &HawConf,
) -> (RwWheel<U32SumAggregator>, u64, u64) {
let min_ms = timestamps.iter().min().copied().unwrap();
let max_ms = timestamps.iter().max().copied().unwrap();
let conf = haw_conf.with_watermark(min_ms);
let mut count_wheel: RwWheel<U32SumAggregator> = RwWheel::with_conf(
Conf::default()
.with_haw_conf(conf)
.with_write_ahead(64000usize.next_power_of_two()),
);
for timestamp in timestamps {
// Record a count
let entry = Entry::new(1, timestamp);
count_wheel.insert(entry);
}
count_wheel.advance_to(max_ms + 1000); // + 1 second
// convert wheel to index
count_wheel.read().to_simd_wheels();
count_wheel.read().to_prefix_wheels();
(count_wheel, min_ms, max_ms)
}
// internal helper that fetches the record batches
async fn prep_index_data(
time_column: &str,
provider: Arc<dyn TableProvider>,
filter: &Option<Expr>,
time_range: &Option<(ScalarValue, ScalarValue)>,
) -> Result<Vec<RecordBatch>> {
let ctx = SessionContext::new();
let df = ctx.read_table(provider)?;
// Apply filter if it exists
let df = if let Some(filter) = filter {
df.filter(filter.clone())?
} else {
df
};
// Apply time-range filter if specified
let df = if let Some((start_range, end_range)) = time_range {
// WHERE "time_column" >= start_range AND "time_column" < end_range
let time_filter = col(time_column)
.gt_eq(lit(start_range.clone()))
.and(col(time_column).lt(lit(end_range.clone())));
df.filter(time_filter)?
} else {
df
};
df.collect().await
}
// checks whether the given data type is a numeric type
fn is_numeric_type(data_type: &DataType) -> bool {
matches!(
data_type,
DataType::Int8
| DataType::Int16
| DataType::Int32
| DataType::Int64
| DataType::UInt8
| DataType::UInt16
| DataType::UInt32
| DataType::UInt64
| DataType::Float16
| DataType::Float32
| DataType::Float64