Repository navigation
Expand file tree
/
Copy pathcast.rs
More file actions
2997 lines (2754 loc) · 109 KB
/
Copy pathcast.rs
File metadata and controls
2997 lines (2754 loc) · 109 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
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
use std::fmt;
use std::hash::Hash;
use std::sync::Arc;
use crate::physical_expr::PhysicalExpr;
use arrow::compute::{CastOptions, can_cast_types};
use arrow::datatypes::{DataType, DataType::*, Field, FieldRef, Metadata, Schema};
use arrow::record_batch::RecordBatch;
use arrow::util::display::{ArrayFormatterFactory, DurationFormat, FormatOptions};
use arrow_schema::extension::{EXTENSION_TYPE_METADATA_KEY, EXTENSION_TYPE_NAME_KEY};
use datafusion_common::datatype::DataTypeExt;
use datafusion_common::format::DEFAULT_FORMAT_OPTIONS;
use datafusion_common::nested_struct::{
requires_nested_struct_cast, validate_data_type_compatibility,
};
use datafusion_common::{Result, not_impl_err};
use datafusion_expr_common::columnar_value::ColumnarValue;
use datafusion_expr_common::interval_arithmetic::Interval;
use datafusion_expr_common::sort_properties::ExprProperties;
const DEFAULT_CAST_OPTIONS: CastOptions<'static> = CastOptions {
safe: false,
format_options: DEFAULT_FORMAT_OPTIONS,
};
const DEFAULT_SAFE_CAST_OPTIONS: CastOptions<'static> = CastOptions {
safe: true,
format_options: DEFAULT_FORMAT_OPTIONS,
};
/// Owns Arrow's borrowed format strings so protobuf decoding does not leak them.
#[derive(Debug, Clone)]
struct OwnedCastOptions {
safe: bool,
format_safe: bool,
null: String,
date_format: Option<String>,
datetime_format: Option<String>,
timestamp_format: Option<String>,
timestamp_tz_format: Option<String>,
time_format: Option<String>,
duration_format: DurationFormat,
types_info: bool,
quoted_strings: bool,
formatter_factory: Option<&'static dyn ArrayFormatterFactory>,
}
impl From<CastOptions<'static>> for OwnedCastOptions {
fn from(options: CastOptions<'static>) -> Self {
let CastOptions {
safe,
format_options,
} = options;
Self {
safe,
format_safe: format_options.safe(),
null: format_options.null().to_owned(),
date_format: format_options.date_format().map(str::to_owned),
datetime_format: format_options.datetime_format().map(str::to_owned),
timestamp_format: format_options.timestamp_format().map(str::to_owned),
timestamp_tz_format: format_options.timestamp_tz_format().map(str::to_owned),
time_format: format_options.time_format().map(str::to_owned),
duration_format: format_options.duration_format(),
types_info: format_options.types_info(),
quoted_strings: format_options.quoted_strings(),
formatter_factory: format_options.formatter_factory(),
}
}
}
impl OwnedCastOptions {
fn as_arrow(&self) -> CastOptions<'_> {
let Self {
safe,
format_safe,
null,
date_format,
datetime_format,
timestamp_format,
timestamp_tz_format,
time_format,
duration_format,
types_info,
quoted_strings,
formatter_factory,
} = self;
CastOptions {
safe: *safe,
format_options: FormatOptions::new()
.with_display_error(*format_safe)
.with_null(null)
.with_date_format(date_format.as_deref())
.with_datetime_format(datetime_format.as_deref())
.with_timestamp_format(timestamp_format.as_deref())
.with_timestamp_tz_format(timestamp_tz_format.as_deref())
.with_time_format(time_format.as_deref())
.with_duration_format(*duration_format)
.with_types_info(*types_info)
.with_quoted_strings(*quoted_strings)
.with_formatter_factory(*formatter_factory),
}
}
}
impl PartialEq for OwnedCastOptions {
fn eq(&self, other: &Self) -> bool {
self.as_arrow() == other.as_arrow()
}
}
impl Eq for OwnedCastOptions {}
impl Hash for OwnedCastOptions {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.as_arrow().hash(state);
}
}
/// Check if name-based struct casting is allowed by validating field compatibility.
///
/// This function applies the same validation rules as execution time to ensure
/// planning-time validation matches runtime validation, enabling fail-fast behavior
/// instead of deferring errors to execution. Handles structs at any nesting level
/// (e.g., `List<Struct>`, `Dictionary<_, Struct>`).
fn can_cast_named_struct_types(source: &DataType, target: &DataType) -> bool {
validate_data_type_compatibility("", source, target).is_ok()
}
/// CAST expression casts an expression to a specific data type and returns a runtime error on invalid cast
#[derive(Debug, Clone, Eq)]
pub struct CastExpr {
/// The expression to cast
pub expr: Arc<dyn PhysicalExpr>,
/// The target field.
///
/// For a type-only cast (see [`CastExpr::new`]) this is a field synthesized
/// from the target data type alone and only its data type is meaningful.
/// For a cast built from an explicit field (see
/// [`CastExpr::new_with_target_field`]) its metadata and nullability are
/// applied to the output field as-is.
target_field: FieldRef,
/// Whether `target_field` was supplied by the caller (as opposed to being
/// synthesized from a `DataType`), and therefore whether its metadata and
/// nullability describe the output field exactly.
explicit_target: bool,
/// Cast options
cast_options: OwnedCastOptions,
}
// Manually derive PartialEq and Hash to work around https://github.com/rust-lang/rust/issues/78808
impl PartialEq for CastExpr {
fn eq(&self, other: &Self) -> bool {
// Compare the semantically meaningful parts of the target field only:
// the field name never affects the output of this expression.
self.expr.eq(&other.expr)
&& self.cast_type().eq(other.cast_type())
&& self.target_metadata().eq(&other.target_metadata())
&& self.target_nullable().eq(&other.target_nullable())
&& self.cast_options.eq(&other.cast_options)
}
}
impl Hash for CastExpr {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.expr.hash(state);
self.cast_type().hash(state);
// Hash the metadata by iterating over sorted keys for deterministic ordering
if let Some(metadata) = self.target_metadata() {
let mut entries: Vec<_> = metadata.iter().collect();
entries.sort_by_key(|(k, _)| *k);
for (k, v) in entries {
k.hash(state);
v.hash(state);
}
}
self.target_nullable().hash(state);
self.cast_options.hash(state);
}
}
impl CastExpr {
/// Create a new `CastExpr` using only a `DataType`.
///
/// This constructor creates a type-only cast where metadata and nullability
/// are passed through from the source expression (with extension type keys
/// stripped from metadata). This is the most common use case when you only
/// need to change the data type.
///
/// For explicit control over the output field's metadata and nullability,
/// use [`CastExpr::new_with_target_field`] or the individual builder methods.
pub fn new(
expr: Arc<dyn PhysicalExpr>,
cast_type: DataType,
cast_options: Option<CastOptions<'static>>,
) -> Self {
Self {
expr,
target_field: cast_type.into_nullable_field_ref(),
explicit_target: false,
cast_options: cast_options.unwrap_or(DEFAULT_CAST_OPTIONS).into(),
}
}
/// Create a new `CastExpr` with an explicit target `FieldRef`.
///
/// The provided `target_field` determines the output characteristics:
/// - The field's data type becomes the cast target type
/// - The field's metadata is used exactly as provided
/// - The field's nullability is preserved
///
/// This is the preferred constructor when the caller has explicit field
/// information that should be used exactly (for example, during schema
/// enforcement or adapter layers).
///
/// See [`CastExpr::new`] for type-only casts where source metadata should
/// pass through.
pub fn new_with_target_field(
expr: Arc<dyn PhysicalExpr>,
target_field: FieldRef,
cast_options: Option<CastOptions<'static>>,
) -> Self {
Self {
expr,
target_field,
explicit_target: true,
cast_options: cast_options.unwrap_or(DEFAULT_CAST_OPTIONS).into(),
}
}
/// The expression to cast
pub fn expr(&self) -> &Arc<dyn PhysicalExpr> {
&self.expr
}
/// The data type to cast to
pub fn cast_type(&self) -> &DataType {
self.target_field.data_type()
}
/// Explicit metadata for the output field, or `None` to pass through source metadata.
pub fn target_metadata(&self) -> Option<&Metadata> {
self.explicit_target.then(|| self.target_field.metadata())
}
/// Explicit nullability for the output field, or `None` to pass through source nullability.
pub fn target_nullable(&self) -> Option<bool> {
self.explicit_target
.then(|| self.target_field.is_nullable())
}
/// The target field this cast was constructed with.
///
/// For a type-only cast this is a field synthesized from the target data
/// type alone; only its data type is meaningful. Note that the returned
/// field may not match what `return_field()` returns when evaluated against
/// a schema, since `return_field()` may incorporate source field information.
///
/// Prefer [`cast_type()`], [`target_metadata()`], and [`target_nullable()`]
/// for direct access to the individual components.
///
/// [`cast_type()`]: CastExpr::cast_type
/// [`target_metadata()`]: CastExpr::target_metadata
/// [`target_nullable()`]: CastExpr::target_nullable
pub fn target_field(&self) -> &FieldRef {
&self.target_field
}
/// The cast options, borrowing custom format strings from this expression.
pub fn cast_options(&self) -> CastOptions<'_> {
self.cast_options.as_arrow()
}
/// Rebuild this cast with a new child and explicit target while preserving its options.
pub fn with_new_expr_and_target_field(
&self,
expr: Arc<dyn PhysicalExpr>,
target_field: FieldRef,
) -> Self {
Self {
expr,
target_field,
explicit_target: true,
cast_options: self.cast_options.clone(),
}
}
/// Whether this cast has explicit metadata (vs pass-through from source).
pub fn has_explicit_metadata(&self) -> bool {
self.explicit_target
}
/// Whether this cast has explicit nullability (vs pass-through from source).
pub fn has_explicit_nullability(&self) -> bool {
self.explicit_target
}
fn resolved_target_field(&self, input_schema: &Schema) -> Result<FieldRef> {
// Try to get the source field for the name. If the target field is
// explicit, we can fall back to an empty name if the source lookup fails
// (e.g., for virtual row-index columns appended at scan time).
let source_result = self.expr.return_field(input_schema);
if self.explicit_target {
// Metadata and nullability come from the target field verbatim
let name = source_result
.as_ref()
.map(|f| f.name().to_string())
.unwrap_or_default();
return Ok(Arc::new(
Field::new(
name,
self.cast_type().clone(),
self.target_field.is_nullable(),
)
.with_metadata(self.target_field.metadata().clone()),
));
}
// Type-only cast: pass through the source metadata and nullability,
// stripping extension type keys (the cast is to a plain storage type).
source_result.map(|source_field| {
let mut metadata = source_field.metadata().clone();
metadata.remove(EXTENSION_TYPE_NAME_KEY);
metadata.remove(EXTENSION_TYPE_METADATA_KEY);
Arc::new(
source_field
.as_ref()
.clone()
.with_data_type(self.cast_type().clone())
.with_metadata(metadata),
)
})
}
/// Check if casting from the source type to the target type is known to be
/// lossless and strictly order-preserving for all source values, preserving nulls.
/// This includes widening casts (e.g. `Int8` or `UInt8` to `Int16`) and representation
/// conversions such as `Int32` to `Date32`, which interprets the same integer
/// as days since the epoch, or `Int64` to `Date64`, which interprets the same
/// integer as milliseconds since the epoch.
pub fn check_bigger_cast(cast_type: &DataType, src: &DataType) -> bool {
if cast_type.eq(src) {
return true;
}
matches!(
(src, cast_type),
(Int8, Int16 | Int32 | Int64)
| (Int16, Int32 | Int64)
| (Int32, Int64)
| (Int32, Date32)
| (Date32, Int32)
| (Int64, Date64)
| (Date64, Int64)
| (UInt8, UInt16 | UInt32 | UInt64 | Int16 | Int32 | Int64)
| (UInt16, UInt32 | UInt64 | Int32 | Int64)
| (UInt32, UInt64 | Int64)
| (Int8 | Int16 | UInt8 | UInt16, Float32)
| (Int8 | Int16 | Int32 | UInt8 | UInt16 | UInt32, Float64)
| (Utf8, LargeUtf8 | Utf8View)
| (Binary, LargeBinary | BinaryView)
)
}
/// Check if the cast is lossless and strictly order-preserving for all source
/// values, preserving nulls. See [`Self::check_bigger_cast`].
pub fn is_bigger_cast(&self, src: &DataType) -> bool {
Self::check_bigger_cast(self.cast_type(), src)
}
}
/// UTC and fixed offsets have no timezone transitions.
fn is_fixed_offset(tz: &str) -> bool {
tz == "UTC" || tz.starts_with(['+', '-'])
}
fn is_binary(data_type: &DataType) -> bool {
matches!(
data_type,
Binary | LargeBinary | BinaryView | FixedSizeBinary(_)
)
}
/// Temporal types stored as a count of units since the epoch (or midnight),
/// which a cast from or to a number reads or writes as that count.
fn is_temporal_count(data_type: &DataType) -> bool {
matches!(
data_type,
Date32 | Date64 | Timestamp(_, _) | Time32(_) | Time64(_) | Duration(_)
)
}
/// Whether the cast never reverses the order of two values that both convert:
/// `a <= b` implies `cast(a) <= cast(b)`. Precision loss may merge values, so
/// this is not sufficient for propagating distinct counts or the ordering of
/// subsequent sort keys (see [`CastExpr::check_bigger_cast`] for that).
///
/// Values that fail to convert are not covered: callers must account for the
/// error or NULL a failure produces.
pub fn is_order_preserving_cast(source_type: &DataType, target_type: &DataType) -> bool {
if source_type == target_type
|| (source_type.is_numeric() || *source_type == Boolean)
&& target_type.is_numeric()
// Changing the string or binary encoding keeps the byte order.
|| source_type.is_string() && target_type.is_string()
|| is_binary(source_type) && is_binary(target_type)
|| source_type.is_numeric() && is_temporal_count(target_type)
|| is_temporal_count(source_type) && target_type.is_numeric()
{
return true;
}
// Temporal casts are not generally monotonic: extracting time-of-day wraps
// at midnight, and timezone transitions can reverse the local date.
match (source_type, target_type) {
(Date32 | Date64, Date32 | Date64) | (Timestamp(_, None), Date32 | Date64) => {
true
}
// Both date types take the date in the timestamp's timezone.
(Timestamp(_, Some(tz)), Date32 | Date64) => is_fixed_offset(tz),
// Arrow checks every scaling that can overflow, so a value that does
// not fit fails to convert instead of wrapping.
(Time32(_) | Time64(_), Time32(_) | Time64(_)) | (Duration(_), Duration(_)) => {
true
}
// Changing the timezone only changes metadata on the epoch value.
(Timestamp(_, Some(_)), Timestamp(_, _)) => true,
// Adding a timezone reads a naive timestamp (or a Date64, which may
// hold any time of day) as a local time. Arrow moves a local time that
// a transition skips forward by the length of the gap, past the local
// times just after the gap, so only a fixed offset keeps the order.
(Timestamp(_, None) | Date64, Timestamp(_, tz)) => {
tz.as_deref().is_none_or(is_fixed_offset)
}
// A Date32 reads as local midnight. A skipped midnight moves forward
// by the gap, and no gap is longer than a day, so it never passes the
// next midnight.
(Date32, Timestamp(_, _)) => true,
_ => false,
}
}
pub(crate) fn cast_expr_properties(
child: &ExprProperties,
target_type: &DataType,
null_on_failure: bool,
) -> Result<ExprProperties> {
let unbounded = Interval::make_unbounded(target_type)?;
let source_type = child.range.data_type();
// A lossless cast recognized by check_bigger_cast is one-to-one, so it is
// strictly order-preserving; a narrowing cast may collapse distinct values,
// breaking the ordering of subsequent sort keys.
let bigger_cast = CastExpr::check_bigger_cast(target_type, &source_type);
// New NULLs from failed conversions may violate NULLS FIRST/LAST, even
// if the successfully converted values remain ordered.
if bigger_cast
|| (!null_on_failure && is_order_preserving_cast(&source_type, target_type))
{
Ok(child
.clone()
.with_range(unbounded)
.with_strictly_order_preserving(
child.strictly_order_preserving && bigger_cast,
))
} else {
Ok(ExprProperties::new_unknown().with_range(unbounded))
}
}
#[cfg(feature = "proto")]
fn serialize_cast_options(
options: &OwnedCastOptions,
) -> Result<Option<datafusion_proto_models::protobuf::PhysicalCastOptions>> {
use datafusion_proto_models::protobuf;
let options = options.as_arrow();
if options.format_options.formatter_factory().is_some() {
return not_impl_err!(
"CastExpr serialization does not support a custom formatter_factory"
);
}
if options == DEFAULT_CAST_OPTIONS {
return Ok(None);
}
let CastOptions {
safe,
format_options,
} = options;
let duration_format = match format_options.duration_format() {
DurationFormat::ISO8601 => protobuf::PhysicalDurationFormat::Iso8601,
DurationFormat::Pretty => protobuf::PhysicalDurationFormat::Pretty,
_ => {
return not_impl_err!(
"CastExpr serialization does not support this duration format"
);
}
};
Ok(Some(protobuf::PhysicalCastOptions {
safe,
format_options: Some(protobuf::PhysicalFormatOptions {
safe: format_options.safe(),
null: format_options.null().to_owned(),
date_format: format_options.date_format().map(str::to_owned),
datetime_format: format_options.datetime_format().map(str::to_owned),
timestamp_format: format_options.timestamp_format().map(str::to_owned),
timestamp_tz_format: format_options.timestamp_tz_format().map(str::to_owned),
time_format: format_options.time_format().map(str::to_owned),
duration_format: duration_format.into(),
types_info: format_options.types_info(),
quoted_strings: format_options.quoted_strings(),
}),
}))
}
#[cfg(feature = "proto")]
fn deserialize_cast_options(
options: Option<&datafusion_proto_models::protobuf::PhysicalCastOptions>,
) -> Result<OwnedCastOptions> {
use datafusion_common::internal_datafusion_err;
use datafusion_proto_models::protobuf;
let Some(options) = options else {
return Ok(DEFAULT_CAST_OPTIONS.into());
};
let protobuf::PhysicalCastOptions {
safe,
format_options,
} = options;
let format_options = format_options.as_ref().ok_or_else(|| {
internal_datafusion_err!(
"CastExpr cast_options is missing required field 'format_options'"
)
})?;
let protobuf::PhysicalFormatOptions {
safe: format_safe,
null,
date_format,
datetime_format,
timestamp_format,
timestamp_tz_format,
time_format,
duration_format,
types_info,
quoted_strings,
} = format_options;
let duration_format = match protobuf::PhysicalDurationFormat::try_from(
*duration_format,
)
.map_err(|_| {
internal_datafusion_err!(
"CastExpr has invalid duration format value {duration_format}"
)
})? {
protobuf::PhysicalDurationFormat::Iso8601 => DurationFormat::ISO8601,
protobuf::PhysicalDurationFormat::Pretty => DurationFormat::Pretty,
};
Ok(OwnedCastOptions {
safe: *safe,
format_safe: *format_safe,
null: null.clone(),
date_format: date_format.clone(),
datetime_format: datetime_format.clone(),
timestamp_format: timestamp_format.clone(),
timestamp_tz_format: timestamp_tz_format.clone(),
time_format: time_format.clone(),
duration_format,
types_info: *types_info,
quoted_strings: *quoted_strings,
// Runtime formatter factories have no protobuf representation; the
// encoder rejects them rather than silently dropping behavior.
formatter_factory: None,
})
}
impl fmt::Display for CastExpr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "CAST({} AS {}", self.expr, self.cast_type())?;
// A cast to an explicit field can change only the nullability (for
// example when a union aligns its inputs), so show it the way schemas
// do: `;N` marks a nullable field.
if self.explicit_target && self.target_field.is_nullable() {
write!(f, ";N")?;
}
write!(f, ")")
}
}
impl PhysicalExpr for CastExpr {
fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
Ok(self.cast_type().clone())
}
fn nullable(&self, input_schema: &Schema) -> Result<bool> {
// A cast is nullable if **either** the child is nullable or the
// target field allows nulls. This conservative rule prevents
// optimizers from assuming a non-null result when a null input could
// still propagate. `return_field()` continues to expose the exact
// target metadata separately.
let child_nullable = self.expr.nullable(input_schema)?;
let target_nullable = self.resolved_target_field(input_schema)?.is_nullable();
Ok(child_nullable || target_nullable)
}
fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
let value = self.expr.evaluate(batch)?;
let cast_options = self.cast_options();
value
.cast_to(self.cast_type(), Some(&cast_options))
.map_err(|error| {
let source = self
.expr
.return_field(batch.schema().as_ref())
.ok()
.filter(|field| !field.name().is_empty())
.map(|field| format!("field '{}'", field.name()))
.unwrap_or_else(|| format!("expression '{}'", self.expr));
error.context(format!(
"Failed to cast {source} from {} to {}",
value.data_type(),
self.cast_type()
))
})
}
fn return_field(&self, input_schema: &Schema) -> Result<FieldRef> {
self.resolved_target_field(input_schema)
}
fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
vec![&self.expr]
}
fn with_new_children(
self: Arc<Self>,
children: Vec<Arc<dyn PhysicalExpr>>,
) -> Result<Arc<dyn PhysicalExpr>> {
Ok(Arc::new(CastExpr {
expr: Arc::clone(&children[0]),
target_field: Arc::clone(&self.target_field),
explicit_target: self.explicit_target,
cast_options: self.cast_options.clone(),
}))
}
fn evaluate_bounds(&self, children: &[&Interval]) -> Result<Interval> {
// Cast current node's interval to the right type:
children[0].cast_to(self.cast_type(), &self.cast_options())
}
fn propagate_constraints(
&self,
interval: &Interval,
children: &[&Interval],
) -> Result<Option<Vec<Interval>>> {
let source_type = children[0].data_type();
let target_type = self.cast_type();
if !can_propagate_cast_constraints(&source_type, target_type) {
return Ok(Some(vec![]));
}
Ok(Some(vec![
interval.cast_to(&source_type, &DEFAULT_SAFE_CAST_OPTIONS)?,
]))
}
/// Propagate ordering only for supported order-preserving conversions.
fn get_properties(&self, children: &[ExprProperties]) -> Result<ExprProperties> {
cast_expr_properties(&children[0], self.cast_type(), self.cast_options.safe)
}
fn fmt_sql(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "CAST(")?;
self.expr.fmt_sql(f)?;
write!(f, " AS {:?}", self.cast_type())?;
write!(f, ")")
}
#[cfg(feature = "proto")]
fn try_to_proto(
&self,
ctx: &datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx<'_>,
) -> Result<Option<datafusion_proto_models::protobuf::PhysicalExprNode>> {
use datafusion_proto_models::protobuf;
let Self {
expr,
target_field,
explicit_target,
cast_options,
} = self;
// Presence carries `explicit_target`, even for a default-shaped field.
let target_field_proto = if *explicit_target {
Some(target_field.as_ref().try_into()?)
} else {
None
};
let cast_options_proto = serialize_cast_options(cast_options)?;
Ok(Some(protobuf::PhysicalExprNode {
expr_id: None,
expr_type: Some(protobuf::physical_expr_node::ExprType::Cast(Box::new(
protobuf::PhysicalCastNode {
expr: Some(Box::new(ctx.encode_child(expr)?)),
arrow_type: Some(target_field.data_type().try_into()?),
target_field: target_field_proto,
cast_options: cast_options_proto,
},
))),
}))
}
}
/// Whether output bounds can be cast back to `source` without excluding valid inputs.
///
/// Used for reverse constraint propagation through a cast from `source` to `target`.
/// Many-to-one casts, such as Float64 to Int32, cannot generally be inverted this way:
/// an output of 0 does not imply an input of 0.0.
/// Returns false for unrecognized conversions so the input range remains unchanged.
fn can_propagate_cast_constraints(source: &DataType, target: &DataType) -> bool {
CastExpr::check_bigger_cast(target, source)
|| (source.is_integer() && target.is_integer())
// NaN bounds are unbounded; finite Float32 values widen exactly.
|| (*source == Float32 && *target == Float64)
}
#[cfg(feature = "proto")]
impl CastExpr {
/// Reconstruct a [`CastExpr`] from its protobuf representation.
///
/// Takes the whole [`PhysicalExprNode`] so the decode signature matches
/// other migrated expressions and can inspect outer-node metadata if
/// needed in the future.
///
/// [`PhysicalExprNode`]: datafusion_proto_models::protobuf::PhysicalExprNode
pub fn try_from_proto(
node: &datafusion_proto_models::protobuf::PhysicalExprNode,
ctx: &datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx<'_>,
) -> Result<Arc<dyn PhysicalExpr>> {
use datafusion_common::internal_err;
use datafusion_physical_expr_common::expect_expr_variant;
use datafusion_physical_expr_common::physical_expr::proto_decode::require_proto_field;
use datafusion_proto_models::protobuf;
let cast_expr = expect_expr_variant!(
node,
protobuf::physical_expr_node::ExprType::Cast,
"CastExpr",
);
let protobuf::PhysicalCastNode {
expr,
arrow_type,
target_field,
cast_options,
} = &**cast_expr;
let expr = ctx.decode_required_expression(expr.as_deref(), "CastExpr", "expr")?;
let arrow_type =
require_proto_field(arrow_type.as_ref(), "CastExpr", "arrow_type")?;
let cast_type: DataType = arrow_type.try_into()?;
let target_field = target_field
.as_ref()
.map(|field| {
let field: Field = field.try_into()?;
if field.data_type() != &cast_type {
return internal_err!(
"CastExpr target_field type does not match arrow_type"
);
}
Ok(Arc::new(field))
})
.transpose()?;
let cast_options = deserialize_cast_options(cast_options.as_ref())?;
let (target_field, explicit_target) = match target_field {
Some(target_field) => (target_field, true),
None => (cast_type.into_nullable_field_ref(), false),
};
Ok(Arc::new(CastExpr {
expr,
target_field,
explicit_target,
cast_options,
}))
}
}
/// Return a PhysicalExpression representing `expr` casted to
/// `cast_type`, if any casting is needed.
///
/// Note that such casts may lose type information
pub fn cast_with_options(
expr: Arc<dyn PhysicalExpr>,
input_schema: &Schema,
cast_type: DataType,
cast_options: Option<CastOptions<'static>>,
) -> Result<Arc<dyn PhysicalExpr>> {
let expr_type = expr.data_type(input_schema)?;
// If the types match, no cast is needed for a type-only cast
if expr_type == cast_type {
return Ok(Arc::clone(&expr));
}
let can_build_cast = if requires_nested_struct_cast(&expr_type, &cast_type) {
can_cast_named_struct_types(&expr_type, &cast_type)
} else {
can_cast_types(&expr_type, &cast_type)
};
if !can_build_cast {
return not_impl_err!("Unsupported CAST from {expr_type} to {cast_type}");
}
Ok(Arc::new(CastExpr::new(expr, cast_type, cast_options)))
}
/// Return a PhysicalExpression representing `expr` casted to `target_field`,
/// preserving any explicit field semantics such as name, nullability, and
/// metadata.
///
/// If the input expression already has the same data type and the target field
/// has no explicit metadata or nullability constraints, the original expression
/// is returned unchanged.
pub fn cast_with_target_field(
expr: Arc<dyn PhysicalExpr>,
input_schema: &Schema,
target_field: &FieldRef,
cast_options: Option<CastOptions<'static>>,
) -> Result<Arc<dyn PhysicalExpr>> {
let expr_type = expr.data_type(input_schema)?;
let cast_type = target_field.data_type();
// Check if this is a "default" target field (type-only cast with no explicit
// metadata or nullability constraints). This is the field created by
// `into_nullable_field_ref()` when only a DataType is known.
let is_type_only = target_field.name().is_empty()
&& target_field.is_nullable()
&& target_field.metadata().is_empty();
// For same-type casts, we can skip creating a CastExpr only if:
// 1. The target is type-only (no explicit metadata)
// 2. The source has no extension metadata that needs to be stripped
// Otherwise we need the CastExpr to strip extension metadata from the source.
if expr_type == *cast_type && is_type_only {
let source_field = expr.return_field(input_schema)?;
let has_extension_metadata = source_field
.metadata()
.contains_key(EXTENSION_TYPE_NAME_KEY);
if !has_extension_metadata {
return Ok(Arc::clone(&expr));
}
}
let can_build_cast = if requires_nested_struct_cast(&expr_type, cast_type) {
// Allow casts involving structs (including nested inside Lists, Dictionaries,
// etc.) that pass name-based compatibility validation. This validation is
// applied at planning time (now) to fail fast, rather than deferring errors
// to execution time. The name-based casting logic will be executed at runtime
// via ColumnarValue::cast_to.
can_cast_named_struct_types(&expr_type, cast_type)
} else {
can_cast_types(&expr_type, cast_type)
};
if !can_build_cast {
return not_impl_err!("Unsupported CAST from {expr_type} to {cast_type}");
}
// For type-only casts, use CastExpr::new which preserves source metadata/nullability.
// For explicit target fields, use new_with_target_field which applies the target's
// extension metadata and nullability.
if is_type_only {
Ok(Arc::new(CastExpr::new(
expr,
cast_type.clone(),
cast_options,
)))
} else {
Ok(Arc::new(CastExpr::new_with_target_field(
expr,
Arc::clone(target_field),
cast_options,
)))
}
}
/// Return a PhysicalExpression representing `expr` casted to
/// `cast_type`, if any casting is needed.
///
/// Note that such casts may lose type information
pub fn cast(
expr: Arc<dyn PhysicalExpr>,
input_schema: &Schema,
cast_type: DataType,
) -> Result<Arc<dyn PhysicalExpr>> {
cast_with_options(expr, input_schema, cast_type, None)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::expressions::column::col;
use arrow::{
array::{
Array, ArrayRef, Decimal128Array, Float32Array, Float64Array, Int8Array,
Int16Array, Int32Array, Int64Array, StringArray, StructArray,
Time64NanosecondArray, TimestampNanosecondArray, UInt32Array,
},
datatypes::*,
};
use datafusion_common::ScalarValue;
use datafusion_common::cast::{
as_boolean_array, as_int64_array, as_string_array, as_struct_array,
as_uint8_array,
};
use datafusion_common::rounding::{next_down, next_up};
use datafusion_physical_expr_common::physical_expr::fmt_sql;
use insta::assert_snapshot;
use std::collections::HashMap;
#[test]
fn test_cast_constraint_propagation() -> Result<()> {
for (source, target, propagates) in [
(Utf8, Int32, false),
(Utf8View, Int32, false),
(Timestamp(TimeUnit::Nanosecond, None), Date32, false),
(Int32, Date32, true),
(Date32, Int32, true),
(Utf8, LargeUtf8, true),
(Utf8, Utf8, true),
(Float64, Int32, false),
(Int64, Float32, false),
(Float64, Float32, false),
(Decimal128(4, 1), Decimal128(4, 0), false),
(Decimal128(4, 1), Int32, false),
(Float64, Decimal128(4, 1), false),
(Int8, Int64, true),
(Int64, Int8, true),
(Int32, UInt32, true),
(UInt32, Int32, true),
(Int32, Float64, true),
(Float32, Float64, true),
(Decimal128(4, 1), Decimal128(4, 1), true),
] {
let schema = Schema::new(vec![Field::new("x", source.clone(), true)]);
let expr = CastExpr::new(col("x", &schema)?, target.clone(), None);
let input = Interval::make_unbounded(&source)?;
let value = ScalarValue::Int32(Some(0)).cast_to(&target)?;
let output = Interval::from(&value);
let expected = if propagates {
vec![Interval::from(&value.cast_to(&source)?)]
} else {
vec![]
};
assert_eq!(
expr.propagate_constraints(&output, &[&input])?,
Some(expected),
"{source} -> {target}"
);
}
Ok(())
}
#[test]
fn test_float_widening_constraint_boundaries() -> Result<()> {
let mut values = vec![
f32::NEG_INFINITY,
-f32::MAX,
-1.0,
-f32::MIN_POSITIVE,
-f32::from_bits(1),
-0.0,
0.0,
f32::from_bits(1),
f32::MIN_POSITIVE,
1.0,
f32::MAX,
f32::INFINITY,
];
// Include both signs of signaling and quiet NaNs with distinct payloads.
values.extend(
[0x7f800001, 0x7f800002, 0x7fc00001, 0xff800001, 0xffc00001]
.map(f32::from_bits),
);
values.extend([next_down(1.0f32), next_up(1.0f32)]);
let schema = Arc::new(Schema::new(vec![Field::new("x", Float32, false)]));
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![Arc::new(Float32Array::from(values.clone()))],
)?;
let expr = CastExpr::new(col("x", &schema)?, Float64, None);
let array = expr.evaluate(&batch)?.into_array(values.len())?;