-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathconsumer.rs
3370 lines (3155 loc) · 130 KB
/
consumer.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
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
// 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_buffer::{IntervalDayTime, IntervalMonthDayNano, OffsetBuffer};
use async_recursion::async_recursion;
use datafusion::arrow::array::MapArray;
use datafusion::arrow::datatypes::{
DataType, Field, FieldRef, Fields, IntervalUnit, Schema, TimeUnit,
};
use datafusion::common::{
not_impl_datafusion_err, not_impl_err, plan_datafusion_err, plan_err,
substrait_datafusion_err, substrait_err, DFSchema, DFSchemaRef,
};
use datafusion::datasource::provider_as_source;
use datafusion::logical_expr::expr::{Exists, InSubquery, Sort};
use datafusion::logical_expr::{
Aggregate, BinaryExpr, Case, Cast, EmptyRelation, Expr, ExprSchemable, Extension,
LogicalPlan, Operator, Projection, SortExpr, Subquery, TryCast, Values,
};
use substrait::proto::aggregate_rel::Grouping;
use substrait::proto::expression as substrait_expression;
use substrait::proto::expression::subquery::set_predicate::PredicateOp;
use substrait::proto::expression_reference::ExprType;
use url::Url;
use crate::extensions::Extensions;
use crate::variation_const::{
DATE_32_TYPE_VARIATION_REF, DATE_64_TYPE_VARIATION_REF,
DECIMAL_128_TYPE_VARIATION_REF, DECIMAL_256_TYPE_VARIATION_REF,
DEFAULT_CONTAINER_TYPE_VARIATION_REF, DEFAULT_TYPE_VARIATION_REF,
LARGE_CONTAINER_TYPE_VARIATION_REF, UNSIGNED_INTEGER_TYPE_VARIATION_REF,
VIEW_CONTAINER_TYPE_VARIATION_REF,
};
#[allow(deprecated)]
use crate::variation_const::{
INTERVAL_DAY_TIME_TYPE_REF, INTERVAL_MONTH_DAY_NANO_TYPE_NAME,
INTERVAL_MONTH_DAY_NANO_TYPE_REF, INTERVAL_YEAR_MONTH_TYPE_REF,
TIMESTAMP_MICRO_TYPE_VARIATION_REF, TIMESTAMP_MILLI_TYPE_VARIATION_REF,
TIMESTAMP_NANO_TYPE_VARIATION_REF, TIMESTAMP_SECOND_TYPE_VARIATION_REF,
};
use async_trait::async_trait;
use datafusion::arrow::array::{new_empty_array, AsArray};
use datafusion::arrow::temporal_conversions::NANOSECONDS;
use datafusion::catalog::TableProvider;
use datafusion::common::scalar::ScalarStructBuilder;
use datafusion::execution::{FunctionRegistry, SessionState};
use datafusion::logical_expr::builder::project;
use datafusion::logical_expr::expr::InList;
use datafusion::logical_expr::{
col, expr, GroupingSet, Like, LogicalPlanBuilder, Partitioning, Repartition,
WindowFrameBound, WindowFrameUnits, WindowFunctionDefinition,
};
use datafusion::prelude::{lit, JoinType};
use datafusion::sql::TableReference;
use datafusion::{
error::Result, logical_expr::utils::split_conjunction, prelude::Column,
scalar::ScalarValue,
};
use std::collections::HashSet;
use std::sync::Arc;
use substrait::proto;
use substrait::proto::exchange_rel::ExchangeKind;
use substrait::proto::expression::cast::FailureBehavior::ReturnNull;
use substrait::proto::expression::literal::user_defined::Val;
use substrait::proto::expression::literal::{
interval_day_to_second, IntervalCompound, IntervalDayToSecond, IntervalYearToMonth,
};
use substrait::proto::expression::subquery::SubqueryType;
use substrait::proto::expression::{
Enum, FieldReference, IfThen, Literal, MultiOrList, Nested, ScalarFunction,
SingularOrList, SwitchExpression, WindowFunction,
};
use substrait::proto::read_rel::local_files::file_or_files::PathType::UriFile;
use substrait::proto::rel_common::{Emit, EmitKind};
use substrait::proto::set_rel::SetOp;
use substrait::proto::{
aggregate_function::AggregationInvocation,
expression::{
field_reference::ReferenceType::DirectReference, literal::LiteralType,
reference_segment::ReferenceType::StructField,
window_function::bound as SubstraitBound,
window_function::bound::Kind as BoundKind, window_function::Bound,
window_function::BoundsType, MaskExpression, RexType,
},
fetch_rel,
function_argument::ArgType,
join_rel, plan_rel, r#type,
read_rel::ReadType,
rel::RelType,
rel_common,
sort_field::{SortDirection, SortKind::*},
AggregateFunction, AggregateRel, ConsistentPartitionWindowRel, CrossRel, ExchangeRel,
Expression, ExtendedExpression, ExtensionLeafRel, ExtensionMultiRel,
ExtensionSingleRel, FetchRel, FilterRel, FunctionArgument, JoinRel, NamedStruct,
Plan, ProjectRel, ReadRel, Rel, RelCommon, SetRel, SortField, SortRel, Type,
};
#[async_trait]
/// This trait is used to consume Substrait plans, converting them into DataFusion Logical Plans.
/// It can be implemented by users to allow for custom handling of relations, expressions, etc.
///
/// Combined with the [crate::logical_plan::producer::SubstraitProducer] this allows for fully
/// customizable Substrait serde.
///
/// # Example Usage
///
/// ```
/// # use async_trait::async_trait;
/// # use datafusion::catalog::TableProvider;
/// # use datafusion::common::{not_impl_err, substrait_err, DFSchema, ScalarValue, TableReference};
/// # use datafusion::error::Result;
/// # use datafusion::execution::{FunctionRegistry, SessionState};
/// # use datafusion::logical_expr::{Expr, LogicalPlan, LogicalPlanBuilder};
/// # use std::sync::Arc;
/// # use substrait::proto;
/// # use substrait::proto::{ExtensionLeafRel, FilterRel, ProjectRel};
/// # use datafusion::arrow::datatypes::DataType;
/// # use datafusion::logical_expr::expr::ScalarFunction;
/// # use datafusion_substrait::extensions::Extensions;
/// # use datafusion_substrait::logical_plan::consumer::{
/// # from_project_rel, from_substrait_rel, from_substrait_rex, SubstraitConsumer
/// # };
///
/// struct CustomSubstraitConsumer {
/// extensions: Arc<Extensions>,
/// state: Arc<SessionState>,
/// }
///
/// #[async_trait]
/// impl SubstraitConsumer for CustomSubstraitConsumer {
/// async fn resolve_table_ref(
/// &self,
/// table_ref: &TableReference,
/// ) -> Result<Option<Arc<dyn TableProvider>>> {
/// let table = table_ref.table().to_string();
/// let schema = self.state.schema_for_ref(table_ref.clone())?;
/// let table_provider = schema.table(&table).await?;
/// Ok(table_provider)
/// }
///
/// fn get_extensions(&self) -> &Extensions {
/// self.extensions.as_ref()
/// }
///
/// fn get_function_registry(&self) -> &impl FunctionRegistry {
/// self.state.as_ref()
/// }
///
/// // You can reuse existing consumer code to assist in handling advanced extensions
/// async fn consume_project(&self, rel: &ProjectRel) -> Result<LogicalPlan> {
/// let df_plan = from_project_rel(self, rel).await?;
/// if let Some(advanced_extension) = rel.advanced_extension.as_ref() {
/// not_impl_err!(
/// "decode and handle an advanced extension: {:?}",
/// advanced_extension
/// )
/// } else {
/// Ok(df_plan)
/// }
/// }
///
/// // You can implement a fully custom consumer method if you need special handling
/// async fn consume_filter(&self, rel: &FilterRel) -> Result<LogicalPlan> {
/// let input = self.consume_rel(rel.input.as_ref().unwrap()).await?;
/// let expression =
/// self.consume_expression(rel.condition.as_ref().unwrap(), input.schema())
/// .await?;
/// // though this one is quite boring
/// LogicalPlanBuilder::from(input).filter(expression)?.build()
/// }
///
/// // You can add handlers for extension relations
/// async fn consume_extension_leaf(
/// &self,
/// rel: &ExtensionLeafRel,
/// ) -> Result<LogicalPlan> {
/// not_impl_err!(
/// "handle protobuf Any {} as you need",
/// rel.detail.as_ref().unwrap().type_url
/// )
/// }
///
/// // and handlers for user-define types
/// fn consume_user_defined_type(&self, typ: &proto::r#type::UserDefined) -> Result<DataType> {
/// let type_string = self.extensions.types.get(&typ.type_reference).unwrap();
/// match type_string.as_str() {
/// "u!foo" => not_impl_err!("handle foo conversion"),
/// "u!bar" => not_impl_err!("handle bar conversion"),
/// _ => substrait_err!("unexpected type")
/// }
/// }
///
/// // and user-defined literals
/// fn consume_user_defined_literal(&self, literal: &proto::expression::literal::UserDefined) -> Result<ScalarValue> {
/// let type_string = self.extensions.types.get(&literal.type_reference).unwrap();
/// match type_string.as_str() {
/// "u!foo" => not_impl_err!("handle foo conversion"),
/// "u!bar" => not_impl_err!("handle bar conversion"),
/// _ => substrait_err!("unexpected type")
/// }
/// }
/// }
/// ```
///
pub trait SubstraitConsumer: Send + Sync + Sized {
async fn resolve_table_ref(
&self,
table_ref: &TableReference,
) -> Result<Option<Arc<dyn TableProvider>>>;
// TODO: Remove these two methods
// Ideally, the abstract consumer should not place any constraints on implementations.
// The functionality for which the Extensions and FunctionRegistry is needed should be abstracted
// out into methods on the trait. As an example, resolve_table_reference is such a method.
// See: https://github.com/apache/datafusion/issues/13863
fn get_extensions(&self) -> &Extensions;
fn get_function_registry(&self) -> &impl FunctionRegistry;
// Relation Methods
// There is one method per Substrait relation to allow for easy overriding of consumer behaviour.
// These methods have default implementations calling the common handler code, to allow for users
// to re-use common handling logic.
/// All [Rel]s to be converted pass through this method.
/// You can provide your own implementation if you wish to customize the conversion behaviour.
async fn consume_rel(&self, rel: &Rel) -> Result<LogicalPlan> {
from_substrait_rel(self, rel).await
}
async fn consume_read(&self, rel: &ReadRel) -> Result<LogicalPlan> {
from_read_rel(self, rel).await
}
async fn consume_filter(&self, rel: &FilterRel) -> Result<LogicalPlan> {
from_filter_rel(self, rel).await
}
async fn consume_fetch(&self, rel: &FetchRel) -> Result<LogicalPlan> {
from_fetch_rel(self, rel).await
}
async fn consume_aggregate(&self, rel: &AggregateRel) -> Result<LogicalPlan> {
from_aggregate_rel(self, rel).await
}
async fn consume_sort(&self, rel: &SortRel) -> Result<LogicalPlan> {
from_sort_rel(self, rel).await
}
async fn consume_join(&self, rel: &JoinRel) -> Result<LogicalPlan> {
from_join_rel(self, rel).await
}
async fn consume_project(&self, rel: &ProjectRel) -> Result<LogicalPlan> {
from_project_rel(self, rel).await
}
async fn consume_set(&self, rel: &SetRel) -> Result<LogicalPlan> {
from_set_rel(self, rel).await
}
async fn consume_cross(&self, rel: &CrossRel) -> Result<LogicalPlan> {
from_cross_rel(self, rel).await
}
async fn consume_consistent_partition_window(
&self,
_rel: &ConsistentPartitionWindowRel,
) -> Result<LogicalPlan> {
not_impl_err!("Consistent Partition Window Rel not supported")
}
async fn consume_exchange(&self, rel: &ExchangeRel) -> Result<LogicalPlan> {
from_exchange_rel(self, rel).await
}
// Expression Methods
// There is one method per Substrait expression to allow for easy overriding of consumer behaviour
// These methods have default implementations calling the common handler code, to allow for users
// to re-use common handling logic.
/// All [Expression]s to be converted pass through this method.
/// You can provide your own implementation if you wish to customize the conversion behaviour.
async fn consume_expression(
&self,
expr: &Expression,
input_schema: &DFSchema,
) -> Result<Expr> {
from_substrait_rex(self, expr, input_schema).await
}
async fn consume_literal(&self, expr: &Literal) -> Result<Expr> {
from_literal(self, expr).await
}
async fn consume_field_reference(
&self,
expr: &FieldReference,
input_schema: &DFSchema,
) -> Result<Expr> {
from_field_reference(self, expr, input_schema).await
}
async fn consume_scalar_function(
&self,
expr: &ScalarFunction,
input_schema: &DFSchema,
) -> Result<Expr> {
from_scalar_function(self, expr, input_schema).await
}
async fn consume_window_function(
&self,
expr: &WindowFunction,
input_schema: &DFSchema,
) -> Result<Expr> {
from_window_function(self, expr, input_schema).await
}
async fn consume_if_then(
&self,
expr: &IfThen,
input_schema: &DFSchema,
) -> Result<Expr> {
from_if_then(self, expr, input_schema).await
}
async fn consume_switch(
&self,
_expr: &SwitchExpression,
_input_schema: &DFSchema,
) -> Result<Expr> {
not_impl_err!("Switch expression not supported")
}
async fn consume_singular_or_list(
&self,
expr: &SingularOrList,
input_schema: &DFSchema,
) -> Result<Expr> {
from_singular_or_list(self, expr, input_schema).await
}
async fn consume_multi_or_list(
&self,
_expr: &MultiOrList,
_input_schema: &DFSchema,
) -> Result<Expr> {
not_impl_err!("Multi Or List expression not supported")
}
async fn consume_cast(
&self,
expr: &substrait_expression::Cast,
input_schema: &DFSchema,
) -> Result<Expr> {
from_cast(self, expr, input_schema).await
}
async fn consume_subquery(
&self,
expr: &substrait_expression::Subquery,
input_schema: &DFSchema,
) -> Result<Expr> {
from_subquery(self, expr, input_schema).await
}
async fn consume_nested(
&self,
_expr: &Nested,
_input_schema: &DFSchema,
) -> Result<Expr> {
not_impl_err!("Nested expression not supported")
}
async fn consume_enum(&self, _expr: &Enum, _input_schema: &DFSchema) -> Result<Expr> {
not_impl_err!("Enum expression not supported")
}
// User-Defined Functionality
// The details of extension relations, and how to handle them, are fully up to users to specify.
// The following methods allow users to customize the consumer behaviour
async fn consume_extension_leaf(
&self,
rel: &ExtensionLeafRel,
) -> Result<LogicalPlan> {
if let Some(detail) = rel.detail.as_ref() {
return substrait_err!(
"Missing handler for ExtensionLeafRel: {}",
detail.type_url
);
}
substrait_err!("Missing handler for ExtensionLeafRel")
}
async fn consume_extension_single(
&self,
rel: &ExtensionSingleRel,
) -> Result<LogicalPlan> {
if let Some(detail) = rel.detail.as_ref() {
return substrait_err!(
"Missing handler for ExtensionSingleRel: {}",
detail.type_url
);
}
substrait_err!("Missing handler for ExtensionSingleRel")
}
async fn consume_extension_multi(
&self,
rel: &ExtensionMultiRel,
) -> Result<LogicalPlan> {
if let Some(detail) = rel.detail.as_ref() {
return substrait_err!(
"Missing handler for ExtensionMultiRel: {}",
detail.type_url
);
}
substrait_err!("Missing handler for ExtensionMultiRel")
}
// Users can bring their own types to Substrait which require custom handling
fn consume_user_defined_type(
&self,
user_defined_type: &r#type::UserDefined,
) -> Result<DataType> {
substrait_err!(
"Missing handler for user-defined type: {}",
user_defined_type.type_reference
)
}
fn consume_user_defined_literal(
&self,
user_defined_literal: &proto::expression::literal::UserDefined,
) -> Result<ScalarValue> {
substrait_err!(
"Missing handler for user-defined literals {}",
user_defined_literal.type_reference
)
}
}
/// Convert Substrait Rel to DataFusion DataFrame
#[async_recursion]
pub async fn from_substrait_rel(
consumer: &impl SubstraitConsumer,
relation: &Rel,
) -> Result<LogicalPlan> {
let plan: Result<LogicalPlan> = match &relation.rel_type {
Some(rel_type) => match rel_type {
RelType::Read(rel) => consumer.consume_read(rel).await,
RelType::Filter(rel) => consumer.consume_filter(rel).await,
RelType::Fetch(rel) => consumer.consume_fetch(rel).await,
RelType::Aggregate(rel) => consumer.consume_aggregate(rel).await,
RelType::Sort(rel) => consumer.consume_sort(rel).await,
RelType::Join(rel) => consumer.consume_join(rel).await,
RelType::Project(rel) => consumer.consume_project(rel).await,
RelType::Set(rel) => consumer.consume_set(rel).await,
RelType::ExtensionSingle(rel) => consumer.consume_extension_single(rel).await,
RelType::ExtensionMulti(rel) => consumer.consume_extension_multi(rel).await,
RelType::ExtensionLeaf(rel) => consumer.consume_extension_leaf(rel).await,
RelType::Cross(rel) => consumer.consume_cross(rel).await,
RelType::Window(rel) => {
consumer.consume_consistent_partition_window(rel).await
}
RelType::Exchange(rel) => consumer.consume_exchange(rel).await,
rt => not_impl_err!("{rt:?} rel not supported yet"),
},
None => return substrait_err!("rel must set rel_type"),
};
apply_emit_kind(retrieve_rel_common(relation), plan?)
}
/// Default SubstraitConsumer for converting standard Substrait without user-defined extensions.
///
/// Used as the consumer in [from_substrait_plan]
pub struct DefaultSubstraitConsumer<'a> {
extensions: &'a Extensions,
state: &'a SessionState,
}
impl<'a> DefaultSubstraitConsumer<'a> {
pub fn new(extensions: &'a Extensions, state: &'a SessionState) -> Self {
DefaultSubstraitConsumer { extensions, state }
}
}
#[async_trait]
impl SubstraitConsumer for DefaultSubstraitConsumer<'_> {
async fn resolve_table_ref(
&self,
table_ref: &TableReference,
) -> Result<Option<Arc<dyn TableProvider>>> {
let table = table_ref.table().to_string();
let schema = self.state.schema_for_ref(table_ref.clone())?;
let table_provider = schema.table(&table).await?;
Ok(table_provider)
}
fn get_extensions(&self) -> &Extensions {
self.extensions
}
fn get_function_registry(&self) -> &impl FunctionRegistry {
self.state
}
async fn consume_extension_leaf(
&self,
rel: &ExtensionLeafRel,
) -> Result<LogicalPlan> {
let Some(ext_detail) = &rel.detail else {
return substrait_err!("Unexpected empty detail in ExtensionLeafRel");
};
let plan = self
.state
.serializer_registry()
.deserialize_logical_plan(&ext_detail.type_url, &ext_detail.value)?;
Ok(LogicalPlan::Extension(Extension { node: plan }))
}
async fn consume_extension_single(
&self,
rel: &ExtensionSingleRel,
) -> Result<LogicalPlan> {
let Some(ext_detail) = &rel.detail else {
return substrait_err!("Unexpected empty detail in ExtensionSingleRel");
};
let plan = self
.state
.serializer_registry()
.deserialize_logical_plan(&ext_detail.type_url, &ext_detail.value)?;
let Some(input_rel) = &rel.input else {
return substrait_err!(
"ExtensionSingleRel missing input rel, try using ExtensionLeafRel instead"
);
};
let input_plan = self.consume_rel(input_rel).await?;
let plan = plan.with_exprs_and_inputs(plan.expressions(), vec![input_plan])?;
Ok(LogicalPlan::Extension(Extension { node: plan }))
}
async fn consume_extension_multi(
&self,
rel: &ExtensionMultiRel,
) -> Result<LogicalPlan> {
let Some(ext_detail) = &rel.detail else {
return substrait_err!("Unexpected empty detail in ExtensionMultiRel");
};
let plan = self
.state
.serializer_registry()
.deserialize_logical_plan(&ext_detail.type_url, &ext_detail.value)?;
let mut inputs = Vec::with_capacity(rel.inputs.len());
for input in &rel.inputs {
let input_plan = self.consume_rel(input).await?;
inputs.push(input_plan);
}
let plan = plan.with_exprs_and_inputs(plan.expressions(), inputs)?;
Ok(LogicalPlan::Extension(Extension { node: plan }))
}
}
// Substrait PrecisionTimestampTz indicates that the timestamp is relative to UTC, which
// is the same as the expectation for any non-empty timezone in DF, so any non-empty timezone
// results in correct points on the timeline, and we pick UTC as a reasonable default.
// However, DF uses the timezone also for some arithmetic and display purposes (see e.g.
// https://github.com/apache/arrow-rs/blob/ee5694078c86c8201549654246900a4232d531a9/arrow-cast/src/cast/mod.rs#L1749).
const DEFAULT_TIMEZONE: &str = "UTC";
pub fn name_to_op(name: &str) -> Option<Operator> {
match name {
"equal" => Some(Operator::Eq),
"not_equal" => Some(Operator::NotEq),
"lt" => Some(Operator::Lt),
"lte" => Some(Operator::LtEq),
"gt" => Some(Operator::Gt),
"gte" => Some(Operator::GtEq),
"add" => Some(Operator::Plus),
"subtract" => Some(Operator::Minus),
"multiply" => Some(Operator::Multiply),
"divide" => Some(Operator::Divide),
"mod" => Some(Operator::Modulo),
"modulus" => Some(Operator::Modulo),
"and" => Some(Operator::And),
"or" => Some(Operator::Or),
"is_distinct_from" => Some(Operator::IsDistinctFrom),
"is_not_distinct_from" => Some(Operator::IsNotDistinctFrom),
"regex_match" => Some(Operator::RegexMatch),
"regex_imatch" => Some(Operator::RegexIMatch),
"regex_not_match" => Some(Operator::RegexNotMatch),
"regex_not_imatch" => Some(Operator::RegexNotIMatch),
"bitwise_and" => Some(Operator::BitwiseAnd),
"bitwise_or" => Some(Operator::BitwiseOr),
"str_concat" => Some(Operator::StringConcat),
"at_arrow" => Some(Operator::AtArrow),
"arrow_at" => Some(Operator::ArrowAt),
"bitwise_xor" => Some(Operator::BitwiseXor),
"bitwise_shift_right" => Some(Operator::BitwiseShiftRight),
"bitwise_shift_left" => Some(Operator::BitwiseShiftLeft),
_ => None,
}
}
pub fn substrait_fun_name(name: &str) -> &str {
let name = match name.rsplit_once(':') {
// Since 0.32.0, Substrait requires the function names to be in a compound format
// https://substrait.io/extensions/#function-signature-compound-names
// for example, `add:i8_i8`.
// On the consumer side, we don't really care about the signature though, just the name.
Some((name, _)) => name,
None => name,
};
name
}
fn split_eq_and_noneq_join_predicate_with_nulls_equality(
filter: &Expr,
) -> (Vec<(Column, Column)>, bool, Option<Expr>) {
let exprs = split_conjunction(filter);
let mut accum_join_keys: Vec<(Column, Column)> = vec![];
let mut accum_filters: Vec<Expr> = vec![];
let mut nulls_equal_nulls = false;
for expr in exprs {
#[allow(clippy::collapsible_match)]
match expr {
Expr::BinaryExpr(binary_expr) => match binary_expr {
x @ (BinaryExpr {
left,
op: Operator::Eq,
right,
}
| BinaryExpr {
left,
op: Operator::IsNotDistinctFrom,
right,
}) => {
nulls_equal_nulls = match x.op {
Operator::Eq => false,
Operator::IsNotDistinctFrom => true,
_ => unreachable!(),
};
match (left.as_ref(), right.as_ref()) {
(Expr::Column(l), Expr::Column(r)) => {
accum_join_keys.push((l.clone(), r.clone()));
}
_ => accum_filters.push(expr.clone()),
}
}
_ => accum_filters.push(expr.clone()),
},
_ => accum_filters.push(expr.clone()),
}
}
let join_filter = accum_filters.into_iter().reduce(Expr::and);
(accum_join_keys, nulls_equal_nulls, join_filter)
}
async fn union_rels(
consumer: &impl SubstraitConsumer,
rels: &[Rel],
is_all: bool,
) -> Result<LogicalPlan> {
let mut union_builder = Ok(LogicalPlanBuilder::from(
consumer.consume_rel(&rels[0]).await?,
));
for input in &rels[1..] {
let rel_plan = consumer.consume_rel(input).await?;
union_builder = if is_all {
union_builder?.union(rel_plan)
} else {
union_builder?.union_distinct(rel_plan)
};
}
union_builder?.build()
}
async fn intersect_rels(
consumer: &impl SubstraitConsumer,
rels: &[Rel],
is_all: bool,
) -> Result<LogicalPlan> {
let mut rel = consumer.consume_rel(&rels[0]).await?;
for input in &rels[1..] {
rel = LogicalPlanBuilder::intersect(
rel,
consumer.consume_rel(input).await?,
is_all,
)?
}
Ok(rel)
}
async fn except_rels(
consumer: &impl SubstraitConsumer,
rels: &[Rel],
is_all: bool,
) -> Result<LogicalPlan> {
let mut rel = consumer.consume_rel(&rels[0]).await?;
for input in &rels[1..] {
rel = LogicalPlanBuilder::except(rel, consumer.consume_rel(input).await?, is_all)?
}
Ok(rel)
}
/// Convert Substrait Plan to DataFusion LogicalPlan
pub async fn from_substrait_plan(
state: &SessionState,
plan: &Plan,
) -> Result<LogicalPlan> {
// Register function extension
let extensions = Extensions::try_from(&plan.extensions)?;
if !extensions.type_variations.is_empty() {
return not_impl_err!("Type variation extensions are not supported");
}
let consumer = DefaultSubstraitConsumer {
extensions: &extensions,
state,
};
from_substrait_plan_with_consumer(&consumer, plan).await
}
/// Convert Substrait Plan to DataFusion LogicalPlan using the given consumer
pub async fn from_substrait_plan_with_consumer(
consumer: &impl SubstraitConsumer,
plan: &Plan,
) -> Result<LogicalPlan> {
match plan.relations.len() {
1 => {
match plan.relations[0].rel_type.as_ref() {
Some(rt) => match rt {
plan_rel::RelType::Rel(rel) => Ok(consumer.consume_rel(rel).await?),
plan_rel::RelType::Root(root) => {
let plan = consumer.consume_rel(root.input.as_ref().unwrap()).await?;
if root.names.is_empty() {
// Backwards compatibility for plans missing names
return Ok(plan);
}
let renamed_schema = make_renamed_schema(plan.schema(), &root.names)?;
if renamed_schema.equivalent_names_and_types(plan.schema()) {
// Nothing to do if the schema is already equivalent
return Ok(plan);
}
match plan {
// If the last node of the plan produces expressions, bake the renames into those expressions.
// This isn't necessary for correctness, but helps with roundtrip tests.
LogicalPlan::Projection(p) => Ok(LogicalPlan::Projection(Projection::try_new(rename_expressions(p.expr, p.input.schema(), renamed_schema.fields())?, p.input)?)),
LogicalPlan::Aggregate(a) => {
let (group_fields, expr_fields) = renamed_schema.fields().split_at(a.group_expr.len());
let new_group_exprs = rename_expressions(a.group_expr, a.input.schema(), group_fields)?;
let new_aggr_exprs = rename_expressions(a.aggr_expr, a.input.schema(), expr_fields)?;
Ok(LogicalPlan::Aggregate(Aggregate::try_new(a.input, new_group_exprs, new_aggr_exprs)?))
},
// There are probably more plans where we could bake things in, can add them later as needed.
// Otherwise, add a new Project to handle the renaming.
_ => Ok(LogicalPlan::Projection(Projection::try_new(rename_expressions(plan.schema().columns().iter().map(|c| col(c.to_owned())), plan.schema(), renamed_schema.fields())?, Arc::new(plan))?))
}
}
},
None => plan_err!("Cannot parse plan relation: None")
}
},
_ => not_impl_err!(
"Substrait plan with more than 1 relation trees not supported. Number of relation trees: {:?}",
plan.relations.len()
)
}
}
/// An ExprContainer is a container for a collection of expressions with a common input schema
///
/// In addition, each expression is associated with a field, which defines the
/// expression's output. The data type and nullability of the field are calculated from the
/// expression and the input schema. However the names of the field (and its nested fields) are
/// derived from the Substrait message.
pub struct ExprContainer {
/// The input schema for the expressions
pub input_schema: DFSchemaRef,
/// The expressions
///
/// Each item contains an expression and the field that defines the expected nullability and name of the expr's output
pub exprs: Vec<(Expr, Field)>,
}
/// Convert Substrait ExtendedExpression to ExprContainer
///
/// A Substrait ExtendedExpression message contains one or more expressions,
/// with names for the outputs, and an input schema. These pieces are all included
/// in the ExprContainer.
///
/// This is a top-level message and can be used to send expressions (not plans)
/// between systems. This is often useful for scenarios like pushdown where filter
/// expressions need to be sent to remote systems.
pub async fn from_substrait_extended_expr(
state: &SessionState,
extended_expr: &ExtendedExpression,
) -> Result<ExprContainer> {
// Register function extension
let extensions = Extensions::try_from(&extended_expr.extensions)?;
if !extensions.type_variations.is_empty() {
return not_impl_err!("Type variation extensions are not supported");
}
let consumer = DefaultSubstraitConsumer {
extensions: &extensions,
state,
};
let input_schema = DFSchemaRef::new(match &extended_expr.base_schema {
Some(base_schema) => from_substrait_named_struct(&consumer, base_schema),
None => {
plan_err!("required property `base_schema` missing from Substrait ExtendedExpression message")
}
}?);
// Parse expressions
let mut exprs = Vec::with_capacity(extended_expr.referred_expr.len());
for (expr_idx, substrait_expr) in extended_expr.referred_expr.iter().enumerate() {
let scalar_expr = match &substrait_expr.expr_type {
Some(ExprType::Expression(scalar_expr)) => Ok(scalar_expr),
Some(ExprType::Measure(_)) => {
not_impl_err!("Measure expressions are not yet supported")
}
None => {
plan_err!("required property `expr_type` missing from Substrait ExpressionReference message")
}
}?;
let expr = consumer
.consume_expression(scalar_expr, &input_schema)
.await?;
let (output_type, expected_nullability) =
expr.data_type_and_nullable(&input_schema)?;
let output_field = Field::new("", output_type, expected_nullability);
let mut names_idx = 0;
let output_field = rename_field(
&output_field,
&substrait_expr.output_names,
expr_idx,
&mut names_idx,
/*rename_self=*/ true,
)?;
exprs.push((expr, output_field));
}
Ok(ExprContainer {
input_schema,
exprs,
})
}
pub fn apply_masking(
schema: DFSchema,
mask_expression: &::core::option::Option<MaskExpression>,
) -> Result<DFSchema> {
match mask_expression {
Some(MaskExpression { select, .. }) => match &select.as_ref() {
Some(projection) => {
let column_indices: Vec<usize> = projection
.struct_items
.iter()
.map(|item| item.field as usize)
.collect();
let fields = column_indices
.iter()
.map(|i| schema.qualified_field(*i))
.map(|(qualifier, field)| {
(qualifier.cloned(), Arc::new(field.clone()))
})
.collect();
Ok(DFSchema::new_with_metadata(
fields,
schema.metadata().clone(),
)?)
}
None => Ok(schema),
},
None => Ok(schema),
}
}
/// Ensure the expressions have the right name(s) according to the new schema.
/// This includes the top-level (column) name, which will be renamed through aliasing if needed,
/// as well as nested names (if the expression produces any struct types), which will be renamed
/// through casting if needed.
fn rename_expressions(
exprs: impl IntoIterator<Item = Expr>,
input_schema: &DFSchema,
new_schema_fields: &[Arc<Field>],
) -> Result<Vec<Expr>> {
exprs
.into_iter()
.zip(new_schema_fields)
.map(|(old_expr, new_field)| {
// Check if type (i.e. nested struct field names) match, use Cast to rename if needed
let new_expr = if &old_expr.get_type(input_schema)? != new_field.data_type() {
Expr::Cast(Cast::new(
Box::new(old_expr),
new_field.data_type().to_owned(),
))
} else {
old_expr
};
// Alias column if needed to fix the top-level name
match &new_expr {
// If expr is a column reference, alias_if_changed would cause an aliasing if the old expr has a qualifier
Expr::Column(c) if &c.name == new_field.name() => Ok(new_expr),
_ => new_expr.alias_if_changed(new_field.name().to_owned()),
}
})
.collect()
}
fn rename_field(
field: &Field,
dfs_names: &Vec<String>,
unnamed_field_suffix: usize, // If Substrait doesn't provide a name, we'll use this "c{unnamed_field_suffix}"
name_idx: &mut usize, // Index into dfs_names
rename_self: bool, // Some fields (e.g. list items) don't have names in Substrait and this will be false to keep old name
) -> Result<Field> {
let name = if rename_self {
next_struct_field_name(unnamed_field_suffix, dfs_names, name_idx)?
} else {
field.name().to_string()
};
match field.data_type() {
DataType::Struct(children) => {
let children = children
.iter()
.enumerate()
.map(|(child_idx, f)| {
rename_field(
f.as_ref(),
dfs_names,
child_idx,
name_idx,
/*rename_self=*/ true,
)
})
.collect::<Result<_>>()?;
Ok(field
.to_owned()
.with_name(name)
.with_data_type(DataType::Struct(children)))
}
DataType::List(inner) => {
let renamed_inner = rename_field(
inner.as_ref(),
dfs_names,
0,
name_idx,
/*rename_self=*/ false,
)?;
Ok(field
.to_owned()
.with_data_type(DataType::List(FieldRef::new(renamed_inner)))
.with_name(name))
}
DataType::LargeList(inner) => {
let renamed_inner = rename_field(
inner.as_ref(),
dfs_names,
0,
name_idx,
/*rename_self= */ false,
)?;
Ok(field
.to_owned()
.with_data_type(DataType::LargeList(FieldRef::new(renamed_inner)))
.with_name(name))