forked from apache/datafusion
-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.rs
3796 lines (3707 loc) · 126 KB
/
functions.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.
//! Declaration of built-in (scalar) functions.
//! This module contains built-in functions' enumeration and metadata.
//!
//! Generally, a function has:
//! * a signature
//! * a return type, that is a function of the incoming argument's types
//! * the computation, that must accept each valid signature
//!
//! * Signature: see `Signature`
//! * Return type: a function `(arg_types) -> return_type`. E.g. for sqrt, ([f32]) -> f32, ([f64]) -> f64.
//!
//! This module also has a set of coercion rules to improve user experience: if an argument i32 is passed
//! to a function that supports f64, it is coerced to f64.
use super::{
type_coercion::{coerce, data_types},
ColumnarValue, PhysicalExpr,
};
use crate::execution::context::ExecutionContextState;
use crate::physical_plan::array_expressions;
use crate::physical_plan::datetime_expressions;
use crate::physical_plan::expressions::{
cast_column, nullif_func, DEFAULT_DATAFUSION_CAST_OPTIONS, SUPPORTED_NULLIF_TYPES,
};
use crate::physical_plan::math_expressions;
use crate::physical_plan::string_expressions;
use crate::{
error::{DataFusionError, Result},
scalar::ScalarValue,
};
use arrow::{
array::{ArrayRef, NullArray},
compute::kernels::length::{bit_length, length},
datatypes::TimeUnit,
datatypes::{DataType, Field, Int32Type, Int64Type, Schema},
record_batch::RecordBatch,
};
use fmt::{Debug, Formatter};
use std::convert::From;
use std::{any::Any, fmt, str::FromStr, sync::Arc};
/// A function's signature, which defines the function's supported argument types.
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub enum Signature {
/// arbitrary number of arguments of an common type out of a list of valid types
// A function such as `concat` is `Variadic(vec![DataType::Utf8, DataType::LargeUtf8])`
Variadic(Vec<DataType>),
/// arbitrary number of arguments of an arbitrary but equal type
// A function such as `array` is `VariadicEqual`
// The first argument decides the type used for coercion
VariadicEqual,
/// fixed number of arguments of an arbitrary but equal type out of a list of valid types
// A function of one argument of f64 is `Uniform(1, vec![DataType::Float64])`
// A function of one argument of f64 or f32 is `Uniform(1, vec![DataType::Float32, DataType::Float64])`
Uniform(usize, Vec<DataType>),
/// exact number of arguments of an exact type
Exact(Vec<DataType>),
/// fixed number of arguments of arbitrary types
Any(usize),
/// One of a list of signatures
OneOf(Vec<Signature>),
}
/// Scalar function
///
/// The Fn param is the wrapped function but be aware that the function will
/// be passed with the slice / vec of columnar values (either scalar or array)
/// with the exception of zero param function, where a singular element vec
/// will be passed. In that case the single element is a null array to indicate
/// the batch's row count (so that the generative zero-argument function can know
/// the result array size).
pub type ScalarFunctionImplementation =
Arc<dyn Fn(&[ColumnarValue]) -> Result<ColumnarValue> + Send + Sync>;
/// A function's return type
pub type ReturnTypeFunction =
Arc<dyn Fn(&[DataType]) -> Result<Arc<DataType>> + Send + Sync>;
/// Enum of all built-in scalar functions
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd)]
pub enum BuiltinScalarFunction {
// math functions
/// abs
Abs,
/// acos
Acos,
/// asin
Asin,
/// atan
Atan,
/// ceil
Ceil,
/// cos
Cos,
/// exp
Exp,
/// floor
Floor,
/// ln, Natural logarithm
Ln,
/// log, same as log10
Log,
/// log10
Log10,
/// log2
Log2,
/// round
Round,
/// signum
Signum,
/// sin
Sin,
/// sqrt
Sqrt,
/// tan
Tan,
/// trunc
Trunc,
// string functions
/// construct an array from columns
Array,
/// ascii
Ascii,
/// bit_length
BitLength,
/// btrim
Btrim,
/// character_length
CharacterLength,
/// chr
Chr,
/// concat
Concat,
/// concat_ws
ConcatWithSeparator,
/// date_part
DatePart,
/// date_trunc
DateTrunc,
/// initcap
InitCap,
/// left
Left,
/// lpad
Lpad,
/// lower
Lower,
/// ltrim
Ltrim,
/// md5
MD5,
/// nullif
NullIf,
/// octet_length
OctetLength,
/// random
Random,
/// regexp_replace
RegexpReplace,
/// repeat
Repeat,
/// replace
Replace,
/// reverse
Reverse,
/// right
Right,
/// rpad
Rpad,
/// rtrim
Rtrim,
/// sha224
SHA224,
/// sha256
SHA256,
/// sha384
SHA384,
/// Sha512
SHA512,
/// split_part
SplitPart,
/// starts_with
StartsWith,
/// strpos
Strpos,
/// substr
Substr,
/// to_hex
ToHex,
/// to_timestamp
ToTimestamp,
/// to_timestamp_millis
ToTimestampMillis,
/// to_timestamp_micros
ToTimestampMicros,
/// to_timestamp_seconds
ToTimestampSeconds,
///now
Now,
/// translate
Translate,
/// trim
Trim,
/// upper
Upper,
/// regexp_match
RegexpMatch,
}
impl BuiltinScalarFunction {
/// an allowlist of functions to take zero arguments, so that they will get special treatment
/// while executing.
fn supports_zero_argument(&self) -> bool {
matches!(
self,
BuiltinScalarFunction::Random | BuiltinScalarFunction::Now
)
}
}
impl fmt::Display for BuiltinScalarFunction {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// lowercase of the debug.
write!(f, "{}", format!("{:?}", self).to_lowercase())
}
}
impl FromStr for BuiltinScalarFunction {
type Err = DataFusionError;
fn from_str(name: &str) -> Result<BuiltinScalarFunction> {
Ok(match name {
// math functions
"abs" => BuiltinScalarFunction::Abs,
"acos" => BuiltinScalarFunction::Acos,
"asin" => BuiltinScalarFunction::Asin,
"atan" => BuiltinScalarFunction::Atan,
"ceil" => BuiltinScalarFunction::Ceil,
"cos" => BuiltinScalarFunction::Cos,
"exp" => BuiltinScalarFunction::Exp,
"floor" => BuiltinScalarFunction::Floor,
"ln" => BuiltinScalarFunction::Ln,
"log" => BuiltinScalarFunction::Log,
"log10" => BuiltinScalarFunction::Log10,
"log2" => BuiltinScalarFunction::Log2,
"round" => BuiltinScalarFunction::Round,
"signum" => BuiltinScalarFunction::Signum,
"sin" => BuiltinScalarFunction::Sin,
"sqrt" => BuiltinScalarFunction::Sqrt,
"tan" => BuiltinScalarFunction::Tan,
"trunc" => BuiltinScalarFunction::Trunc,
// string functions
"array" => BuiltinScalarFunction::Array,
"ascii" => BuiltinScalarFunction::Ascii,
"bit_length" => BuiltinScalarFunction::BitLength,
"btrim" => BuiltinScalarFunction::Btrim,
"char_length" => BuiltinScalarFunction::CharacterLength,
"character_length" => BuiltinScalarFunction::CharacterLength,
"concat" => BuiltinScalarFunction::Concat,
"concat_ws" => BuiltinScalarFunction::ConcatWithSeparator,
"chr" => BuiltinScalarFunction::Chr,
"date_part" | "datepart" => BuiltinScalarFunction::DatePart,
"date_trunc" | "datetrunc" => BuiltinScalarFunction::DateTrunc,
"initcap" => BuiltinScalarFunction::InitCap,
"left" => BuiltinScalarFunction::Left,
"length" => BuiltinScalarFunction::CharacterLength,
"lower" => BuiltinScalarFunction::Lower,
"lpad" => BuiltinScalarFunction::Lpad,
"ltrim" => BuiltinScalarFunction::Ltrim,
"md5" => BuiltinScalarFunction::MD5,
"nullif" => BuiltinScalarFunction::NullIf,
"octet_length" => BuiltinScalarFunction::OctetLength,
"random" => BuiltinScalarFunction::Random,
"regexp_replace" => BuiltinScalarFunction::RegexpReplace,
"repeat" => BuiltinScalarFunction::Repeat,
"replace" => BuiltinScalarFunction::Replace,
"reverse" => BuiltinScalarFunction::Reverse,
"right" => BuiltinScalarFunction::Right,
"rpad" => BuiltinScalarFunction::Rpad,
"rtrim" => BuiltinScalarFunction::Rtrim,
"sha224" => BuiltinScalarFunction::SHA224,
"sha256" => BuiltinScalarFunction::SHA256,
"sha384" => BuiltinScalarFunction::SHA384,
"sha512" => BuiltinScalarFunction::SHA512,
"split_part" => BuiltinScalarFunction::SplitPart,
"starts_with" => BuiltinScalarFunction::StartsWith,
"strpos" => BuiltinScalarFunction::Strpos,
"substr" => BuiltinScalarFunction::Substr,
"to_hex" => BuiltinScalarFunction::ToHex,
"to_timestamp" => BuiltinScalarFunction::ToTimestamp,
"to_timestamp_millis" => BuiltinScalarFunction::ToTimestampMillis,
"to_timestamp_micros" => BuiltinScalarFunction::ToTimestampMicros,
"to_timestamp_seconds" => BuiltinScalarFunction::ToTimestampSeconds,
"now" => BuiltinScalarFunction::Now,
"translate" => BuiltinScalarFunction::Translate,
"trim" => BuiltinScalarFunction::Trim,
"upper" => BuiltinScalarFunction::Upper,
"regexp_match" => BuiltinScalarFunction::RegexpMatch,
_ => {
return Err(DataFusionError::Plan(format!(
"There is no built-in function named {}",
name
)))
}
})
}
}
macro_rules! make_utf8_to_return_type {
($FUNC:ident, $largeUtf8Type:expr, $utf8Type:expr) => {
fn $FUNC(arg_type: &DataType, name: &str) -> Result<DataType> {
Ok(match arg_type {
DataType::LargeUtf8 => $largeUtf8Type,
DataType::Utf8 => $utf8Type,
_ => {
// this error is internal as `data_types` should have captured this.
return Err(DataFusionError::Internal(format!(
"The {:?} function can only accept strings.",
name
)));
}
})
}
};
}
make_utf8_to_return_type!(utf8_to_str_type, DataType::LargeUtf8, DataType::Utf8);
make_utf8_to_return_type!(utf8_to_int_type, DataType::Int64, DataType::Int32);
make_utf8_to_return_type!(utf8_to_binary_type, DataType::Binary, DataType::Binary);
/// Returns the datatype of the scalar function
pub fn return_type(
fun: &BuiltinScalarFunction,
arg_types: &[DataType],
) -> Result<DataType> {
// Note that this function *must* return the same type that the respective physical expression returns
// or the execution panics.
// verify that this is a valid set of data types for this function
data_types(arg_types, &signature(fun))?;
// the return type of the built in function.
// Some built-in functions' return type depends on the incoming type.
match fun {
BuiltinScalarFunction::Array => Ok(DataType::FixedSizeList(
Box::new(Field::new("item", arg_types[0].clone(), true)),
arg_types.len() as i32,
)),
BuiltinScalarFunction::Ascii => Ok(DataType::Int32),
BuiltinScalarFunction::BitLength => utf8_to_int_type(&arg_types[0], "bit_length"),
BuiltinScalarFunction::Btrim => utf8_to_str_type(&arg_types[0], "btrim"),
BuiltinScalarFunction::CharacterLength => {
utf8_to_int_type(&arg_types[0], "character_length")
}
BuiltinScalarFunction::Chr => Ok(DataType::Utf8),
BuiltinScalarFunction::Concat => Ok(DataType::Utf8),
BuiltinScalarFunction::ConcatWithSeparator => Ok(DataType::Utf8),
BuiltinScalarFunction::DatePart => Ok(DataType::Int32),
BuiltinScalarFunction::DateTrunc => {
Ok(DataType::Timestamp(TimeUnit::Nanosecond, None))
}
BuiltinScalarFunction::InitCap => utf8_to_str_type(&arg_types[0], "initcap"),
BuiltinScalarFunction::Left => utf8_to_str_type(&arg_types[0], "left"),
BuiltinScalarFunction::Lower => utf8_to_str_type(&arg_types[0], "lower"),
BuiltinScalarFunction::Lpad => utf8_to_str_type(&arg_types[0], "lpad"),
BuiltinScalarFunction::Ltrim => utf8_to_str_type(&arg_types[0], "ltrim"),
BuiltinScalarFunction::MD5 => utf8_to_str_type(&arg_types[0], "md5"),
BuiltinScalarFunction::NullIf => {
// NULLIF has two args and they might get coerced, get a preview of this
let coerced_types = data_types(arg_types, &signature(fun));
coerced_types.map(|typs| typs[0].clone())
}
BuiltinScalarFunction::OctetLength => {
utf8_to_int_type(&arg_types[0], "octet_length")
}
BuiltinScalarFunction::Random => Ok(DataType::Float64),
BuiltinScalarFunction::RegexpReplace => {
utf8_to_str_type(&arg_types[0], "regex_replace")
}
BuiltinScalarFunction::Repeat => utf8_to_str_type(&arg_types[0], "repeat"),
BuiltinScalarFunction::Replace => utf8_to_str_type(&arg_types[0], "replace"),
BuiltinScalarFunction::Reverse => utf8_to_str_type(&arg_types[0], "reverse"),
BuiltinScalarFunction::Right => utf8_to_str_type(&arg_types[0], "right"),
BuiltinScalarFunction::Rpad => utf8_to_str_type(&arg_types[0], "rpad"),
BuiltinScalarFunction::Rtrim => utf8_to_str_type(&arg_types[0], "rtrimp"),
BuiltinScalarFunction::SHA224 => utf8_to_binary_type(&arg_types[0], "sha224"),
BuiltinScalarFunction::SHA256 => utf8_to_binary_type(&arg_types[0], "sha256"),
BuiltinScalarFunction::SHA384 => utf8_to_binary_type(&arg_types[0], "sha384"),
BuiltinScalarFunction::SHA512 => utf8_to_binary_type(&arg_types[0], "sha512"),
BuiltinScalarFunction::SplitPart => utf8_to_str_type(&arg_types[0], "split_part"),
BuiltinScalarFunction::StartsWith => Ok(DataType::Boolean),
BuiltinScalarFunction::Strpos => utf8_to_int_type(&arg_types[0], "strpos"),
BuiltinScalarFunction::Substr => utf8_to_str_type(&arg_types[0], "substr"),
BuiltinScalarFunction::ToHex => Ok(match arg_types[0] {
DataType::Int8 | DataType::Int16 | DataType::Int32 | DataType::Int64 => {
DataType::Utf8
}
_ => {
// this error is internal as `data_types` should have captured this.
return Err(DataFusionError::Internal(
"The to_hex function can only accept integers.".to_string(),
));
}
}),
BuiltinScalarFunction::ToTimestamp => {
Ok(DataType::Timestamp(TimeUnit::Nanosecond, None))
}
BuiltinScalarFunction::ToTimestampMillis => {
Ok(DataType::Timestamp(TimeUnit::Millisecond, None))
}
BuiltinScalarFunction::ToTimestampMicros => {
Ok(DataType::Timestamp(TimeUnit::Microsecond, None))
}
BuiltinScalarFunction::ToTimestampSeconds => {
Ok(DataType::Timestamp(TimeUnit::Second, None))
}
BuiltinScalarFunction::Now => Ok(DataType::Timestamp(TimeUnit::Nanosecond, None)),
BuiltinScalarFunction::Translate => utf8_to_str_type(&arg_types[0], "translate"),
BuiltinScalarFunction::Trim => utf8_to_str_type(&arg_types[0], "trim"),
BuiltinScalarFunction::Upper => utf8_to_str_type(&arg_types[0], "upper"),
BuiltinScalarFunction::RegexpMatch => Ok(match arg_types[0] {
DataType::LargeUtf8 => {
DataType::List(Box::new(Field::new("item", DataType::LargeUtf8, true)))
}
DataType::Utf8 => {
DataType::List(Box::new(Field::new("item", DataType::Utf8, true)))
}
_ => {
// this error is internal as `data_types` should have captured this.
return Err(DataFusionError::Internal(
"The regexp_extract function can only accept strings.".to_string(),
));
}
}),
BuiltinScalarFunction::Abs
| BuiltinScalarFunction::Acos
| BuiltinScalarFunction::Asin
| BuiltinScalarFunction::Atan
| BuiltinScalarFunction::Ceil
| BuiltinScalarFunction::Cos
| BuiltinScalarFunction::Exp
| BuiltinScalarFunction::Floor
| BuiltinScalarFunction::Log
| BuiltinScalarFunction::Ln
| BuiltinScalarFunction::Log10
| BuiltinScalarFunction::Log2
| BuiltinScalarFunction::Round
| BuiltinScalarFunction::Signum
| BuiltinScalarFunction::Sin
| BuiltinScalarFunction::Sqrt
| BuiltinScalarFunction::Tan
| BuiltinScalarFunction::Trunc => {
if arg_types.is_empty() {
return Err(DataFusionError::Internal(format!(
"builtin scalar function {} does not support empty arguments",
fun
)));
}
match arg_types[0] {
DataType::Float32 => Ok(DataType::Float32),
_ => Ok(DataType::Float64),
}
}
}
}
#[cfg(feature = "crypto_expressions")]
macro_rules! invoke_if_crypto_expressions_feature_flag {
($FUNC:ident, $NAME:expr) => {{
use crate::physical_plan::crypto_expressions;
crypto_expressions::$FUNC
}};
}
#[cfg(not(feature = "crypto_expressions"))]
macro_rules! invoke_if_crypto_expressions_feature_flag {
($FUNC:ident, $NAME:expr) => {
|_: &[ColumnarValue]| -> Result<ColumnarValue> {
Err(DataFusionError::Internal(format!(
"function {} requires compilation with feature flag: crypto_expressions.",
$NAME
)))
}
};
}
#[cfg(feature = "regex_expressions")]
macro_rules! invoke_if_regex_expressions_feature_flag {
($FUNC:ident, $T:tt, $NAME:expr) => {{
use crate::physical_plan::regex_expressions;
regex_expressions::$FUNC::<$T>
}};
}
#[cfg(not(feature = "regex_expressions"))]
macro_rules! invoke_if_regex_expressions_feature_flag {
($FUNC:ident, $T:tt, $NAME:expr) => {
|_: &[ArrayRef]| -> Result<ArrayRef> {
Err(DataFusionError::Internal(format!(
"function {} requires compilation with feature flag: regex_expressions.",
$NAME
)))
}
};
}
#[cfg(feature = "unicode_expressions")]
macro_rules! invoke_if_unicode_expressions_feature_flag {
($FUNC:ident, $T:tt, $NAME:expr) => {{
use crate::physical_plan::unicode_expressions;
unicode_expressions::$FUNC::<$T>
}};
}
#[cfg(not(feature = "unicode_expressions"))]
macro_rules! invoke_if_unicode_expressions_feature_flag {
($FUNC:ident, $T:tt, $NAME:expr) => {
|_: &[ArrayRef]| -> Result<ArrayRef> {
Err(DataFusionError::Internal(format!(
"function {} requires compilation with feature flag: unicode_expressions.",
$NAME
)))
}
};
}
/// Create a physical scalar function.
pub fn create_physical_fun(
fun: &BuiltinScalarFunction,
ctx_state: &ExecutionContextState,
) -> Result<ScalarFunctionImplementation> {
Ok(match fun {
// math functions
BuiltinScalarFunction::Abs => Arc::new(math_expressions::abs),
BuiltinScalarFunction::Acos => Arc::new(math_expressions::acos),
BuiltinScalarFunction::Asin => Arc::new(math_expressions::asin),
BuiltinScalarFunction::Atan => Arc::new(math_expressions::atan),
BuiltinScalarFunction::Ceil => Arc::new(math_expressions::ceil),
BuiltinScalarFunction::Cos => Arc::new(math_expressions::cos),
BuiltinScalarFunction::Exp => Arc::new(math_expressions::exp),
BuiltinScalarFunction::Floor => Arc::new(math_expressions::floor),
BuiltinScalarFunction::Log => Arc::new(math_expressions::log10),
BuiltinScalarFunction::Ln => Arc::new(math_expressions::ln),
BuiltinScalarFunction::Log10 => Arc::new(math_expressions::log10),
BuiltinScalarFunction::Log2 => Arc::new(math_expressions::log2),
BuiltinScalarFunction::Random => Arc::new(math_expressions::random),
BuiltinScalarFunction::Round => Arc::new(math_expressions::round),
BuiltinScalarFunction::Signum => Arc::new(math_expressions::signum),
BuiltinScalarFunction::Sin => Arc::new(math_expressions::sin),
BuiltinScalarFunction::Sqrt => Arc::new(math_expressions::sqrt),
BuiltinScalarFunction::Tan => Arc::new(math_expressions::tan),
BuiltinScalarFunction::Trunc => Arc::new(math_expressions::trunc),
// string functions
BuiltinScalarFunction::Array => Arc::new(array_expressions::array),
BuiltinScalarFunction::Ascii => Arc::new(|args| match args[0].data_type() {
DataType::Utf8 => {
make_scalar_function(string_expressions::ascii::<i32>)(args)
}
DataType::LargeUtf8 => {
make_scalar_function(string_expressions::ascii::<i64>)(args)
}
other => Err(DataFusionError::Internal(format!(
"Unsupported data type {:?} for function ascii",
other,
))),
}),
BuiltinScalarFunction::BitLength => Arc::new(|args| match &args[0] {
ColumnarValue::Array(v) => Ok(ColumnarValue::Array(bit_length(v.as_ref())?)),
ColumnarValue::Scalar(v) => match v {
ScalarValue::Utf8(v) => Ok(ColumnarValue::Scalar(ScalarValue::Int32(
v.as_ref().map(|x| (x.len() * 8) as i32),
))),
ScalarValue::LargeUtf8(v) => Ok(ColumnarValue::Scalar(
ScalarValue::Int64(v.as_ref().map(|x| (x.len() * 8) as i64)),
)),
_ => unreachable!(),
},
}),
BuiltinScalarFunction::Btrim => Arc::new(|args| match args[0].data_type() {
DataType::Utf8 => {
make_scalar_function(string_expressions::btrim::<i32>)(args)
}
DataType::LargeUtf8 => {
make_scalar_function(string_expressions::btrim::<i64>)(args)
}
other => Err(DataFusionError::Internal(format!(
"Unsupported data type {:?} for function btrim",
other,
))),
}),
BuiltinScalarFunction::CharacterLength => {
Arc::new(|args| match args[0].data_type() {
DataType::Utf8 => {
let func = invoke_if_unicode_expressions_feature_flag!(
character_length,
Int32Type,
"character_length"
);
make_scalar_function(func)(args)
}
DataType::LargeUtf8 => {
let func = invoke_if_unicode_expressions_feature_flag!(
character_length,
Int64Type,
"character_length"
);
make_scalar_function(func)(args)
}
other => Err(DataFusionError::Internal(format!(
"Unsupported data type {:?} for function character_length",
other,
))),
})
}
BuiltinScalarFunction::Chr => {
Arc::new(|args| make_scalar_function(string_expressions::chr)(args))
}
BuiltinScalarFunction::Concat => Arc::new(string_expressions::concat),
BuiltinScalarFunction::ConcatWithSeparator => {
Arc::new(|args| make_scalar_function(string_expressions::concat_ws)(args))
}
BuiltinScalarFunction::DatePart => Arc::new(datetime_expressions::date_part),
BuiltinScalarFunction::DateTrunc => Arc::new(datetime_expressions::date_trunc),
BuiltinScalarFunction::Now => {
// bind value for now at plan time
Arc::new(datetime_expressions::make_now(
ctx_state.execution_props.query_execution_start_time,
))
}
BuiltinScalarFunction::InitCap => Arc::new(|args| match args[0].data_type() {
DataType::Utf8 => {
make_scalar_function(string_expressions::initcap::<i32>)(args)
}
DataType::LargeUtf8 => {
make_scalar_function(string_expressions::initcap::<i64>)(args)
}
other => Err(DataFusionError::Internal(format!(
"Unsupported data type {:?} for function initcap",
other,
))),
}),
BuiltinScalarFunction::Left => Arc::new(|args| match args[0].data_type() {
DataType::Utf8 => {
let func = invoke_if_unicode_expressions_feature_flag!(left, i32, "left");
make_scalar_function(func)(args)
}
DataType::LargeUtf8 => {
let func = invoke_if_unicode_expressions_feature_flag!(left, i64, "left");
make_scalar_function(func)(args)
}
other => Err(DataFusionError::Internal(format!(
"Unsupported data type {:?} for function left",
other,
))),
}),
BuiltinScalarFunction::Lower => Arc::new(string_expressions::lower),
BuiltinScalarFunction::Lpad => Arc::new(|args| match args[0].data_type() {
DataType::Utf8 => {
let func = invoke_if_unicode_expressions_feature_flag!(lpad, i32, "lpad");
make_scalar_function(func)(args)
}
DataType::LargeUtf8 => {
let func = invoke_if_unicode_expressions_feature_flag!(lpad, i64, "lpad");
make_scalar_function(func)(args)
}
other => Err(DataFusionError::Internal(format!(
"Unsupported data type {:?} for function lpad",
other,
))),
}),
BuiltinScalarFunction::Ltrim => Arc::new(|args| match args[0].data_type() {
DataType::Utf8 => {
make_scalar_function(string_expressions::ltrim::<i32>)(args)
}
DataType::LargeUtf8 => {
make_scalar_function(string_expressions::ltrim::<i64>)(args)
}
other => Err(DataFusionError::Internal(format!(
"Unsupported data type {:?} for function ltrim",
other,
))),
}),
BuiltinScalarFunction::MD5 => {
Arc::new(invoke_if_crypto_expressions_feature_flag!(md5, "md5"))
}
BuiltinScalarFunction::NullIf => Arc::new(nullif_func),
BuiltinScalarFunction::OctetLength => Arc::new(|args| match &args[0] {
ColumnarValue::Array(v) => Ok(ColumnarValue::Array(length(v.as_ref())?)),
ColumnarValue::Scalar(v) => match v {
ScalarValue::Utf8(v) => Ok(ColumnarValue::Scalar(ScalarValue::Int32(
v.as_ref().map(|x| x.len() as i32),
))),
ScalarValue::LargeUtf8(v) => Ok(ColumnarValue::Scalar(
ScalarValue::Int64(v.as_ref().map(|x| x.len() as i64)),
)),
_ => unreachable!(),
},
}),
BuiltinScalarFunction::RegexpMatch => {
Arc::new(|args| match args[0].data_type() {
DataType::Utf8 => {
let func = invoke_if_regex_expressions_feature_flag!(
regexp_match,
i32,
"regexp_match"
);
make_scalar_function(func)(args)
}
DataType::LargeUtf8 => {
let func = invoke_if_regex_expressions_feature_flag!(
regexp_match,
i64,
"regexp_match"
);
make_scalar_function(func)(args)
}
other => Err(DataFusionError::Internal(format!(
"Unsupported data type {:?} for function regexp_match",
other
))),
})
}
BuiltinScalarFunction::RegexpReplace => {
Arc::new(|args| match args[0].data_type() {
DataType::Utf8 => {
let func = invoke_if_regex_expressions_feature_flag!(
regexp_replace,
i32,
"regexp_replace"
);
make_scalar_function(func)(args)
}
DataType::LargeUtf8 => {
let func = invoke_if_regex_expressions_feature_flag!(
regexp_replace,
i64,
"regexp_replace"
);
make_scalar_function(func)(args)
}
other => Err(DataFusionError::Internal(format!(
"Unsupported data type {:?} for function regexp_replace",
other,
))),
})
}
BuiltinScalarFunction::Repeat => Arc::new(|args| match args[0].data_type() {
DataType::Utf8 => {
make_scalar_function(string_expressions::repeat::<i32>)(args)
}
DataType::LargeUtf8 => {
make_scalar_function(string_expressions::repeat::<i64>)(args)
}
other => Err(DataFusionError::Internal(format!(
"Unsupported data type {:?} for function repeat",
other,
))),
}),
BuiltinScalarFunction::Replace => Arc::new(|args| match args[0].data_type() {
DataType::Utf8 => {
make_scalar_function(string_expressions::replace::<i32>)(args)
}
DataType::LargeUtf8 => {
make_scalar_function(string_expressions::replace::<i64>)(args)
}
other => Err(DataFusionError::Internal(format!(
"Unsupported data type {:?} for function replace",
other,
))),
}),
BuiltinScalarFunction::Reverse => Arc::new(|args| match args[0].data_type() {
DataType::Utf8 => {
let func =
invoke_if_unicode_expressions_feature_flag!(reverse, i32, "reverse");
make_scalar_function(func)(args)
}
DataType::LargeUtf8 => {
let func =
invoke_if_unicode_expressions_feature_flag!(reverse, i64, "reverse");
make_scalar_function(func)(args)
}
other => Err(DataFusionError::Internal(format!(
"Unsupported data type {:?} for function reverse",
other,
))),
}),
BuiltinScalarFunction::Right => Arc::new(|args| match args[0].data_type() {
DataType::Utf8 => {
let func =
invoke_if_unicode_expressions_feature_flag!(right, i32, "right");
make_scalar_function(func)(args)
}
DataType::LargeUtf8 => {
let func =
invoke_if_unicode_expressions_feature_flag!(right, i64, "right");
make_scalar_function(func)(args)
}
other => Err(DataFusionError::Internal(format!(
"Unsupported data type {:?} for function right",
other,
))),
}),
BuiltinScalarFunction::Rpad => Arc::new(|args| match args[0].data_type() {
DataType::Utf8 => {
let func = invoke_if_unicode_expressions_feature_flag!(rpad, i32, "rpad");
make_scalar_function(func)(args)
}
DataType::LargeUtf8 => {
let func = invoke_if_unicode_expressions_feature_flag!(rpad, i64, "rpad");
make_scalar_function(func)(args)
}
other => Err(DataFusionError::Internal(format!(
"Unsupported data type {:?} for function rpad",
other,
))),
}),
BuiltinScalarFunction::Rtrim => Arc::new(|args| match args[0].data_type() {
DataType::Utf8 => {
make_scalar_function(string_expressions::rtrim::<i32>)(args)
}
DataType::LargeUtf8 => {
make_scalar_function(string_expressions::rtrim::<i64>)(args)
}
other => Err(DataFusionError::Internal(format!(
"Unsupported data type {:?} for function rtrim",
other,
))),
}),
BuiltinScalarFunction::SHA224 => {
Arc::new(invoke_if_crypto_expressions_feature_flag!(sha224, "sha224"))
}
BuiltinScalarFunction::SHA256 => {
Arc::new(invoke_if_crypto_expressions_feature_flag!(sha256, "sha256"))
}
BuiltinScalarFunction::SHA384 => {
Arc::new(invoke_if_crypto_expressions_feature_flag!(sha384, "sha384"))
}
BuiltinScalarFunction::SHA512 => {
Arc::new(invoke_if_crypto_expressions_feature_flag!(sha512, "sha512"))
}
BuiltinScalarFunction::SplitPart => Arc::new(|args| match args[0].data_type() {
DataType::Utf8 => {
make_scalar_function(string_expressions::split_part::<i32>)(args)
}
DataType::LargeUtf8 => {
make_scalar_function(string_expressions::split_part::<i64>)(args)
}
other => Err(DataFusionError::Internal(format!(
"Unsupported data type {:?} for function split_part",
other,
))),
}),
BuiltinScalarFunction::StartsWith => Arc::new(|args| match args[0].data_type() {
DataType::Utf8 => {
make_scalar_function(string_expressions::starts_with::<i32>)(args)
}
DataType::LargeUtf8 => {
make_scalar_function(string_expressions::starts_with::<i64>)(args)
}
other => Err(DataFusionError::Internal(format!(
"Unsupported data type {:?} for function starts_with",
other,
))),
}),
BuiltinScalarFunction::Strpos => Arc::new(|args| match args[0].data_type() {
DataType::Utf8 => {
let func = invoke_if_unicode_expressions_feature_flag!(
strpos, Int32Type, "strpos"
);
make_scalar_function(func)(args)
}
DataType::LargeUtf8 => {
let func = invoke_if_unicode_expressions_feature_flag!(
strpos, Int64Type, "strpos"
);
make_scalar_function(func)(args)
}
other => Err(DataFusionError::Internal(format!(
"Unsupported data type {:?} for function strpos",
other,
))),
}),
BuiltinScalarFunction::Substr => Arc::new(|args| match args[0].data_type() {
DataType::Utf8 => {
let func =
invoke_if_unicode_expressions_feature_flag!(substr, i32, "substr");
make_scalar_function(func)(args)
}
DataType::LargeUtf8 => {
let func =
invoke_if_unicode_expressions_feature_flag!(substr, i64, "substr");
make_scalar_function(func)(args)
}
other => Err(DataFusionError::Internal(format!(
"Unsupported data type {:?} for function substr",
other,
))),
}),
BuiltinScalarFunction::ToHex => Arc::new(|args| match args[0].data_type() {
DataType::Int32 => {
make_scalar_function(string_expressions::to_hex::<Int32Type>)(args)
}
DataType::Int64 => {
make_scalar_function(string_expressions::to_hex::<Int64Type>)(args)
}
other => Err(DataFusionError::Internal(format!(
"Unsupported data type {:?} for function to_hex",
other,
))),
}),
BuiltinScalarFunction::Translate => Arc::new(|args| match args[0].data_type() {
DataType::Utf8 => {
let func = invoke_if_unicode_expressions_feature_flag!(
translate,
i32,
"translate"
);
make_scalar_function(func)(args)
}
DataType::LargeUtf8 => {
let func = invoke_if_unicode_expressions_feature_flag!(
translate,
i64,
"translate"
);
make_scalar_function(func)(args)
}
other => Err(DataFusionError::Internal(format!(
"Unsupported data type {:?} for function translate",
other,
))),
}),
BuiltinScalarFunction::Trim => Arc::new(|args| match args[0].data_type() {
DataType::Utf8 => {
make_scalar_function(string_expressions::btrim::<i32>)(args)
}
DataType::LargeUtf8 => {
make_scalar_function(string_expressions::btrim::<i64>)(args)
}
other => Err(DataFusionError::Internal(format!(
"Unsupported data type {:?} for function trim",
other,
))),
}),
BuiltinScalarFunction::Upper => Arc::new(string_expressions::upper),
_ => {
return Err(DataFusionError::Internal(format!(
"create_physical_fun: Unsupported scalar function {:?}",
fun
)))
}
})
}
/// Create a physical (function) expression.
/// This function errors when `args`' can't be coerced to a valid argument type of the function.
pub fn create_physical_expr(
fun: &BuiltinScalarFunction,
args: &[Arc<dyn PhysicalExpr>],
input_schema: &Schema,
ctx_state: &ExecutionContextState,
) -> Result<Arc<dyn PhysicalExpr>> {
let fun_expr: ScalarFunctionImplementation = match fun {
// These functions need args and input schema to pick an implementation
// Unlike the string functions, which actually figure out the function to use with each array,
// here we return either a cast fn or string timestamp translation based on the expression data type
// so we don't have to pay a per-array/batch cost.
BuiltinScalarFunction::ToTimestamp => {
Arc::new(match args[0].data_type(input_schema) {
Ok(DataType::Int64) | Ok(DataType::Timestamp(_, None)) => {
|col_values: &[ColumnarValue]| {
cast_column(
&col_values[0],
&DataType::Timestamp(TimeUnit::Nanosecond, None),
&DEFAULT_DATAFUSION_CAST_OPTIONS,
)
}
}
Ok(DataType::Utf8) => datetime_expressions::to_timestamp,
other => {
return Err(DataFusionError::Internal(format!(