-
Notifications
You must be signed in to change notification settings - Fork 28.2k
/
TypeCoercion.scala
1246 lines (1115 loc) · 53.5 KB
/
TypeCoercion.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.analysis
import javax.annotation.Nullable
import scala.annotation.tailrec
import scala.collection.mutable
import org.apache.spark.internal.Logging
import org.apache.spark.sql.catalyst.expressions._
import org.apache.spark.sql.catalyst.expressions.aggregate._
import org.apache.spark.sql.catalyst.plans.logical._
import org.apache.spark.sql.catalyst.rules.Rule
import org.apache.spark.sql.catalyst.trees.AlwaysProcess
import org.apache.spark.sql.catalyst.types.DataTypeUtils
import org.apache.spark.sql.errors.QueryCompilationErrors
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types._
import org.apache.spark.sql.types.UpCastRule.numericPrecedence
abstract class TypeCoercionBase {
/**
* A collection of [[Rule]] that can be used to coerce differing types that participate in
* operations into compatible ones.
*/
def typeCoercionRules: List[Rule[LogicalPlan]]
/**
* Find the tightest common type of two types that might be used in a binary expression.
* This handles all numeric types except fixed-precision decimals interacting with each other or
* with primitive types, because in that case the precision and scale of the result depends on
* the operation. Those rules are implemented in [[DecimalPrecision]].
*/
val findTightestCommonType: (DataType, DataType) => Option[DataType]
/**
* Looking for a widened data type of two given data types with some acceptable loss of precision.
* E.g. there is no common type for double and decimal because double's range
* is larger than decimal, and yet decimal is more precise than double, but in
* union we would cast the decimal into double.
*/
def findWiderTypeForTwo(t1: DataType, t2: DataType): Option[DataType]
/**
* Looking for a widened data type of a given sequence of data types with some acceptable loss
* of precision.
* E.g. there is no common type for double and decimal because double's range
* is larger than decimal, and yet decimal is more precise than double, but in
* union we would cast the decimal into double.
*/
def findWiderCommonType(types: Seq[DataType]): Option[DataType]
/**
* Given an expected data type, try to cast the expression and return the cast expression.
*
* If the expression already fits the input type, we simply return the expression itself.
* If the expression has an incompatible type that cannot be implicitly cast, return None.
*/
def implicitCast(e: Expression, expectedType: AbstractDataType): Option[Expression]
/**
* Whether casting `from` as `to` is valid.
*/
def canCast(from: DataType, to: DataType): Boolean
protected def findTypeForComplex(
t1: DataType,
t2: DataType,
findTypeFunc: (DataType, DataType) => Option[DataType]): Option[DataType] = (t1, t2) match {
case (ArrayType(et1, containsNull1), ArrayType(et2, containsNull2)) =>
findTypeFunc(et1, et2).map { et =>
ArrayType(et, containsNull1 || containsNull2 ||
Cast.forceNullable(et1, et) || Cast.forceNullable(et2, et))
}
case (MapType(kt1, vt1, valueContainsNull1), MapType(kt2, vt2, valueContainsNull2)) =>
findTypeFunc(kt1, kt2)
.filter { kt => !Cast.forceNullable(kt1, kt) && !Cast.forceNullable(kt2, kt) }
.flatMap { kt =>
findTypeFunc(vt1, vt2).map { vt =>
MapType(kt, vt, valueContainsNull1 || valueContainsNull2 ||
Cast.forceNullable(vt1, vt) || Cast.forceNullable(vt2, vt))
}
}
case (StructType(fields1), StructType(fields2)) if fields1.length == fields2.length =>
val resolver = SQLConf.get.resolver
fields1.zip(fields2).foldLeft(Option(new StructType())) {
case (Some(struct), (field1, field2)) if resolver(field1.name, field2.name) =>
findTypeFunc(field1.dataType, field2.dataType).map { dt =>
struct.add(field1.name, dt, field1.nullable || field2.nullable ||
Cast.forceNullable(field1.dataType, dt) || Cast.forceNullable(field2.dataType, dt))
}
case _ => None
}
case _ => None
}
/**
* Finds a wider type when one or both types are decimals. If the wider decimal type exceeds
* system limitation, this rule will truncate the decimal type. If a decimal and other fractional
* types are compared, returns a double type.
*/
protected def findWiderTypeForDecimal(dt1: DataType, dt2: DataType): Option[DataType] = {
(dt1, dt2) match {
case (t1: DecimalType, t2: DecimalType) =>
Some(DecimalPrecision.widerDecimalType(t1, t2))
case (t: IntegralType, d: DecimalType) =>
Some(DecimalPrecision.widerDecimalType(DecimalType.forType(t), d))
case (d: DecimalType, t: IntegralType) =>
Some(DecimalPrecision.widerDecimalType(DecimalType.forType(t), d))
case (_: FractionalType, _: DecimalType) | (_: DecimalType, _: FractionalType) =>
Some(DoubleType)
case _ => None
}
}
/**
* Similar to [[findWiderTypeForTwo]] that can handle decimal types, but can't promote to
* string. If the wider decimal type exceeds system limitation, this rule will truncate
* the decimal type before return it.
*/
private[catalyst] def findWiderTypeWithoutStringPromotionForTwo(
t1: DataType,
t2: DataType): Option[DataType] = {
findTightestCommonType(t1, t2)
.orElse(findWiderTypeForDecimal(t1, t2))
.orElse(findTypeForComplex(t1, t2, findWiderTypeWithoutStringPromotionForTwo))
}
def findWiderTypeWithoutStringPromotion(types: Seq[DataType]): Option[DataType] = {
types.foldLeft[Option[DataType]](Some(NullType))((r, c) => r match {
case Some(d) => findWiderTypeWithoutStringPromotionForTwo(d, c)
case None => None
})
}
/**
* Check whether the given types are equal ignoring nullable, containsNull and valueContainsNull.
*/
def haveSameType(types: Seq[DataType]): Boolean = {
if (types.size <= 1) {
true
} else {
val head = types.head
types.tail.forall(e => DataTypeUtils.sameType(e, head))
}
}
protected def castIfNotSameType(expr: Expression, dt: DataType): Expression = {
if (!DataTypeUtils.sameType(expr.dataType, dt)) {
Cast(expr, dt)
} else {
expr
}
}
protected def findWiderDateTimeType(d1: DatetimeType, d2: DatetimeType): DatetimeType =
(d1, d2) match {
case (_: TimestampType, _: DateType) | (_: DateType, _: TimestampType) =>
TimestampType
case (_: TimestampType, _: TimestampNTZType) | (_: TimestampNTZType, _: TimestampType) =>
TimestampType
case (_: TimestampNTZType, _: DateType) | (_: DateType, _: TimestampNTZType) =>
TimestampNTZType
}
/**
* Type coercion rule that combines multiple type coercion rules and applies them in a single tree
* traversal.
*/
class CombinedTypeCoercionRule(rules: Seq[TypeCoercionRule]) extends TypeCoercionRule {
override def transform: PartialFunction[Expression, Expression] = {
val transforms = rules.map(_.transform)
Function.unlift { e: Expression =>
val result = transforms.foldLeft(e) {
case (current, transform) => transform.applyOrElse(current, identity[Expression])
}
if (result ne e) {
Some(result)
} else {
None
}
}
}
}
/**
* Widens the data types of the [[Unpivot]] values.
*/
object UnpivotCoercion extends Rule[LogicalPlan] {
override def apply(plan: LogicalPlan): LogicalPlan = plan resolveOperators {
case up: Unpivot if up.canBeCoercioned && !up.valuesTypeCoercioned =>
// get wider data type of inner values at same idx
val valueDataTypes = up.values.get.head.zipWithIndex.map {
case (_, idx) => findWiderTypeWithoutStringPromotion(up.values.get.map(_ (idx).dataType))
}
// cast inner values to type according to their idx
val values = up.values.get.map(values =>
values.zipWithIndex.map {
case (value, idx) => (value, valueDataTypes(idx))
} map {
case (value, Some(valueType)) if value.dataType != valueType =>
Alias(Cast(value, valueType), value.name)()
case (value, _) => value
}
)
up.copy(values = Some(values))
}
}
/**
* Widens the data types of the children of Union/Except/Intersect.
* 1. When ANSI mode is off:
* Loosely based on rules from "Hadoop: The Definitive Guide" 2nd edition, by Tom White
*
* The implicit conversion rules can be summarized as follows:
* - Any integral numeric type can be implicitly converted to a wider type.
* - All the integral numeric types, FLOAT, and (perhaps surprisingly) STRING can be
* implicitly converted to DOUBLE.
* - TINYINT, SMALLINT, and INT can all be converted to FLOAT.
* - BOOLEAN types cannot be converted to any other type.
* - Any integral numeric type can be implicitly converted to decimal type.
* - two different decimal types will be converted into a wider decimal type for both of them.
* - decimal type will be converted into double if there float or double together with it.
*
* All types when UNION-ed with strings will be promoted to
* strings. Other string conversions are handled by PromoteStrings.
*
* Widening types might result in loss of precision in the following cases:
* - IntegerType to FloatType
* - LongType to FloatType
* - LongType to DoubleType
* - DecimalType to Double
*
* 2. When ANSI mode is on:
* The implicit conversion is determined by the closest common data type from the precedent
* lists from left and right child. See the comments of Object `AnsiTypeCoercion` for details.
*/
object WidenSetOperationTypes extends Rule[LogicalPlan] {
override def apply(plan: LogicalPlan): LogicalPlan = {
plan resolveOperatorsUpWithNewOutput {
case s @ Except(left, right, isAll) if s.childrenResolved &&
left.output.length == right.output.length && !s.resolved =>
val newChildren: Seq[LogicalPlan] = buildNewChildrenWithWiderTypes(left :: right :: Nil)
if (newChildren.isEmpty) {
s -> Nil
} else {
assert(newChildren.length == 2)
val attrMapping = left.output.zip(newChildren.head.output)
Except(newChildren.head, newChildren.last, isAll) -> attrMapping
}
case s @ Intersect(left, right, isAll) if s.childrenResolved &&
left.output.length == right.output.length && !s.resolved =>
val newChildren: Seq[LogicalPlan] = buildNewChildrenWithWiderTypes(left :: right :: Nil)
if (newChildren.isEmpty) {
s -> Nil
} else {
assert(newChildren.length == 2)
val attrMapping = left.output.zip(newChildren.head.output)
Intersect(newChildren.head, newChildren.last, isAll) -> attrMapping
}
case s: Union if s.childrenResolved && !s.byName &&
s.children.forall(_.output.length == s.children.head.output.length) && !s.resolved =>
val newChildren: Seq[LogicalPlan] = buildNewChildrenWithWiderTypes(s.children)
if (newChildren.isEmpty) {
s -> Nil
} else {
val attrMapping = s.children.head.output.zip(newChildren.head.output)
s.copy(children = newChildren) -> attrMapping
}
}
}
/** Build new children with the widest types for each attribute among all the children */
private def buildNewChildrenWithWiderTypes(children: Seq[LogicalPlan]): Seq[LogicalPlan] = {
require(children.forall(_.output.length == children.head.output.length))
// Get a sequence of data types, each of which is the widest type of this specific attribute
// in all the children
val targetTypes: Seq[Option[DataType]] =
getWidestTypes(children, attrIndex = 0, mutable.Queue[Option[DataType]]())
if (targetTypes.exists(_.isDefined)) {
// Add an extra Project if the targetTypes are different from the original types.
children.map(widenTypes(_, targetTypes))
} else {
Nil
}
}
/** Get the widest type for each attribute in all the children */
@tailrec private def getWidestTypes(
children: Seq[LogicalPlan],
attrIndex: Int,
castedTypes: mutable.Queue[Option[DataType]]): Seq[Option[DataType]] = {
// Return the result after the widen data types have been found for all the children
if (attrIndex >= children.head.output.length) return castedTypes.toSeq
// For the attrIndex-th attribute, find the widest type
val widenTypeOpt = findWiderCommonType(children.map(_.output(attrIndex).dataType))
castedTypes.enqueue(widenTypeOpt)
getWidestTypes(children, attrIndex + 1, castedTypes)
}
/** Given a plan, add an extra project on top to widen some columns' data types. */
private def widenTypes(plan: LogicalPlan, targetTypes: Seq[Option[DataType]]): LogicalPlan = {
var changed = false
val casted = plan.output.zip(targetTypes).map {
case (e, Some(dt)) if e.dataType != dt =>
changed = true
Alias(Cast(e, dt, Some(conf.sessionLocalTimeZone)), e.name)()
case (e, _) => e
}
if (changed) {
Project(casted, plan)
} else {
plan
}
}
}
/**
* Handles type coercion for both IN expression with subquery and IN
* expressions without subquery.
* 1. In the first case, find the common type by comparing the left hand side (LHS)
* expression types against corresponding right hand side (RHS) expression derived
* from the subquery expression's plan output. Inject appropriate casts in the
* LHS and RHS side of IN expression.
*
* 2. In the second case, convert the value and in list expressions to the
* common operator type by looking at all the argument types and finding
* the closest one that all the arguments can be cast to. When no common
* operator type is found the original expression will be returned and an
* Analysis Exception will be raised at the type checking phase.
*/
object InConversion extends TypeCoercionRule {
override val transform: PartialFunction[Expression, Expression] = {
// Skip nodes who's children have not been resolved yet.
case e if !e.childrenResolved => e
// Handle type casting required between value expression and subquery output
// in IN subquery.
case i @ InSubquery(lhs, l: ListQuery)
if !i.resolved && lhs.length == l.plan.output.length =>
// LHS is the value expressions of IN subquery.
// RHS is the subquery output.
val rhs = l.plan.output
val commonTypes = lhs.zip(rhs).flatMap { case (l, r) =>
findWiderTypeForTwo(l.dataType, r.dataType)
}
// The number of columns/expressions must match between LHS and RHS of an
// IN subquery expression.
if (commonTypes.length == lhs.length) {
val castedRhs = rhs.zip(commonTypes).map {
case (e, dt) if e.dataType != dt => Alias(Cast(e, dt), e.name)()
case (e, _) => e
}
val newLhs = lhs.zip(commonTypes).map {
case (e, dt) if e.dataType != dt => Cast(e, dt)
case (e, _) => e
}
InSubquery(newLhs, l.withNewPlan(Project(castedRhs, l.plan)))
} else {
i
}
case i @ In(a, b) if b.exists(_.dataType != a.dataType) =>
findWiderCommonType(i.children.map(_.dataType)) match {
case Some(finalDataType) => i.withNewChildren(i.children.map(Cast(_, finalDataType)))
case None => i
}
}
}
/**
* This ensure that the types for various functions are as expected.
*/
object FunctionArgumentConversion extends TypeCoercionRule {
override val transform: PartialFunction[Expression, Expression] = {
// Skip nodes who's children have not been resolved yet.
case e if !e.childrenResolved => e
case a @ CreateArray(children, _) if !haveSameType(children.map(_.dataType)) =>
val types = children.map(_.dataType)
findWiderCommonType(types) match {
case Some(finalDataType) => a.copy(children.map(castIfNotSameType(_, finalDataType)))
case None => a
}
case c @ Concat(children) if children.forall(c => ArrayType.acceptsType(c.dataType)) &&
!haveSameType(c.inputTypesForMerging) =>
val types = children.map(_.dataType)
findWiderCommonType(types) match {
case Some(finalDataType) => Concat(children.map(castIfNotSameType(_, finalDataType)))
case None => c
}
case aj @ ArrayJoin(arr, d, nr) if !ArrayType(StringType).acceptsType(arr.dataType) &&
ArrayType.acceptsType(arr.dataType) =>
val containsNull = arr.dataType.asInstanceOf[ArrayType].containsNull
implicitCast(arr, ArrayType(StringType, containsNull)) match {
case Some(castedArr) => ArrayJoin(castedArr, d, nr)
case None => aj
}
case s @ Sequence(_, _, _, timeZoneId)
if !haveSameType(s.coercibleChildren.map(_.dataType)) =>
val types = s.coercibleChildren.map(_.dataType)
findWiderCommonType(types) match {
case Some(widerDataType) => s.castChildrenTo(widerDataType)
case None => s
}
case m @ MapConcat(children) if children.forall(c => MapType.acceptsType(c.dataType)) &&
!haveSameType(m.inputTypesForMerging) =>
val types = children.map(_.dataType)
findWiderCommonType(types) match {
case Some(finalDataType) => MapConcat(children.map(castIfNotSameType(_, finalDataType)))
case None => m
}
case m @ CreateMap(children, _) if m.keys.length == m.values.length &&
(!haveSameType(m.keys.map(_.dataType)) || !haveSameType(m.values.map(_.dataType))) =>
val keyTypes = m.keys.map(_.dataType)
val newKeys = findWiderCommonType(keyTypes) match {
case Some(finalDataType) => m.keys.map(castIfNotSameType(_, finalDataType))
case None => m.keys
}
val valueTypes = m.values.map(_.dataType)
val newValues = findWiderCommonType(valueTypes) match {
case Some(finalDataType) => m.values.map(castIfNotSameType(_, finalDataType))
case None => m.values
}
m.copy(newKeys.zip(newValues).flatMap { case (k, v) => Seq(k, v) })
// Hive lets you do aggregation of timestamps... for some reason
case Sum(e @ TimestampTypeExpression(), _) => Sum(Cast(e, DoubleType))
case Average(e @ TimestampTypeExpression(), _) => Average(Cast(e, DoubleType))
// Coalesce should return the first non-null value, which could be any column
// from the list. So we need to make sure the return type is deterministic and
// compatible with every child column.
case c @ Coalesce(es) if !haveSameType(c.inputTypesForMerging) =>
val types = es.map(_.dataType)
findWiderCommonType(types) match {
case Some(finalDataType) =>
Coalesce(es.map(castIfNotSameType(_, finalDataType)))
case None =>
c
}
// When finding wider type for `Greatest` and `Least`, we should handle decimal types even if
// we need to truncate, but we should not promote one side to string if the other side is
// string.g
case g @ Greatest(children) if !haveSameType(g.inputTypesForMerging) =>
val types = children.map(_.dataType)
findWiderTypeWithoutStringPromotion(types) match {
case Some(finalDataType) => Greatest(children.map(castIfNotSameType(_, finalDataType)))
case None => g
}
case l @ Least(children) if !haveSameType(l.inputTypesForMerging) =>
val types = children.map(_.dataType)
findWiderTypeWithoutStringPromotion(types) match {
case Some(finalDataType) => Least(children.map(castIfNotSameType(_, finalDataType)))
case None => l
}
case NaNvl(l, r) if l.dataType == DoubleType && r.dataType == FloatType =>
NaNvl(l, Cast(r, DoubleType))
case NaNvl(l, r) if l.dataType == FloatType && r.dataType == DoubleType =>
NaNvl(Cast(l, DoubleType), r)
case NaNvl(l, r) if r.dataType == NullType => NaNvl(l, Cast(r, l.dataType))
}
}
/**
* Hive only performs integral division with the DIV operator. The arguments to / are always
* converted to fractional types.
*/
object Division extends TypeCoercionRule {
override val transform: PartialFunction[Expression, Expression] = {
// Skip nodes who has not been resolved yet,
// as this is an extra rule which should be applied at last.
case e if !e.childrenResolved => e
// Decimal and Double remain the same
case d: Divide if d.dataType == DoubleType => d
case d: Divide if d.dataType.isInstanceOf[DecimalType] => d
case d @ Divide(left, right, _) if isNumericOrNull(left) && isNumericOrNull(right) =>
d.copy(left = Cast(left, DoubleType), right = Cast(right, DoubleType))
}
private def isNumericOrNull(ex: Expression): Boolean = {
// We need to handle null types in case a query contains null literals.
ex.dataType.isInstanceOf[NumericType] || ex.dataType == NullType
}
}
/**
* The DIV operator always returns long-type value.
* This rule cast the integral inputs to long type, to avoid overflow during calculation.
*/
object IntegralDivision extends TypeCoercionRule {
override val transform: PartialFunction[Expression, Expression] = {
case e if !e.childrenResolved => e
case d @ IntegralDivide(left, right, _) =>
d.copy(left = mayCastToLong(left), right = mayCastToLong(right))
}
private def mayCastToLong(expr: Expression): Expression = expr.dataType match {
case _: ByteType | _: ShortType | _: IntegerType => Cast(expr, LongType)
case _ => expr
}
}
/**
* Coerces the type of different branches of a CASE WHEN statement to a common type.
*/
object CaseWhenCoercion extends TypeCoercionRule {
override val transform: PartialFunction[Expression, Expression] = {
case c: CaseWhen if c.childrenResolved && !haveSameType(c.inputTypesForMerging) =>
val maybeCommonType = findWiderCommonType(c.inputTypesForMerging)
maybeCommonType.map { commonType =>
val newBranches = c.branches.map { case (condition, value) =>
(condition, castIfNotSameType(value, commonType))
}
val newElseValue = c.elseValue.map(castIfNotSameType(_, commonType))
CaseWhen(newBranches, newElseValue)
}.getOrElse(c)
}
}
/**
* Coerces the type of different branches of If statement to a common type.
*/
object IfCoercion extends TypeCoercionRule {
override val transform: PartialFunction[Expression, Expression] = {
case e if !e.childrenResolved => e
// Find tightest common type for If, if the true value and false value have different types.
case i @ If(pred, left, right) if !haveSameType(i.inputTypesForMerging) =>
findWiderTypeForTwo(left.dataType, right.dataType).map { widestType =>
val newLeft = castIfNotSameType(left, widestType)
val newRight = castIfNotSameType(right, widestType)
If(pred, newLeft, newRight)
}.getOrElse(i) // If there is no applicable conversion, leave expression unchanged.
case If(Literal(null, NullType), left, right) =>
If(Literal.create(null, BooleanType), left, right)
case If(pred, left, right) if pred.dataType == NullType =>
If(Cast(pred, BooleanType), left, right)
}
}
/**
* Coerces NullTypes in the Stack expression to the column types of the corresponding positions.
*/
object StackCoercion extends TypeCoercionRule {
override val transform: PartialFunction[Expression, Expression] = {
case s @ Stack(children) if s.childrenResolved && s.hasFoldableNumRows =>
Stack(children.zipWithIndex.map {
// The first child is the number of rows for stack.
case (e, 0) => e
case (Literal(null, NullType), index: Int) =>
Literal.create(null, s.findDataType(index))
case (e, _) => e
})
}
}
/**
* Coerces the types of [[Concat]] children to expected ones.
*
* If `spark.sql.function.concatBinaryAsString` is false and all children types are binary,
* the expected types are binary. Otherwise, the expected ones are strings.
*/
object ConcatCoercion extends TypeCoercionRule {
override val transform: PartialFunction[Expression, Expression] = {
// Skip nodes if unresolved or empty children
case c @ Concat(children) if !c.childrenResolved || children.isEmpty => c
case c @ Concat(children) if conf.concatBinaryAsString ||
!children.map(_.dataType).forall(_ == BinaryType) =>
val newChildren = c.children.map { e =>
implicitCast(e, SQLConf.get.defaultStringType).getOrElse(e)
}
c.copy(children = newChildren)
}
}
/**
* Coerces key types of two different [[MapType]] arguments of the [[MapZipWith]] expression
* to a common type.
*/
object MapZipWithCoercion extends TypeCoercionRule {
override val transform: PartialFunction[Expression, Expression] = {
// Lambda function isn't resolved when the rule is executed.
case m @ MapZipWith(left, right, function) if m.arguments.forall(a => a.resolved &&
MapType.acceptsType(a.dataType)) &&
!DataTypeUtils.sameType(m.leftKeyType, m.rightKeyType) =>
findWiderTypeForTwo(m.leftKeyType, m.rightKeyType) match {
case Some(finalKeyType) if !Cast.forceNullable(m.leftKeyType, finalKeyType) &&
!Cast.forceNullable(m.rightKeyType, finalKeyType) =>
val newLeft = castIfNotSameType(
left,
MapType(finalKeyType, m.leftValueType, m.leftValueContainsNull))
val newRight = castIfNotSameType(
right,
MapType(finalKeyType, m.rightValueType, m.rightValueContainsNull))
MapZipWith(newLeft, newRight, function)
case _ => m
}
}
}
/**
* Coerces the types of [[Elt]] children to expected ones.
*
* If `spark.sql.function.eltOutputAsString` is false and all children types are binary,
* the expected types are binary. Otherwise, the expected ones are strings.
*/
object EltCoercion extends TypeCoercionRule {
override val transform: PartialFunction[Expression, Expression] = {
// Skip nodes if unresolved or not enough children
case c @ Elt(children, _) if !c.childrenResolved || children.size < 2 => c
case c @ Elt(children, _) =>
val index = children.head
val newIndex = implicitCast(index, IntegerType).getOrElse(index)
val newInputs = if (conf.eltOutputAsString ||
!children.tail.map(_.dataType).forall(_ == BinaryType)) {
children.tail.map { e =>
implicitCast(e, SQLConf.get.defaultStringType).getOrElse(e)
}
} else {
children.tail
}
c.copy(children = newIndex +: newInputs)
}
}
/**
* Casts types according to the expected input types for [[Expression]]s.
*/
object ImplicitTypeCasts extends TypeCoercionRule {
private def canHandleTypeCoercion(leftType: DataType, rightType: DataType): Boolean = {
(leftType, rightType) match {
case (_: DecimalType, NullType) => true
case (NullType, _: DecimalType) => true
case _ =>
// If DecimalType operands are involved except for the two cases above,
// DecimalPrecision will handle it.
!leftType.isInstanceOf[DecimalType] && !rightType.isInstanceOf[DecimalType] &&
leftType != rightType
}
}
override val transform: PartialFunction[Expression, Expression] = {
// Skip nodes who's children have not been resolved yet.
case e if !e.childrenResolved => e
case b @ BinaryOperator(left, right)
if canHandleTypeCoercion(left.dataType, right.dataType) =>
findTightestCommonType(left.dataType, right.dataType).map { commonType =>
if (b.inputType.acceptsType(commonType)) {
// If the expression accepts the tightest common type, cast to that.
val newLeft = if (left.dataType == commonType) left else Cast(left, commonType)
val newRight = if (right.dataType == commonType) right else Cast(right, commonType)
b.withNewChildren(Seq(newLeft, newRight))
} else {
// Otherwise, don't do anything with the expression.
b
}
}.getOrElse(b) // If there is no applicable conversion, leave expression unchanged.
case e: ImplicitCastInputTypes if e.inputTypes.nonEmpty =>
val children: Seq[Expression] = e.children.zip(e.inputTypes).map { case (in, expected) =>
// If we cannot do the implicit cast, just use the original input.
implicitCast(in, expected).getOrElse(in)
}
e.withNewChildren(children)
case e: ExpectsInputTypes if e.inputTypes.nonEmpty =>
// Convert NullType into some specific target type for ExpectsInputTypes that don't do
// general implicit casting.
val children: Seq[Expression] = e.children.zip(e.inputTypes).map { case (in, expected) =>
if (in.dataType == NullType && !expected.acceptsType(NullType)) {
Literal.create(null, expected.defaultConcreteType)
} else {
in
}
}
e.withNewChildren(children)
case udf: ScalaUDF if udf.inputTypes.nonEmpty =>
val children = udf.children.zip(udf.inputTypes).map { case (in, expected) =>
// Currently Scala UDF will only expect `AnyDataType` at top level, so this trick works.
// In the future we should create types like `AbstractArrayType`, so that Scala UDF can
// accept inputs of array type of arbitrary element type.
if (expected == AnyDataType) {
in
} else {
implicitCast(
in,
udfInputToCastType(in.dataType, expected.asInstanceOf[DataType])
).getOrElse(in)
}
}
udf.copy(children = children)
}
private def udfInputToCastType(input: DataType, expectedType: DataType): DataType = {
(input, expectedType) match {
// SPARK-26308: avoid casting to an arbitrary precision and scale for decimals. Please note
// that precision and scale cannot be inferred properly for a ScalaUDF because, when it is
// created, it is not bound to any column. So here the precision and scale of the input
// column is used.
case (in: DecimalType, _: DecimalType) => in
case (ArrayType(dtIn, _), ArrayType(dtExp, nullableExp)) =>
ArrayType(udfInputToCastType(dtIn, dtExp), nullableExp)
case (MapType(keyDtIn, valueDtIn, _), MapType(keyDtExp, valueDtExp, nullableExp)) =>
MapType(udfInputToCastType(keyDtIn, keyDtExp),
udfInputToCastType(valueDtIn, valueDtExp),
nullableExp)
case (StructType(fieldsIn), StructType(fieldsExp)) =>
val fieldTypes =
fieldsIn.map(_.dataType).zip(fieldsExp.map(_.dataType)).map { case (dtIn, dtExp) =>
udfInputToCastType(dtIn, dtExp)
}
StructType(fieldsExp.zip(fieldTypes).map { case (field, newDt) =>
field.copy(dataType = newDt)
})
case (_, other) => other
}
}
}
/**
* Cast WindowFrame boundaries to the type they operate upon.
*/
object WindowFrameCoercion extends TypeCoercionRule {
override val transform: PartialFunction[Expression, Expression] = {
case s @ WindowSpecDefinition(_, Seq(order), SpecifiedWindowFrame(RangeFrame, lower, upper))
if order.resolved =>
s.copy(frameSpecification = SpecifiedWindowFrame(
RangeFrame,
createBoundaryCast(lower, order.dataType),
createBoundaryCast(upper, order.dataType)))
}
private def createBoundaryCast(boundary: Expression, dt: DataType): Expression = {
(boundary, dt) match {
case (e: SpecialFrameBoundary, _) => e
case (e, _: DateType) => e
case (e, _: TimestampType) => e
case (e: Expression, t) if e.dataType != t && canCast(e.dataType, t) =>
Cast(e, t)
case _ => boundary
}
}
}
/**
* A special rule to support string literal as the second argument of date_add/date_sub functions,
* to keep backward compatibility as a temporary workaround.
* TODO(SPARK-28589): implement ANSI type type coercion and handle string literals.
*/
object StringLiteralCoercion extends TypeCoercionRule {
override val transform: PartialFunction[Expression, Expression] = {
// Skip nodes who's children have not been resolved yet.
case e if !e.childrenResolved => e
case DateAdd(l, r) if r.dataType.isInstanceOf[StringType] && r.foldable =>
val days = try {
Cast(r, IntegerType, ansiEnabled = true).eval().asInstanceOf[Int]
} catch {
case e: NumberFormatException =>
throw QueryCompilationErrors.secondArgumentOfFunctionIsNotIntegerError("date_add", e)
}
DateAdd(l, Literal(days))
case DateSub(l, r) if r.dataType.isInstanceOf[StringType] && r.foldable =>
val days = try {
Cast(r, IntegerType, ansiEnabled = true).eval().asInstanceOf[Int]
} catch {
case e: NumberFormatException =>
throw QueryCompilationErrors.secondArgumentOfFunctionIsNotIntegerError("date_sub", e)
}
DateSub(l, Literal(days))
}
}
}
/**
* A collection of [[Rule]] that can be used to coerce differing types that participate in
* operations into compatible ones.
*
* Notes about type widening / tightest common types: Broadly, there are two cases when we need
* to widen data types (e.g. union, binary comparison). In case 1, we are looking for a common
* data type for two or more data types, and in this case no loss of precision is allowed. Examples
* include type inference in JSON (e.g. what's the column's data type if one row is an integer
* while the other row is a long?). In case 2, we are looking for a widened data type with
* some acceptable loss of precision (e.g. there is no common type for double and decimal because
* double's range is larger than decimal, and yet decimal is more precise than double, but in
* union we would cast the decimal into double).
*/
object TypeCoercion extends TypeCoercionBase {
override def typeCoercionRules: List[Rule[LogicalPlan]] =
UnpivotCoercion ::
WidenSetOperationTypes ::
new CombinedTypeCoercionRule(
CollationTypeCasts ::
InConversion ::
PromoteStrings ::
DecimalPrecision ::
BooleanEquality ::
FunctionArgumentConversion ::
ConcatCoercion ::
MapZipWithCoercion ::
EltCoercion ::
CaseWhenCoercion ::
IfCoercion ::
StackCoercion ::
Division ::
IntegralDivision ::
ImplicitTypeCasts ::
DateTimeOperations ::
WindowFrameCoercion ::
StringLiteralCoercion :: Nil) :: Nil
override def canCast(from: DataType, to: DataType): Boolean = Cast.canCast(from, to)
override val findTightestCommonType: (DataType, DataType) => Option[DataType] = {
case (t1, t2) if t1 == t2 => Some(t1)
case (NullType, t1) => Some(t1)
case (t1, NullType) => Some(t1)
case (t1: IntegralType, t2: DecimalType) if t2.isWiderThan(t1) =>
Some(t2)
case (t1: DecimalType, t2: IntegralType) if t1.isWiderThan(t2) =>
Some(t1)
// Promote numeric types to the highest of the two
case (t1: NumericType, t2: NumericType)
if !t1.isInstanceOf[DecimalType] && !t2.isInstanceOf[DecimalType] =>
val index = numericPrecedence.lastIndexWhere(t => t == t1 || t == t2)
Some(numericPrecedence(index))
case (d1: DatetimeType, d2: DatetimeType) => Some(findWiderDateTimeType(d1, d2))
case (t1: DayTimeIntervalType, t2: DayTimeIntervalType) =>
Some(DayTimeIntervalType(t1.startField.min(t2.startField), t1.endField.max(t2.endField)))
case (t1: YearMonthIntervalType, t2: YearMonthIntervalType) =>
Some(YearMonthIntervalType(t1.startField.min(t2.startField), t1.endField.max(t2.endField)))
case (t1, t2) => findTypeForComplex(t1, t2, findTightestCommonType)
}
/** Promotes all the way to StringType. */
private def stringPromotion(dt1: DataType, dt2: DataType): Option[DataType] = (dt1, dt2) match {
case (st: StringType, t2: AtomicType) if t2 != BinaryType && t2 != BooleanType => Some(st)
case (t1: AtomicType, st: StringType) if t1 != BinaryType && t1 != BooleanType => Some(st)
case _ => None
}
// Return whether a string literal can be promoted as the give data type in a binary comparison.
private def canPromoteAsInBinaryComparison(dt: DataType) = dt match {
// If a binary comparison contains interval type and string type, we can't decide which
// interval type the string should be promoted as. There are many possible interval
// types, such as year interval, month interval, day interval, hour interval, etc.
case _: YearMonthIntervalType | _: DayTimeIntervalType => false
// There is no need to add `Cast` for comparison between strings.
case _: StringType => false
case _: AtomicType => true
case _ => false
}
/**
* This function determines the target type of a comparison operator when one operand
* is a String and the other is not. It also handles when one op is a Date and the
* other is a Timestamp by making the target type to be String.
*/
def findCommonTypeForBinaryComparison(
dt1: DataType, dt2: DataType, conf: SQLConf): Option[DataType] = (dt1, dt2) match {
case (st: StringType, DateType)
=> if (conf.castDatetimeToString) Some(st) else Some(DateType)
case (DateType, st: StringType)
=> if (conf.castDatetimeToString) Some(st) else Some(DateType)
case (st: StringType, TimestampType)
=> if (conf.castDatetimeToString) Some(st) else Some(TimestampType)
case (TimestampType, st: StringType)
=> if (conf.castDatetimeToString) Some(st) else Some(TimestampType)
case (st: StringType, NullType) => Some(st)
case (NullType, st: StringType) => Some(st)
// Cast to TimestampType when we compare DateType with TimestampType
// i.e. TimeStamp('2017-03-01 00:00:00') eq Date('2017-03-01') = true
case (TimestampType, DateType) => Some(TimestampType)
case (DateType, TimestampType) => Some(TimestampType)
// There is no proper decimal type we can pick,
// using double type is the best we can do.
// See SPARK-22469 for details.
case (DecimalType.Fixed(_, s), _: StringType) if s > 0 => Some(DoubleType)
case (_: StringType, DecimalType.Fixed(_, s)) if s > 0 => Some(DoubleType)
case (l: StringType, r: AtomicType) if canPromoteAsInBinaryComparison(r) => Some(r)
case (l: AtomicType, r: StringType) if canPromoteAsInBinaryComparison(l) => Some(l)
case (l, r) => None
}
override def findWiderTypeForTwo(t1: DataType, t2: DataType): Option[DataType] = {
findTightestCommonType(t1, t2)
.orElse(findWiderTypeForDecimal(t1, t2))
.orElse(stringPromotion(t1, t2))
.orElse(findTypeForComplex(t1, t2, findWiderTypeForTwo))
}
override def findWiderCommonType(types: Seq[DataType]): Option[DataType] = {
// findWiderTypeForTwo doesn't satisfy the associative law, i.e. (a op b) op c may not equal
// to a op (b op c). This is only a problem for StringType or nested StringType in ArrayType.
// Excluding these types, findWiderTypeForTwo satisfies the associative law. For instance,
// (TimestampType, IntegerType, StringType) should have StringType as the wider common type.
val (stringTypes, nonStringTypes) = types.partition(hasStringType(_))
(stringTypes.distinct ++ nonStringTypes).foldLeft[Option[DataType]](Some(NullType))((r, c) =>
r match {
case Some(d) => findWiderTypeForTwo(d, c)
case _ => None
})
}
override def implicitCast(e: Expression, expectedType: AbstractDataType): Option[Expression] = {
implicitCast(e.dataType, expectedType).map { dt =>
if (dt == e.dataType) e else Cast(e, dt)
}
}
private def implicitCast(inType: DataType, expectedType: AbstractDataType): Option[DataType] = {
// Note that ret is nullable to avoid typing a lot of Some(...) in this local scope.
// We wrap immediately an Option after this.
@Nullable val ret: DataType = (inType, expectedType) match {
// If the expected type is already a parent of the input type, no need to cast.
case _ if expectedType.acceptsType(inType) => inType
// Cast null type (usually from null literals) into target types
case (NullType, target) => target.defaultConcreteType
// If the function accepts any numeric type and the input is a string, we follow the hive
// convention and cast that input into a double
case (_: StringType, NumericType) => NumericType.defaultConcreteType
// Implicit cast among numeric types. When we reach here, input type is not acceptable.
// If input is a numeric type but not decimal, and we expect a decimal type,
// cast the input to decimal.
case (d: NumericType, DecimalType) => DecimalType.forType(d)
// For any other numeric types, implicitly cast to each other, e.g. long -> int, int -> long
case (_: NumericType, target: NumericType) => target
// Implicit cast between date time types
case (_: DatetimeType, d: DatetimeType) => d
case (_: DatetimeType, AnyTimestampType) => AnyTimestampType.defaultConcreteType
// Implicit cast from/to string
case (_: StringType, DecimalType) => DecimalType.SYSTEM_DEFAULT
case (_: StringType, target: NumericType) => target
case (_: StringType, datetime: DatetimeType) => datetime
case (_: StringType, AnyTimestampType) => AnyTimestampType.defaultConcreteType
case (_: StringType, BinaryType) => BinaryType
// Cast any atomic type to string.
case (any: AtomicType, _: StringType) if !any.isInstanceOf[StringType] => StringType
case (any: AtomicType, st: StringTypeCollated)