@@ -58,6 +58,7 @@ use arrow::{
58
58
use arrow_buffer:: { IntervalDayTime , IntervalMonthDayNano , ScalarBuffer } ;
59
59
use arrow_schema:: { UnionFields , UnionMode } ;
60
60
61
+ use crate :: format:: DEFAULT_CAST_OPTIONS ;
61
62
use half:: f16;
62
63
pub use struct_builder:: ScalarStructBuilder ;
63
64
@@ -2809,22 +2810,30 @@ impl ScalarValue {
2809
2810
2810
2811
/// Try to parse `value` into a ScalarValue of type `target_type`
2811
2812
pub fn try_from_string ( value : String , target_type : & DataType ) -> Result < Self > {
2812
- let value = ScalarValue :: from ( value) ;
2813
- let cast_options = CastOptions {
2814
- safe : false ,
2815
- format_options : Default :: default ( ) ,
2816
- } ;
2817
- let cast_arr = cast_with_options ( & value. to_array ( ) ?, target_type, & cast_options) ?;
2818
- ScalarValue :: try_from_array ( & cast_arr, 0 )
2813
+ ScalarValue :: from ( value) . cast_to ( target_type)
2819
2814
}
2820
2815
2821
2816
/// Try to cast this value to a ScalarValue of type `data_type`
2822
- pub fn cast_to ( & self , data_type : & DataType ) -> Result < Self > {
2823
- let cast_options = CastOptions {
2824
- safe : false ,
2825
- format_options : Default :: default ( ) ,
2817
+ pub fn cast_to ( & self , target_type : & DataType ) -> Result < Self > {
2818
+ self . cast_to_with_options ( target_type, & DEFAULT_CAST_OPTIONS )
2819
+ }
2820
+
2821
+ /// Try to cast this value to a ScalarValue of type `data_type` with [`CastOptions`]
2822
+ pub fn cast_to_with_options (
2823
+ & self ,
2824
+ target_type : & DataType ,
2825
+ cast_options : & CastOptions < ' static > ,
2826
+ ) -> Result < Self > {
2827
+ let scalar_array = match ( self , target_type) {
2828
+ (
2829
+ ScalarValue :: Float64 ( Some ( float_ts) ) ,
2830
+ DataType :: Timestamp ( TimeUnit :: Nanosecond , None ) ,
2831
+ ) => ScalarValue :: Int64 ( Some ( ( float_ts * 1_000_000_000_f64 ) . trunc ( ) as i64 ) )
2832
+ . to_array ( ) ?,
2833
+ _ => self . to_array ( ) ?,
2826
2834
} ;
2827
- let cast_arr = cast_with_options ( & self . to_array ( ) ?, data_type, & cast_options) ?;
2835
+
2836
+ let cast_arr = cast_with_options ( & scalar_array, target_type, cast_options) ?;
2828
2837
ScalarValue :: try_from_array ( & cast_arr, 0 )
2829
2838
}
2830
2839
0 commit comments