/
Cast.scala
2243 lines (2060 loc) · 85.9 KB
/
Cast.scala
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.
*/
package org.apache.spark.sql.catalyst.expressions
import java.time.{ZoneId, ZoneOffset}
import java.util.Locale
import java.util.concurrent.TimeUnit._
import org.apache.spark.{QueryContext, SparkArithmeticException, SparkIllegalArgumentException}
import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.analysis.TypeCheckResult
import org.apache.spark.sql.catalyst.analysis.TypeCheckResult.DataTypeMismatch
import org.apache.spark.sql.catalyst.expressions.codegen._
import org.apache.spark.sql.catalyst.expressions.codegen.Block._
import org.apache.spark.sql.catalyst.trees.TreeNodeTag
import org.apache.spark.sql.catalyst.trees.TreePattern._
import org.apache.spark.sql.catalyst.types.{PhysicalFractionalType, PhysicalIntegralType, PhysicalNumericType}
import org.apache.spark.sql.catalyst.util._
import org.apache.spark.sql.catalyst.util.DateTimeConstants._
import org.apache.spark.sql.catalyst.util.DateTimeUtils._
import org.apache.spark.sql.catalyst.util.IntervalUtils.{dayTimeIntervalToByte, dayTimeIntervalToDecimal, dayTimeIntervalToInt, dayTimeIntervalToLong, dayTimeIntervalToShort, yearMonthIntervalToByte, yearMonthIntervalToInt, yearMonthIntervalToShort}
import org.apache.spark.sql.errors.{QueryErrorsBase, QueryExecutionErrors}
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types._
import org.apache.spark.unsafe.types.{UTF8String, VariantVal}
import org.apache.spark.unsafe.types.UTF8String.{IntWrapper, LongWrapper}
import org.apache.spark.util.ArrayImplicits._
object Cast extends QueryErrorsBase {
/**
* As per section 6.13 "cast specification" in "Information technology — Database languages " +
* "- SQL — Part 2: Foundation (SQL/Foundation)":
* If the <cast operand> is a <value expression>, then the valid combinations of TD and SD
* in a <cast specification> are given by the following table. "Y" indicates that the
* combination is syntactically valid without restriction; "M" indicates that the combination
* is valid subject to other Syntax Rules in this Sub- clause being satisfied; and "N" indicates
* that the combination is not valid:
* SD TD
* EN AN C D T TS YM DT BO UDT B RT CT RW
* EN Y Y Y N N N M M N M N M N N
* AN Y Y Y N N N N N N M N M N N
* C Y Y Y Y Y Y Y Y Y M N M N N
* D N N Y Y N Y N N N M N M N N
* T N N Y N Y Y N N N M N M N N
* TS N N Y Y Y Y N N N M N M N N
* YM M N Y N N N Y N N M N M N N
* DT M N Y N N N N Y N M N M N N
* BO N N Y N N N N N Y M N M N N
* UDT M M M M M M M M M M M M M N
* B N N N N N N N N N M Y M N N
* RT M M M M M M M M M M M M N N
* CT N N N N N N N N N M N N M N
* RW N N N N N N N N N N N N N M
*
* Where:
* EN = Exact Numeric
* AN = Approximate Numeric
* C = Character (Fixed- or Variable-Length, or Character Large Object)
* D = Date
* T = Time
* TS = Timestamp
* YM = Year-Month Interval
* DT = Day-Time Interval
* BO = Boolean
* UDT = User-Defined Type
* B = Binary (Fixed- or Variable-Length or Binary Large Object)
* RT = Reference type
* CT = Collection type
* RW = Row type
*
* Spark's ANSI mode follows the syntax rules, except it specially allow the following
* straightforward type conversions which are disallowed as per the SQL standard:
* - Numeric <=> Boolean
* - String <=> Binary
*/
def canAnsiCast(from: DataType, to: DataType): Boolean = (from, to) match {
case (fromType, toType) if fromType == toType => true
case (NullType, _) => true
case (_, _: StringType) => true
case (_: StringType, _: BinaryType) => true
case (_: StringType, BooleanType) => true
case (_: NumericType, BooleanType) => true
case (_: StringType, TimestampType) => true
case (DateType, TimestampType) => true
case (TimestampNTZType, TimestampType) => true
case (_: NumericType, TimestampType) => true
case (_: StringType, TimestampNTZType) => true
case (DateType, TimestampNTZType) => true
case (TimestampType, TimestampNTZType) => true
case (_: StringType, _: CalendarIntervalType) => true
case (_: StringType, _: AnsiIntervalType) => true
case (_: AnsiIntervalType, _: IntegralType | _: DecimalType) => true
case (_: IntegralType | _: DecimalType, _: AnsiIntervalType) => true
case (_: DayTimeIntervalType, _: DayTimeIntervalType) => true
case (_: YearMonthIntervalType, _: YearMonthIntervalType) => true
case (_: StringType, DateType) => true
case (TimestampType, DateType) => true
case (TimestampNTZType, DateType) => true
case (_: NumericType, _: NumericType) => true
case (_: StringType, _: NumericType) => true
case (BooleanType, _: NumericType) => true
case (TimestampType, _: NumericType) => true
case (VariantType, _) => variant.VariantGet.checkDataType(to)
case (_, VariantType) => variant.VariantGet.checkDataType(from)
case (ArrayType(fromType, fn), ArrayType(toType, tn)) =>
canAnsiCast(fromType, toType) && resolvableNullability(fn, tn)
case (MapType(fromKey, fromValue, fn), MapType(toKey, toValue, tn)) =>
canAnsiCast(fromKey, toKey) && canAnsiCast(fromValue, toValue) &&
resolvableNullability(fn, tn)
case (StructType(fromFields), StructType(toFields)) =>
fromFields.length == toFields.length &&
fromFields.zip(toFields).forall {
case (fromField, toField) =>
canAnsiCast(fromField.dataType, toField.dataType) &&
resolvableNullability(fromField.nullable, toField.nullable)
}
case (udt1: UserDefinedType[_], udt2: UserDefinedType[_]) if udt2.acceptsType(udt1) => true
case _ => false
}
// If the target data type is a complex type which can't have Null values, we should guarantee
// that the casting between the element types won't produce Null results.
def canTryCast(from: DataType, to: DataType): Boolean = (from, to) match {
case (ArrayType(fromType, fn), ArrayType(toType, tn)) =>
canCast(fromType, toType) &&
resolvableNullability(fn || forceNullable(fromType, toType), tn)
case (MapType(fromKey, fromValue, fn), MapType(toKey, toValue, tn)) =>
canCast(fromKey, toKey) &&
(!forceNullable(fromKey, toKey)) &&
canCast(fromValue, toValue) &&
resolvableNullability(fn || forceNullable(fromValue, toValue), tn)
case (StructType(fromFields), StructType(toFields)) =>
fromFields.length == toFields.length &&
fromFields.zip(toFields).forall {
case (fromField, toField) =>
canCast(fromField.dataType, toField.dataType) &&
resolvableNullability(
fromField.nullable || forceNullable(fromField.dataType, toField.dataType),
toField.nullable)
}
case _ =>
Cast.canAnsiCast(from, to)
}
/**
* A tag to identify if a CAST added by the table insertion resolver.
*/
val BY_TABLE_INSERTION = TreeNodeTag[Unit]("by_table_insertion")
/**
* A tag to decide if a CAST is specified by user.
*/
val USER_SPECIFIED_CAST = new TreeNodeTag[Unit]("user_specified_cast")
/**
* Returns true iff we can cast `from` type to `to` type.
*/
def canCast(from: DataType, to: DataType): Boolean = (from, to) match {
case (fromType, toType) if fromType == toType => true
case (NullType, _) => true
case (_, _: StringType) => true
case (_: StringType, BinaryType) => true
case (_: IntegralType, BinaryType) => true
case (_: StringType, BooleanType) => true
case (DateType, BooleanType) => true
case (TimestampType, BooleanType) => true
case (_: NumericType, BooleanType) => true
case (_: StringType, TimestampType) => true
case (BooleanType, TimestampType) => true
case (DateType, TimestampType) => true
case (_: NumericType, TimestampType) => true
case (TimestampNTZType, TimestampType) => true
case (_: StringType, TimestampNTZType) => true
case (DateType, TimestampNTZType) => true
case (TimestampType, TimestampNTZType) => true
case (_: StringType, DateType) => true
case (TimestampType, DateType) => true
case (TimestampNTZType, DateType) => true
case (_: StringType, CalendarIntervalType) => true
case (_: StringType, _: DayTimeIntervalType) => true
case (_: StringType, _: YearMonthIntervalType) => true
case (_: IntegralType, DayTimeIntervalType(s, e)) if s == e => true
case (_: IntegralType, YearMonthIntervalType(s, e)) if s == e => true
case (_: DayTimeIntervalType, _: DayTimeIntervalType) => true
case (_: YearMonthIntervalType, _: YearMonthIntervalType) => true
case (_: AnsiIntervalType, _: IntegralType | _: DecimalType) => true
case (_: IntegralType | _: DecimalType, _: AnsiIntervalType) => true
case (_: StringType, _: NumericType) => true
case (BooleanType, _: NumericType) => true
case (DateType, _: NumericType) => true
case (TimestampType, _: NumericType) => true
case (_: NumericType, _: NumericType) => true
case (VariantType, _) => variant.VariantGet.checkDataType(to)
case (_, VariantType) => variant.VariantGet.checkDataType(from)
case (ArrayType(fromType, fn), ArrayType(toType, tn)) =>
canCast(fromType, toType) &&
resolvableNullability(fn || forceNullable(fromType, toType), tn)
case (MapType(fromKey, fromValue, fn), MapType(toKey, toValue, tn)) =>
canCast(fromKey, toKey) &&
(!forceNullable(fromKey, toKey)) &&
canCast(fromValue, toValue) &&
resolvableNullability(fn || forceNullable(fromValue, toValue), tn)
case (StructType(fromFields), StructType(toFields)) =>
fromFields.length == toFields.length &&
fromFields.zip(toFields).forall {
case (fromField, toField) =>
canCast(fromField.dataType, toField.dataType) &&
resolvableNullability(
fromField.nullable || forceNullable(fromField.dataType, toField.dataType),
toField.nullable)
}
case (udt1: UserDefinedType[_], udt2: UserDefinedType[_]) if udt2.acceptsType(udt1) => true
case _ => false
}
/**
* Return true if we need to use the `timeZone` information casting `from` type to `to` type.
* The patterns matched reflect the current implementation in the Cast node.
* c.f. usage of `timeZone` in:
* * Cast.castToString
* * Cast.castToDate
* * Cast.castToTimestamp
*/
def needsTimeZone(from: DataType, to: DataType): Boolean = (from, to) match {
case (VariantType, _) => true
case (_: StringType, TimestampType) => true
case (TimestampType, StringType) => true
case (DateType, TimestampType) => true
case (TimestampType, DateType) => true
case (TimestampType, TimestampNTZType) => true
case (TimestampNTZType, TimestampType) => true
case (ArrayType(fromType, _), ArrayType(toType, _)) => needsTimeZone(fromType, toType)
case (MapType(fromKey, fromValue, _), MapType(toKey, toValue, _)) =>
needsTimeZone(fromKey, toKey) || needsTimeZone(fromValue, toValue)
case (StructType(fromFields), StructType(toFields)) =>
fromFields.length == toFields.length &&
fromFields.zip(toFields).exists {
case (fromField, toField) =>
needsTimeZone(fromField.dataType, toField.dataType)
}
case _ => false
}
/**
* Returns true iff we can safely up-cast the `from` type to `to` type without any truncating or
* precision lose or possible runtime failures. For example, long -> int, string -> int are not
* up-cast.
*/
def canUpCast(from: DataType, to: DataType): Boolean = UpCastRule.canUpCast(from, to)
/**
* Returns true iff we can cast the `from` type to `to` type as per the ANSI SQL.
* In practice, the behavior is mostly the same as PostgreSQL. It disallows certain unreasonable
* type conversions such as converting `string` to `int` or `double` to `boolean`.
*/
def canANSIStoreAssign(from: DataType, to: DataType): Boolean = (from, to) match {
case _ if from == to => true
case (NullType, _) => true
case (_: NumericType, _: NumericType) => true
case (_: AtomicType, _: StringType) => true
case (_: CalendarIntervalType, _: StringType) => true
case (_: DatetimeType, _: DatetimeType) => true
case (ArrayType(fromType, fn), ArrayType(toType, tn)) =>
resolvableNullability(fn, tn) && canANSIStoreAssign(fromType, toType)
case (MapType(fromKey, fromValue, fn), MapType(toKey, toValue, tn)) =>
resolvableNullability(fn, tn) && canANSIStoreAssign(fromKey, toKey) &&
canANSIStoreAssign(fromValue, toValue)
case (StructType(fromFields), StructType(toFields)) =>
fromFields.length == toFields.length &&
fromFields.zip(toFields).forall {
case (f1, f2) =>
resolvableNullability(f1.nullable, f2.nullable) &&
canANSIStoreAssign(f1.dataType, f2.dataType)
}
case _ => false
}
def canNullSafeCastToDecimal(from: DataType, to: DecimalType): Boolean = from match {
case from: BooleanType if to.isWiderThan(DecimalType.BooleanDecimal) => true
case from: NumericType if to.isWiderThan(from) => true
case from: DecimalType =>
// truncating or precision lose
(to.precision - to.scale) > (from.precision - from.scale)
case _ => false // overflow
}
/**
* Returns `true` if casting non-nullable values from `from` type to `to` type
* may return null. Note that the caller side should take care of input nullability
* first and only call this method if the input is not nullable.
*/
def forceNullable(from: DataType, to: DataType): Boolean = (from, to) match {
case (NullType, _) => false // empty array or map case
case (_, _) if from == to => false
case (VariantType, _) => true
case (_: StringType, BinaryType | _: StringType) => false
case (_: StringType, _) => true
case (_, _: StringType) => false
case (TimestampType, ByteType | ShortType | IntegerType) => true
case (FloatType | DoubleType, TimestampType) => true
case (TimestampType, DateType) => false
case (_, DateType) => true
case (DateType, TimestampType) => false
case (DateType, _) => true
case (_, CalendarIntervalType) => true
case (_, to: DecimalType) if !canNullSafeCastToDecimal(from, to) => true
case (_: FractionalType, _: IntegralType) => true // NaN, infinity
case _ => false
}
def resolvableNullability(from: Boolean, to: Boolean): Boolean = !from || to
/**
* We process literals such as 'Infinity', 'Inf', '-Infinity' and 'NaN' etc in case
* insensitive manner to be compatible with other database systems such as PostgreSQL and DB2.
*/
def processFloatingPointSpecialLiterals(v: String, isFloat: Boolean): Any = {
v.trim.toLowerCase(Locale.ROOT) match {
case "inf" | "+inf" | "infinity" | "+infinity" =>
if (isFloat) Float.PositiveInfinity else Double.PositiveInfinity
case "-inf" | "-infinity" =>
if (isFloat) Float.NegativeInfinity else Double.NegativeInfinity
case "nan" =>
if (isFloat) Float.NaN else Double.NaN
case _ => null
}
}
def typeCheckFailureMessage(
from: DataType,
to: DataType,
fallbackConf: Option[(String, String)]): DataTypeMismatch = {
def withFunSuggest(names: String*): DataTypeMismatch = {
DataTypeMismatch(
errorSubClass = "CAST_WITH_FUNC_SUGGESTION",
messageParameters = Map(
"srcType" -> toSQLType(from),
"targetType" -> toSQLType(to),
"functionNames" -> names.map(toSQLId).mkString("/")))
}
(from, to) match {
case (_: NumericType, TimestampType) =>
withFunSuggest("TIMESTAMP_SECONDS", "TIMESTAMP_MILLIS", "TIMESTAMP_MICROS")
case (TimestampType, _: NumericType) =>
withFunSuggest("UNIX_SECONDS", "UNIX_MILLIS", "UNIX_MICROS")
case (_: NumericType, DateType) =>
withFunSuggest("DATE_FROM_UNIX_DATE")
case (DateType, _: NumericType) =>
withFunSuggest("UNIX_DATE")
case _ if fallbackConf.isDefined && Cast.canCast(from, to) =>
DataTypeMismatch(
errorSubClass = "CAST_WITH_CONF_SUGGESTION",
messageParameters = Map(
"srcType" -> toSQLType(from),
"targetType" -> toSQLType(to),
"config" -> toSQLConf(fallbackConf.get._1),
"configVal" -> toSQLValue(fallbackConf.get._2, StringType)))
case _ =>
DataTypeMismatch(
errorSubClass = "CAST_WITHOUT_SUGGESTION",
messageParameters = Map(
"srcType" -> toSQLType(from),
"targetType" -> toSQLType(to)))
}
}
def apply(
child: Expression,
dataType: DataType,
ansiEnabled: Boolean): Cast =
Cast(child, dataType, None, EvalMode.fromBoolean(ansiEnabled))
def apply(
child: Expression,
dataType: DataType,
timeZoneId: Option[String],
ansiEnabled: Boolean): Cast =
Cast(child, dataType, timeZoneId, EvalMode.fromBoolean(ansiEnabled))
}
/**
* Cast the child expression to the target data type.
*
* When cast from/to timezone related types, we need timeZoneId, which will be resolved with
* session local timezone by an analyzer [[ResolveTimeZone]].
*/
@ExpressionDescription(
usage = "_FUNC_(expr AS type) - Casts the value `expr` to the target data type `type`." +
" `expr` :: `type` alternative casting syntax is also supported.",
examples = """
Examples:
> SELECT _FUNC_('10' as int);
10
> SELECT '10' :: int;
10
""",
since = "1.0.0",
group = "conversion_funcs")
case class Cast(
child: Expression,
dataType: DataType,
timeZoneId: Option[String] = None,
evalMode: EvalMode.Value = EvalMode.fromSQLConf(SQLConf.get))
extends UnaryExpression
with TimeZoneAwareExpression
with ToStringBase
with NullIntolerant
with SupportQueryContext
with QueryErrorsBase {
def this(child: Expression, dataType: DataType, timeZoneId: Option[String]) =
this(child, dataType, timeZoneId, evalMode = EvalMode.fromSQLConf(SQLConf.get))
override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
copy(timeZoneId = Option(timeZoneId))
override protected def withNewChildInternal(newChild: Expression): Cast = copy(child = newChild)
final override def nodePatternsInternal(): Seq[TreePattern] = Seq(CAST)
def ansiEnabled: Boolean = {
evalMode == EvalMode.ANSI || (evalMode == EvalMode.TRY && !canUseLegacyCastForTryCast)
}
// Whether this expression is used for `try_cast()`.
def isTryCast: Boolean = {
evalMode == EvalMode.TRY
}
private def typeCheckFailureInCast: DataTypeMismatch = evalMode match {
case EvalMode.ANSI =>
if (getTagValue(Cast.BY_TABLE_INSERTION).isDefined) {
Cast.typeCheckFailureMessage(child.dataType, dataType,
Some(SQLConf.STORE_ASSIGNMENT_POLICY.key ->
SQLConf.StoreAssignmentPolicy.LEGACY.toString))
} else {
Cast.typeCheckFailureMessage(child.dataType, dataType,
Some(SQLConf.ANSI_ENABLED.key -> "false"))
}
case EvalMode.TRY =>
Cast.typeCheckFailureMessage(child.dataType, dataType, None)
case _ =>
DataTypeMismatch(
errorSubClass = "CAST_WITHOUT_SUGGESTION",
messageParameters = Map(
"srcType" -> toSQLType(child.dataType),
"targetType" -> toSQLType(dataType)))
}
override def checkInputDataTypes(): TypeCheckResult = {
val canCast = evalMode match {
case EvalMode.LEGACY => Cast.canCast(child.dataType, dataType)
case EvalMode.ANSI => Cast.canAnsiCast(child.dataType, dataType)
case EvalMode.TRY => Cast.canTryCast(child.dataType, dataType)
case other => throw new SparkIllegalArgumentException(
errorClass = "_LEGACY_ERROR_TEMP_3232",
messageParameters = Map("other" -> other.toString))
}
if (canCast) {
TypeCheckResult.TypeCheckSuccess
} else {
typeCheckFailureInCast
}
}
override def nullable: Boolean = if (!isTryCast) {
child.nullable || Cast.forceNullable(child.dataType, dataType)
} else {
(child.dataType, dataType) match {
case (_: StringType, BinaryType) => child.nullable
// TODO: Implement a more accurate method for checking whether a decimal value can be cast
// as integral types without overflow. Currently, the cast can overflow even if
// "Cast.canUpCast" method returns true.
case (_: DecimalType, _: IntegralType) => true
case _ => child.nullable || !Cast.canUpCast(child.dataType, dataType)
}
}
override def initQueryContext(): Option[QueryContext] = if (ansiEnabled) {
Some(origin.context)
} else {
None
}
// When this cast involves TimeZone, it's only resolved if the timeZoneId is set;
// Otherwise behave like Expression.resolved.
override lazy val resolved: Boolean =
childrenResolved && checkInputDataTypes().isSuccess && (!needsTimeZone || timeZoneId.isDefined)
override lazy val canonicalized: Expression = {
val basic = withNewChildren(Seq(child.canonicalized)).asInstanceOf[Cast]
if (timeZoneId.isDefined && !needsTimeZone) {
basic.withTimeZone(null)
} else {
basic
}
}
def needsTimeZone: Boolean = Cast.needsTimeZone(child.dataType, dataType)
// [[func]] assumes the input is no longer null because eval already does the null check.
@inline protected[this] def buildCast[T](a: Any, func: T => Any): Any = func(a.asInstanceOf[T])
private val legacyCastToStr = SQLConf.get.getConf(SQLConf.LEGACY_COMPLEX_TYPES_TO_STRING)
protected val (leftBracket, rightBracket) = if (legacyCastToStr) ("[", "]") else ("{", "}")
override protected def nullString: String = if (legacyCastToStr) "" else "null"
// In ANSI mode, Spark always use plain string representation on casting Decimal values
// as strings. Otherwise, the casting is using `BigDecimal.toString` which may use scientific
// notation if an exponent is needed.
override protected def useDecimalPlainString: Boolean = ansiEnabled
// The class name of `DateTimeUtils`
protected def dateTimeUtilsCls: String = DateTimeUtils.getClass.getName.stripSuffix("$")
// BinaryConverter
private[this] def castToBinary(from: DataType): Any => Any = from match {
case _: StringType => buildCast[UTF8String](_, _.getBytes)
case ByteType => buildCast[Byte](_, NumberConverter.toBinary)
case ShortType => buildCast[Short](_, NumberConverter.toBinary)
case IntegerType => buildCast[Int](_, NumberConverter.toBinary)
case LongType => buildCast[Long](_, NumberConverter.toBinary)
}
// UDFToBoolean
private[this] def castToBoolean(from: DataType): Any => Any = from match {
case _: StringType =>
buildCast[UTF8String](_, s => {
if (StringUtils.isTrueString(s)) {
true
} else if (StringUtils.isFalseString(s)) {
false
} else {
if (ansiEnabled) {
throw QueryExecutionErrors.invalidInputSyntaxForBooleanError(s, getContextOrNull())
} else {
null
}
}
})
case TimestampType =>
buildCast[Long](_, t => t != 0)
case DateType =>
// Hive would return null when cast from date to boolean
buildCast[Int](_, d => null)
case LongType =>
buildCast[Long](_, _ != 0)
case IntegerType =>
buildCast[Int](_, _ != 0)
case ShortType =>
buildCast[Short](_, _ != 0)
case ByteType =>
buildCast[Byte](_, _ != 0)
case DecimalType() =>
buildCast[Decimal](_, !_.isZero)
case DoubleType =>
buildCast[Double](_, _ != 0)
case FloatType =>
buildCast[Float](_, _ != 0)
}
// TimestampConverter
private[this] def castToTimestamp(from: DataType): Any => Any = from match {
case _: StringType =>
buildCast[UTF8String](_, utfs => {
if (ansiEnabled) {
DateTimeUtils.stringToTimestampAnsi(utfs, zoneId, getContextOrNull())
} else {
DateTimeUtils.stringToTimestamp(utfs, zoneId).orNull
}
})
case BooleanType =>
buildCast[Boolean](_, b => if (b) 1L else 0L)
case LongType =>
buildCast[Long](_, l => longToTimestamp(l))
case IntegerType =>
buildCast[Int](_, i => longToTimestamp(i.toLong))
case ShortType =>
buildCast[Short](_, s => longToTimestamp(s.toLong))
case ByteType =>
buildCast[Byte](_, b => longToTimestamp(b.toLong))
case DateType =>
buildCast[Int](_, d => daysToMicros(d, zoneId))
case TimestampNTZType =>
buildCast[Long](_, ts => convertTz(ts, zoneId, ZoneOffset.UTC))
// TimestampWritable.decimalToTimestamp
case DecimalType() =>
buildCast[Decimal](_, d => decimalToTimestamp(d))
// TimestampWritable.doubleToTimestamp
case DoubleType =>
if (ansiEnabled) {
buildCast[Double](_, d => doubleToTimestampAnsi(d, getContextOrNull()))
} else {
buildCast[Double](_, d => doubleToTimestamp(d))
}
// TimestampWritable.floatToTimestamp
case FloatType =>
if (ansiEnabled) {
buildCast[Float](_, f => doubleToTimestampAnsi(f.toDouble, getContextOrNull()))
} else {
buildCast[Float](_, f => doubleToTimestamp(f.toDouble))
}
}
private[this] def castToTimestampNTZ(from: DataType): Any => Any = from match {
case _: StringType =>
buildCast[UTF8String](_, utfs => {
if (ansiEnabled) {
DateTimeUtils.stringToTimestampWithoutTimeZoneAnsi(utfs, getContextOrNull())
} else {
DateTimeUtils.stringToTimestampWithoutTimeZone(utfs).orNull
}
})
case DateType =>
buildCast[Int](_, d => daysToMicros(d, ZoneOffset.UTC))
case TimestampType =>
buildCast[Long](_, ts => convertTz(ts, ZoneOffset.UTC, zoneId))
}
private[this] def decimalToTimestamp(d: Decimal): Long = {
(d.toBigDecimal * MICROS_PER_SECOND).longValue
}
private[this] def doubleToTimestamp(d: Double): Any = {
if (d.isNaN || d.isInfinite) null else (d * MICROS_PER_SECOND).toLong
}
// converting seconds to us
private[this] def longToTimestamp(t: Long): Long = SECONDS.toMicros(t)
// converting us to seconds
private[this] def timestampToLong(ts: Long): Long = {
Math.floorDiv(ts, MICROS_PER_SECOND)
}
// converting us to seconds in double
private[this] def timestampToDouble(ts: Long): Double = {
ts / MICROS_PER_SECOND.toDouble
}
// DateConverter
private[this] def castToDate(from: DataType): Any => Any = from match {
case _: StringType =>
if (ansiEnabled) {
buildCast[UTF8String](_, s => DateTimeUtils.stringToDateAnsi(s, getContextOrNull()))
} else {
buildCast[UTF8String](_, s => DateTimeUtils.stringToDate(s).orNull)
}
case TimestampType =>
// throw valid precision more than seconds, according to Hive.
// Timestamp.nanos is in 0 to 999,999,999, no more than a second.
buildCast[Long](_, t => microsToDays(t, zoneId))
case TimestampNTZType =>
buildCast[Long](_, t => microsToDays(t, ZoneOffset.UTC))
}
// IntervalConverter
private[this] def castToInterval(from: DataType): Any => Any = from match {
case _: StringType =>
buildCast[UTF8String](_, s => IntervalUtils.safeStringToInterval(s))
}
private[this] def castToDayTimeInterval(
from: DataType,
it: DayTimeIntervalType): Any => Any = from match {
case _: StringType => buildCast[UTF8String](_, s =>
IntervalUtils.castStringToDTInterval(s, it.startField, it.endField))
case _: DayTimeIntervalType => buildCast[Long](_, s =>
IntervalUtils.durationToMicros(IntervalUtils.microsToDuration(s), it.endField))
case x: IntegralType =>
if (x == LongType) {
b => IntervalUtils.longToDayTimeInterval(
PhysicalIntegralType.integral(x).toLong(b), it.startField, it.endField)
} else {
b => IntervalUtils.intToDayTimeInterval(
PhysicalIntegralType.integral(x).toInt(b), it.startField, it.endField)
}
case DecimalType.Fixed(p, s) =>
buildCast[Decimal](_, d =>
IntervalUtils.decimalToDayTimeInterval(d, p, s, it.startField, it.endField))
}
private[this] def castToYearMonthInterval(
from: DataType,
it: YearMonthIntervalType): Any => Any = from match {
case _: StringType => buildCast[UTF8String](_, s =>
IntervalUtils.castStringToYMInterval(s, it.startField, it.endField))
case _: YearMonthIntervalType => buildCast[Int](_, s =>
IntervalUtils.periodToMonths(IntervalUtils.monthsToPeriod(s), it.endField))
case x: IntegralType =>
if (x == LongType) {
b => IntervalUtils.longToYearMonthInterval(
PhysicalIntegralType.integral(x).toLong(b), it.startField, it.endField)
} else {
b => IntervalUtils.intToYearMonthInterval(
PhysicalIntegralType.integral(x).toInt(b), it.startField, it.endField)
}
case DecimalType.Fixed(p, s) =>
buildCast[Decimal](_, d =>
IntervalUtils.decimalToYearMonthInterval(d, p, s, it.startField, it.endField))
}
// LongConverter
private[this] def castToLong(from: DataType): Any => Any = from match {
case _: StringType if ansiEnabled =>
buildCast[UTF8String](_, v => UTF8StringUtils.toLongExact(v, getContextOrNull()))
case _: StringType =>
val result = new LongWrapper()
buildCast[UTF8String](_, s => if (s.toLong(result)) result.value else null)
case BooleanType =>
buildCast[Boolean](_, b => if (b) 1L else 0L)
case DateType =>
buildCast[Int](_, d => null)
case TimestampType =>
buildCast[Long](_, t => timestampToLong(t))
case x: NumericType if ansiEnabled =>
val exactNumeric = PhysicalNumericType.exactNumeric(x)
b => exactNumeric.toLong(b)
case x: NumericType =>
val numeric = PhysicalNumericType.numeric(x)
b => numeric.toLong(b)
case x: DayTimeIntervalType =>
buildCast[Long](_, i => dayTimeIntervalToLong(i, x.startField, x.endField))
case x: YearMonthIntervalType =>
buildCast[Int](_, i => yearMonthIntervalToInt(i, x.startField, x.endField).toLong)
}
private def errorOrNull(t: Any, from: DataType, to: DataType) = {
if (ansiEnabled) {
throw QueryExecutionErrors.castingCauseOverflowError(t, from, to)
} else {
null
}
}
// IntConverter
private[this] def castToInt(from: DataType): Any => Any = from match {
case _: StringType if ansiEnabled =>
buildCast[UTF8String](_, v => UTF8StringUtils.toIntExact(v, getContextOrNull()))
case _: StringType =>
val result = new IntWrapper()
buildCast[UTF8String](_, s => if (s.toInt(result)) result.value else null)
case BooleanType =>
buildCast[Boolean](_, b => if (b) 1 else 0)
case DateType =>
buildCast[Int](_, d => null)
case TimestampType =>
buildCast[Long](_, t => {
val longValue = timestampToLong(t)
if (longValue == longValue.toInt) {
longValue.toInt
} else {
errorOrNull(t, from, IntegerType)
}
})
case x: NumericType if ansiEnabled =>
val exactNumeric = PhysicalNumericType.exactNumeric(x)
b => exactNumeric.toInt(b)
case x: NumericType =>
val numeric = PhysicalNumericType.numeric(x)
b => numeric.toInt(b)
case x: DayTimeIntervalType =>
buildCast[Long](_, i => dayTimeIntervalToInt(i, x.startField, x.endField))
case x: YearMonthIntervalType =>
buildCast[Int](_, i => yearMonthIntervalToInt(i, x.startField, x.endField))
}
// ShortConverter
private[this] def castToShort(from: DataType): Any => Any = from match {
case _: StringType if ansiEnabled =>
buildCast[UTF8String](_, v => UTF8StringUtils.toShortExact(v, getContextOrNull()))
case _: StringType =>
val result = new IntWrapper()
buildCast[UTF8String](_, s => if (s.toShort(result)) {
result.value.toShort
} else {
null
})
case BooleanType =>
buildCast[Boolean](_, b => if (b) 1.toShort else 0.toShort)
case DateType =>
buildCast[Int](_, d => null)
case TimestampType =>
buildCast[Long](_, t => {
val longValue = timestampToLong(t)
if (longValue == longValue.toShort) {
longValue.toShort
} else {
errorOrNull(t, from, ShortType)
}
})
case x: NumericType if ansiEnabled =>
val exactNumeric = PhysicalNumericType.exactNumeric(x)
b =>
val intValue = try {
exactNumeric.toInt(b)
} catch {
case _: ArithmeticException =>
throw QueryExecutionErrors.castingCauseOverflowError(b, from, ShortType)
}
if (intValue == intValue.toShort) {
intValue.toShort
} else {
throw QueryExecutionErrors.castingCauseOverflowError(b, from, ShortType)
}
case x: NumericType =>
val numeric = PhysicalNumericType.numeric(x)
b => numeric.toInt(b).toShort
case x: DayTimeIntervalType =>
buildCast[Long](_, i => dayTimeIntervalToShort(i, x.startField, x.endField))
case x: YearMonthIntervalType =>
buildCast[Int](_, i => yearMonthIntervalToShort(i, x.startField, x.endField))
}
// ByteConverter
private[this] def castToByte(from: DataType): Any => Any = from match {
case _: StringType if ansiEnabled =>
buildCast[UTF8String](_, v => UTF8StringUtils.toByteExact(v, getContextOrNull()))
case _: StringType =>
val result = new IntWrapper()
buildCast[UTF8String](_, s => if (s.toByte(result)) {
result.value.toByte
} else {
null
})
case BooleanType =>
buildCast[Boolean](_, b => if (b) 1.toByte else 0.toByte)
case DateType =>
buildCast[Int](_, d => null)
case TimestampType =>
buildCast[Long](_, t => {
val longValue = timestampToLong(t)
if (longValue == longValue.toByte) {
longValue.toByte
} else {
errorOrNull(t, from, ByteType)
}
})
case x: NumericType if ansiEnabled =>
val exactNumeric = PhysicalNumericType.exactNumeric(x)
b =>
val intValue = try {
exactNumeric.toInt(b)
} catch {
case _: ArithmeticException =>
throw QueryExecutionErrors.castingCauseOverflowError(b, from, ByteType)
}
if (intValue == intValue.toByte) {
intValue.toByte
} else {
throw QueryExecutionErrors.castingCauseOverflowError(b, from, ByteType)
}
case x: NumericType =>
val numeric = PhysicalNumericType.numeric(x)
b => numeric.toInt(b).toByte
case x: DayTimeIntervalType =>
buildCast[Long](_, i => dayTimeIntervalToByte(i, x.startField, x.endField))
case x: YearMonthIntervalType =>
buildCast[Int](_, i => yearMonthIntervalToByte(i, x.startField, x.endField))
}
/**
* Change the precision / scale in a given decimal to those set in `decimalType` (if any),
* modifying `value` in-place and returning it if successful. If an overflow occurs, it
* either returns null or throws an exception according to the value set for
* `spark.sql.ansi.enabled`.
*
* NOTE: this modifies `value` in-place, so don't call it on external data.
*/
private[this] def changePrecision(value: Decimal, decimalType: DecimalType): Decimal = {
changePrecision(value, decimalType, !ansiEnabled)
}
private[this] def changePrecision(
value: Decimal,
decimalType: DecimalType,
nullOnOverflow: Boolean): Decimal = {
if (value.changePrecision(decimalType.precision, decimalType.scale)) {
value
} else {
if (nullOnOverflow) {
null
} else {
throw QueryExecutionErrors.cannotChangeDecimalPrecisionError(
value, decimalType.precision, decimalType.scale, getContextOrNull())
}
}
}
/**
* Create new `Decimal` with precision and scale given in `decimalType` (if any).
* If overflow occurs, if `spark.sql.ansi.enabled` is false, null is returned;
* otherwise, an `ArithmeticException` is thrown.
*/
private[this] def toPrecision(
value: Decimal,
decimalType: DecimalType,
context: QueryContext): Decimal =
value.toPrecision(
decimalType.precision, decimalType.scale, Decimal.ROUND_HALF_UP, !ansiEnabled, context)
private[this] def castToDecimal(from: DataType, target: DecimalType): Any => Any = from match {
case _: StringType if !ansiEnabled =>
buildCast[UTF8String](_, s => {
val d = Decimal.fromString(s)
if (d == null) null else changePrecision(d, target)
})
case _: StringType if ansiEnabled =>
buildCast[UTF8String](_,
s => changePrecision(Decimal.fromStringANSI(s, target, getContextOrNull()), target))
case BooleanType =>
buildCast[Boolean](_,
b => toPrecision(if (b) Decimal.ONE else Decimal.ZERO, target, getContextOrNull()))
case DateType =>
buildCast[Int](_, d => null) // date can't cast to decimal in Hive
case TimestampType =>
// Note that we lose precision here.
buildCast[Long](_, t => changePrecision(Decimal(timestampToDouble(t)), target))
case dt: DecimalType =>
b => toPrecision(b.asInstanceOf[Decimal], target, getContextOrNull())
case t: IntegralType =>
b => changePrecision(Decimal(PhysicalIntegralType.integral(t).toLong(b)), target)
case x: FractionalType =>
val fractional = PhysicalFractionalType.fractional(x)
b => try {
changePrecision(Decimal(fractional.toDouble(b)), target)
} catch {
case _: NumberFormatException => null
}
case x: DayTimeIntervalType =>
buildCast[Long](_, dt =>
changePrecision(
value = dayTimeIntervalToDecimal(dt, x.endField),
decimalType = target,
nullOnOverflow = false))
case x: YearMonthIntervalType =>
buildCast[Int](_, ym =>