forked from apache/datafusion-comet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCometCastSuite.scala
More file actions
2159 lines (1906 loc) · 71.7 KB
/
CometCastSuite.scala
File metadata and controls
2159 lines (1906 loc) · 71.7 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
/*
* 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.comet
import java.io.File
import scala.collection.mutable.ListBuffer
import scala.util.Random
import org.apache.hadoop.fs.Path
import org.apache.spark.sql.{CometTestBase, DataFrame, Row, SaveMode}
import org.apache.spark.sql.catalyst.expressions.Cast
import org.apache.spark.sql.catalyst.parser.ParseException
import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper
import org.apache.spark.sql.functions.{col, monotonically_increasing_id}
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types.{ArrayType, BinaryType, BooleanType, ByteType, DataType, DataTypes, DateType, DecimalType, DoubleType, FloatType, IntegerType, LongType, ShortType, StringType, StructField, StructType, TimestampType}
import org.apache.comet.expressions.{CometCast, CometEvalMode}
import org.apache.comet.rules.CometScanTypeChecker
import org.apache.comet.serde.{Compatible, Incompatible}
class CometCastSuite extends CometTestBase with AdaptiveSparkPlanHelper {
import testImplicits._
/** Create a data generator using a fixed seed so that tests are reproducible */
private val gen = DataGenerator.DEFAULT
/** Number of random data items to generate in each test */
private val dataSize = 10000
// we should eventually add more whitespace chars here as documented in
// https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#isWhitespace-char-
// but this is likely a reasonable starting point for now
private val whitespaceChars = " \t\r\n"
/**
* We use these characters to construct strings that potentially represent valid numbers such as
* `-12.34d` or `4e7`. Invalid numeric strings will also be generated, such as `+e.-d`.
*/
private val numericPattern = "0123456789deEf+-." + whitespaceChars
private val datePattern = "0123456789/" + whitespaceChars
private val timestampPattern = "0123456789/:T" + whitespaceChars
lazy val usingParquetExecWithIncompatTypes: Boolean =
hasUnsignedSmallIntSafetyCheck(conf)
// Timezone list to check temporal type casts
private val representativeTimezones = Seq(
// UTC
"UTC",
// North America
"America/New_York",
"America/Chicago",
"America/Denver",
"America/Los_Angeles",
"America/Sao_Paulo", // South America, UTC-3 (no DST in winter)
// Europe
"Europe/London",
"Europe/Paris",
"Europe/Berlin",
// Africa
"Africa/Cairo", // UTC+2, no DST
"Africa/Johannesburg", // UTC+2, no DST
// Middle East
"Asia/Dubai", // UTC+4, no DST
// Asia/Tehran omitted: IANA tzdata for 1977-1979 Iran has been revised multiple times
// (UTC+4 vs UTC+3:30 as standard for parts of that period), causing JDK and chrono-tz
// to disagree on historical dates. Use Asia/Dubai for UTC+4 coverage.
// Asia
"Asia/Tokyo",
"Asia/Shanghai",
// Asia/Singapore omitted: changed UTC+7:30 -> UTC+8 in 1982; test dates go back to 1970
// and JDK tzdata versions may disagree with chrono-tz on the historical offset.
"Asia/Kolkata", // UTC+5:30 (half-hour offset)
"Asia/Kathmandu", // UTC+5:45 (quarter-hour offset)
// Oceania
"Australia/Sydney",
"Pacific/Auckland",
"Pacific/Chatham" // UTC+12:45 (quarter-hour offset)
)
test("all valid cast combinations covered") {
val names = testNames
def assertTestsExist(fromTypes: Seq[DataType], toTypes: Seq[DataType]): Unit = {
for (fromType <- fromTypes) {
for (toType <- toTypes) {
val expectedTestName = s"cast $fromType to $toType"
val testExists = names.contains(expectedTestName)
if (Cast.canCast(fromType, toType)) {
if (fromType == toType) {
if (testExists) {
fail(s"Found redundant test for no-op cast: $expectedTestName")
}
} else if (!testExists) {
fail(s"Missing test: $expectedTestName")
} else {
val testIgnored =
tags.get(expectedTestName).exists(s => s.contains("org.scalatest.Ignore"))
CometCast.isSupported(fromType, toType, None, CometEvalMode.LEGACY) match {
case Compatible(_) =>
if (testIgnored) {
fail(
s"Cast from $fromType to $toType is reported as compatible " +
"with Spark but the test is ignored")
}
case _ =>
if (!testIgnored) {
fail(
s"We claim that cast from $fromType to $toType is not compatible " +
"with Spark but the test is not ignored")
}
}
}
} else if (testExists) {
fail(s"Found test for cast that Spark does not support: $expectedTestName")
}
}
}
}
assertTestsExist(CometCast.supportedTypes, CometCast.supportedTypes)
}
// CAST from BooleanType
test("cast BooleanType to ByteType") {
castTest(generateBools(), DataTypes.ByteType)
}
test("cast BooleanType to ShortType") {
castTest(generateBools(), DataTypes.ShortType)
}
test("cast BooleanType to IntegerType") {
castTest(generateBools(), DataTypes.IntegerType)
}
test("cast BooleanType to LongType") {
castTest(generateBools(), DataTypes.LongType)
}
test("cast BooleanType to FloatType") {
castTest(generateBools(), DataTypes.FloatType)
}
test("cast BooleanType to DoubleType") {
castTest(generateBools(), DataTypes.DoubleType)
}
test("cast BooleanType to DecimalType(10,2)") {
castTest(generateBools(), DataTypes.createDecimalType(10, 2))
}
test("cast BooleanType to DecimalType(14,4)") {
castTest(generateBools(), DataTypes.createDecimalType(14, 4))
}
test("cast BooleanType to DecimalType(30,0)") {
castTest(generateBools(), DataTypes.createDecimalType(30, 0))
}
test("cast BooleanType to StringType") {
castTest(generateBools(), DataTypes.StringType)
}
test("cast BooleanType to TimestampType") {
// Spark does not support ANSI or Try mode for Boolean to Timestamp casts
castTest(generateBools(), DataTypes.TimestampType, testAnsi = false, testTry = false)
}
// CAST from ByteType
test("cast ByteType to BooleanType") {
castTest(
generateBytes(),
DataTypes.BooleanType,
hasIncompatibleType = usingParquetExecWithIncompatTypes)
}
test("cast ByteType to ShortType") {
castTest(
generateBytes(),
DataTypes.ShortType,
hasIncompatibleType = usingParquetExecWithIncompatTypes)
}
test("cast ByteType to IntegerType") {
castTest(
generateBytes(),
DataTypes.IntegerType,
hasIncompatibleType = usingParquetExecWithIncompatTypes)
}
test("cast ByteType to LongType") {
castTest(
generateBytes(),
DataTypes.LongType,
hasIncompatibleType = usingParquetExecWithIncompatTypes)
}
test("cast ByteType to FloatType") {
castTest(
generateBytes(),
DataTypes.FloatType,
hasIncompatibleType = usingParquetExecWithIncompatTypes)
}
test("cast ByteType to DoubleType") {
castTest(
generateBytes(),
DataTypes.DoubleType,
hasIncompatibleType = usingParquetExecWithIncompatTypes)
}
test("cast ByteType to DecimalType(10,2)") {
castTest(
generateBytes(),
DataTypes.createDecimalType(10, 2),
hasIncompatibleType = usingParquetExecWithIncompatTypes)
}
test("cast ByteType to StringType") {
castTest(
generateBytes(),
DataTypes.StringType,
hasIncompatibleType = usingParquetExecWithIncompatTypes)
}
test("cast ByteType to BinaryType") {
// Spark does not support ANSI or Try mode
castTest(
generateBytes(),
DataTypes.BinaryType,
hasIncompatibleType = usingParquetExecWithIncompatTypes,
testAnsi = false,
testTry = false)
}
test("cast ByteType to TimestampType") {
representativeTimezones.foreach { tz =>
withSQLConf(SQLConf.SESSION_LOCAL_TIMEZONE.key -> tz) {
castTest(
generateBytes(),
DataTypes.TimestampType,
hasIncompatibleType = usingParquetExecWithIncompatTypes)
}
}
}
// CAST from ShortType
test("cast ShortType to BooleanType") {
castTest(
generateShorts(),
DataTypes.BooleanType,
hasIncompatibleType = usingParquetExecWithIncompatTypes)
}
test("cast ShortType to ByteType") {
// https://github.com/apache/datafusion-comet/issues/311
castTest(
generateShorts(),
DataTypes.ByteType,
hasIncompatibleType = usingParquetExecWithIncompatTypes)
}
test("cast ShortType to IntegerType") {
castTest(
generateShorts(),
DataTypes.IntegerType,
hasIncompatibleType = usingParquetExecWithIncompatTypes)
}
test("cast ShortType to LongType") {
castTest(
generateShorts(),
DataTypes.LongType,
hasIncompatibleType = usingParquetExecWithIncompatTypes)
}
test("cast ShortType to FloatType") {
castTest(
generateShorts(),
DataTypes.FloatType,
hasIncompatibleType = usingParquetExecWithIncompatTypes)
}
test("cast ShortType to DoubleType") {
castTest(
generateShorts(),
DataTypes.DoubleType,
hasIncompatibleType = usingParquetExecWithIncompatTypes)
}
test("cast ShortType to DecimalType(10,2)") {
castTest(
generateShorts(),
DataTypes.createDecimalType(10, 2),
hasIncompatibleType = usingParquetExecWithIncompatTypes)
}
test("cast ShortType to StringType") {
castTest(
generateShorts(),
DataTypes.StringType,
hasIncompatibleType = usingParquetExecWithIncompatTypes)
}
test("cast ShortType to BinaryType") {
// Spark does not support ANSI or Try mode
castTest(
generateShorts(),
DataTypes.BinaryType,
hasIncompatibleType = usingParquetExecWithIncompatTypes,
testAnsi = false,
testTry = false)
}
test("cast ShortType to TimestampType") {
representativeTimezones.foreach { tz =>
withSQLConf(SQLConf.SESSION_LOCAL_TIMEZONE.key -> tz) {
castTest(
generateShorts(),
DataTypes.TimestampType,
hasIncompatibleType = usingParquetExecWithIncompatTypes)
}
}
}
// CAST from integer
test("cast IntegerType to BooleanType") {
castTest(generateInts(), DataTypes.BooleanType)
}
test("cast IntegerType to ByteType") {
// https://github.com/apache/datafusion-comet/issues/311
castTest(generateInts(), DataTypes.ByteType)
}
test("cast IntegerType to ShortType") {
// https://github.com/apache/datafusion-comet/issues/311
castTest(generateInts(), DataTypes.ShortType)
}
test("cast IntegerType to LongType") {
castTest(generateInts(), DataTypes.LongType)
}
test("cast IntegerType to FloatType") {
castTest(generateInts(), DataTypes.FloatType)
}
test("cast IntegerType to DoubleType") {
castTest(generateInts(), DataTypes.DoubleType)
}
test("cast IntegerType to DecimalType(10,2)") {
castTest(generateInts(), DataTypes.createDecimalType(10, 2))
}
test("cast IntegerType to DecimalType(10,2) overflow check") {
val intToDecimal10OverflowValues =
Seq(Int.MinValue, -100000000, -100000001, 100000000, 100000001, Int.MaxValue).toDF("a")
castTest(intToDecimal10OverflowValues, DataTypes.createDecimalType(10, 2))
}
test("cast IntegerType to DecimalType check arbitrary scale and precision") {
Seq(DecimalType.MAX_PRECISION, DecimalType.MAX_SCALE, 0, 10, 15)
.combinations(2)
.map({ c =>
castTest(generateInts(), DataTypes.createDecimalType(c.head, c.last))
})
}
test("cast IntegerType to StringType") {
castTest(generateInts(), DataTypes.StringType)
}
test("cast IntegerType to BinaryType") {
// Spark does not support ANSI or Try mode
castTest(generateInts(), DataTypes.BinaryType, testAnsi = false, testTry = false)
}
test("cast IntegerType to TimestampType") {
representativeTimezones.foreach { tz =>
withSQLConf(SQLConf.SESSION_LOCAL_TIMEZONE.key -> tz) {
castTest(generateInts(), DataTypes.TimestampType)
}
}
}
// CAST from LongType
test("cast LongType to BooleanType") {
castTest(generateLongs(), DataTypes.BooleanType)
}
test("cast LongType to ByteType") {
// https://github.com/apache/datafusion-comet/issues/311
castTest(generateLongs(), DataTypes.ByteType)
}
test("cast LongType to ShortType") {
// https://github.com/apache/datafusion-comet/issues/311
castTest(generateLongs(), DataTypes.ShortType)
}
test("cast LongType to IntegerType") {
// https://github.com/apache/datafusion-comet/issues/311
castTest(generateLongs(), DataTypes.IntegerType)
}
test("cast LongType to FloatType") {
castTest(generateLongs(), DataTypes.FloatType)
}
test("cast LongType to DoubleType") {
castTest(generateLongs(), DataTypes.DoubleType)
}
test("cast LongType to DecimalType(10,2)") {
castTest(generateLongs(), DataTypes.createDecimalType(10, 2))
}
test("cast LongType to StringType") {
castTest(generateLongs(), DataTypes.StringType)
}
test("cast LongType to BinaryType") {
// Spark does not support ANSI or Try mode
castTest(generateLongs(), DataTypes.BinaryType, testAnsi = false, testTry = false)
}
test("cast LongType to TimestampType") {
// Cast back to long avoids java.sql.Timestamp overflow during collect() for extreme values
representativeTimezones.foreach { tz =>
withSQLConf(SQLConf.SESSION_LOCAL_TIMEZONE.key -> tz) {
withTable("t1") {
generateLongs().write.saveAsTable("t1")
val df = spark.sql("select a, cast(cast(a as timestamp) as long) from t1")
checkSparkAnswerAndOperator(df)
}
}
}
}
// CAST from FloatType
test("cast FloatType to BooleanType") {
castTest(generateFloats(), DataTypes.BooleanType)
}
test("cast FloatType to ByteType") {
castTest(generateFloats(), DataTypes.ByteType)
}
test("cast FloatType to ShortType") {
castTest(generateFloats(), DataTypes.ShortType)
}
test("cast FloatType to IntegerType") {
castTest(generateFloats(), DataTypes.IntegerType)
}
test("cast FloatType to LongType") {
castTest(generateFloats(), DataTypes.LongType)
}
test("cast FloatType to DoubleType") {
castTest(generateFloats(), DataTypes.DoubleType)
}
ignore("cast FloatType to DecimalType(10,2)") {
// // https://github.com/apache/datafusion-comet/issues/1371
castTest(generateFloats(), DataTypes.createDecimalType(10, 2))
}
test("cast FloatType to DecimalType(10,2) - allow incompat") {
withSQLConf(CometConf.getExprAllowIncompatConfigKey(classOf[Cast]) -> "true") {
castTest(generateFloats(), DataTypes.createDecimalType(10, 2))
}
}
test("cast FloatType to StringType") {
// https://github.com/apache/datafusion-comet/issues/312
val r = new Random(0)
val values = Seq(
Float.MaxValue,
Float.MinValue,
Float.NaN,
Float.PositiveInfinity,
Float.NegativeInfinity,
1.0f,
-1.0f,
Short.MinValue.toFloat,
Short.MaxValue.toFloat,
-0.0f,
0.0f) ++
Range(0, dataSize).map(_ => r.nextFloat())
castTest(withNulls(values).toDF("a"), DataTypes.StringType)
}
test("cast FloatType to TimestampType") {
representativeTimezones.foreach { tz =>
withSQLConf(SQLConf.SESSION_LOCAL_TIMEZONE.key -> tz) {
// Use useDFDiff to avoid collect() which fails on extreme timestamp values
castTest(generateFloats(), DataTypes.TimestampType, useDataFrameDiff = true)
}
}
}
// CAST from DoubleType
test("cast DoubleType to BooleanType") {
castTest(generateDoubles(), DataTypes.BooleanType)
}
test("cast DoubleType to ByteType") {
castTest(generateDoubles(), DataTypes.ByteType)
}
test("cast DoubleType to ShortType") {
castTest(generateDoubles(), DataTypes.ShortType)
}
test("cast DoubleType to IntegerType") {
castTest(generateDoubles(), DataTypes.IntegerType)
}
test("cast DoubleType to LongType") {
castTest(generateDoubles(), DataTypes.LongType)
}
test("cast DoubleType to FloatType") {
castTest(generateDoubles(), DataTypes.FloatType)
}
ignore("cast DoubleType to DecimalType(10,2)") {
// https://github.com/apache/datafusion-comet/issues/1371
castTest(generateDoubles(), DataTypes.createDecimalType(10, 2))
}
test("cast DoubleType to DecimalType(10,2) - allow incompat") {
withSQLConf(CometConf.getExprAllowIncompatConfigKey(classOf[Cast]) -> "true") {
castTest(generateDoubles(), DataTypes.createDecimalType(10, 2))
}
}
test("cast DoubleType to StringType") {
// https://github.com/apache/datafusion-comet/issues/312
val r = new Random(0)
val values = Seq(
Double.MaxValue,
Double.MinValue,
Double.NaN,
Double.PositiveInfinity,
Double.NegativeInfinity,
1.0d,
-1.0d,
Int.MinValue.toDouble,
Int.MaxValue.toDouble,
-0.0d,
0.0d) ++
Range(0, dataSize).map(_ => r.nextDouble())
castTest(withNulls(values).toDF("a"), DataTypes.StringType)
}
test("cast DoubleType to TimestampType") {
representativeTimezones.foreach { tz =>
withSQLConf(SQLConf.SESSION_LOCAL_TIMEZONE.key -> tz) {
// Use useDFDiff to avoid collect() which fails on extreme timestamp values
castTest(generateDoubles(), DataTypes.TimestampType, useDataFrameDiff = true)
}
}
}
// CAST from DecimalType(10,2)
test("cast DecimalType(10,2) to BooleanType") {
castTest(generateDecimalsPrecision10Scale2(), DataTypes.BooleanType)
}
test("cast DecimalType(10,2) to ByteType") {
castTest(generateDecimalsPrecision10Scale2(), DataTypes.ByteType)
}
test("cast DecimalType(10,2) to ShortType") {
castTest(generateDecimalsPrecision10Scale2(), DataTypes.ShortType)
castTest(
generateDecimalsPrecision10Scale2(Seq(BigDecimal("-96833550.07"))),
DataTypes.ShortType)
}
test("cast DecimalType(10,2) to IntegerType") {
castTest(generateDecimalsPrecision10Scale2(), DataTypes.IntegerType)
}
test("cast DecimalType(10,2) to LongType") {
castTest(generateDecimalsPrecision10Scale2(), DataTypes.LongType)
}
test("cast DecimalType(10,2) to FloatType") {
castTest(generateDecimalsPrecision10Scale2(), DataTypes.FloatType)
}
test("cast DecimalType(10,2) to DoubleType") {
castTest(generateDecimalsPrecision10Scale2(), DataTypes.DoubleType)
}
// CAST from DecimalType(15,5): fractional truncation for int/long; int overflow possible
test("cast DecimalType(15,5) to IntegerType") {
castTest(generateDecimalsPrecision15Scale5(), DataTypes.IntegerType)
}
test("cast DecimalType(15,5) to LongType") {
castTest(generateDecimalsPrecision15Scale5(), DataTypes.LongType)
}
test("cast DecimalType(15,5) to BooleanType") {
castTest(generateDecimalsPrecision15Scale5(), DataTypes.BooleanType)
}
// CAST from DecimalType(20,0): large integers with no fractional part; long overflow possible
test("cast DecimalType(20,0) to IntegerType") {
castTest(generateDecimalsPrecision20Scale0(), DataTypes.IntegerType)
}
test("cast DecimalType(20,0) to LongType") {
castTest(generateDecimalsPrecision20Scale0(), DataTypes.LongType)
}
test("cast DecimalType(20,0) to BooleanType") {
castTest(generateDecimalsPrecision20Scale0(), DataTypes.BooleanType)
}
test("cast DecimalType(38,18) to ByteType") {
castTest(generateDecimalsPrecision38Scale18(), DataTypes.ByteType)
}
test("cast DecimalType(38,18) to ShortType") {
castTest(generateDecimalsPrecision38Scale18(), DataTypes.ShortType)
castTest(
generateDecimalsPrecision38Scale18(Seq(BigDecimal("-99999999999999999999.07"))),
DataTypes.ShortType)
}
test("cast DecimalType(38,18) to IntegerType") {
castTest(generateDecimalsPrecision38Scale18(), DataTypes.IntegerType)
castTest(
generateDecimalsPrecision38Scale18(Seq(BigDecimal("-99999999999999999999.07"))),
DataTypes.IntegerType)
}
test("cast DecimalType(38,18) to LongType") {
castTest(generateDecimalsPrecision38Scale18(), DataTypes.LongType)
castTest(
generateDecimalsPrecision38Scale18(Seq(BigDecimal("-99999999999999999999.07"))),
DataTypes.LongType)
}
test("cast DecimalType(38,18) to FloatType") {
castTest(generateDecimalsPrecision38Scale18(), DataTypes.FloatType)
// small fractions exercise the i128 / 10^scale precision path
castTest(
generateDecimalsPrecision38Scale18(
Seq(
BigDecimal("0.000000000000000001"),
BigDecimal("-0.000000000000000001"),
BigDecimal("1.500000000000000000"),
BigDecimal("123456789.123456789"))),
DataTypes.FloatType)
}
test("cast DecimalType(38,18) to DoubleType") {
castTest(generateDecimalsPrecision38Scale18(), DataTypes.DoubleType)
// small fractions exercise the i128 / 10^scale precision path
castTest(
generateDecimalsPrecision38Scale18(
Seq(
BigDecimal("0.000000000000000001"),
BigDecimal("-0.000000000000000001"),
BigDecimal("1.500000000000000000"),
BigDecimal("123456789.123456789"))),
DataTypes.DoubleType)
}
test("cast DecimalType(38,18) to BooleanType") {
castTest(generateDecimalsPrecision38Scale18(), DataTypes.BooleanType)
// tiny non-zero values must be true; only exact zero is false
castTest(
generateDecimalsPrecision38Scale18(
Seq(BigDecimal("0.000000000000000001"), BigDecimal("-0.000000000000000001"))),
DataTypes.BooleanType)
}
test("cast DecimalType(10,2) to StringType") {
castTest(generateDecimalsPrecision10Scale2(), DataTypes.StringType)
}
test("cast DecimalType(38,18) to StringType") {
castTest(generateDecimalsPrecision38Scale18(), DataTypes.StringType)
}
test("cast DecimalType with negative scale to StringType") {
// Negative-scale decimals are a legacy Spark feature gated on
// spark.sql.legacy.allowNegativeScaleOfDecimal=true. Spark LEGACY cast uses Java's
// BigDecimal.toString() which produces scientific notation for negative-scale values
// (e.g. 12300 stored as Decimal(7,-2) with unscaled=123 → "1.23E+4").
// CometCast.canCastToString checks the
// config and returns Incompatible when it is false.
//
// Parquet does not support negative-scale decimals so we use checkSparkAnswer directly
// (no parquet round-trip) to avoid schema coercion.
// With config enabled, enable localTableScan so Comet can take over the full plan
// and execute the cast natively. Parquet does not support negative-scale decimals so
// the data is kept in-memory; localTableScan.enabled bridges that gap.
withSQLConf(
"spark.sql.legacy.allowNegativeScaleOfDecimal" -> "true",
"spark.comet.exec.localTableScan.enabled" -> "true") {
val dfNeg2 = Seq(
Some(BigDecimal("0")),
Some(BigDecimal("100")),
Some(BigDecimal("12300")),
Some(BigDecimal("-99900")),
Some(BigDecimal("9999900")),
None)
.toDF("b")
.withColumn("a", col("b").cast(DecimalType(7, -2)))
.drop("b")
.select(col("a").cast(DataTypes.StringType).as("result"))
checkSparkAnswerAndOperator(dfNeg2)
val dfNeg4 = Seq(
Some(BigDecimal("0")),
Some(BigDecimal("10000")),
Some(BigDecimal("120000")),
Some(BigDecimal("-9990000")),
None)
.toDF("b")
.withColumn("a", col("b").cast(DecimalType(7, -4)))
.drop("b")
.select(col("a").cast(DataTypes.StringType).as("result"))
checkSparkAnswerAndOperator(dfNeg4)
}
// With config disabled (default): the SQL parser rejects negative scale, so
// negative-scale decimals cannot be created through normal SQL paths.
// CometCast.isSupported returns Incompatible for this case, ensuring Comet does
// not attempt native execution if such a value ever reaches the planner.
// Note: DecimalType(7, -2) must be constructed while config=true, because the
// constructor itself checks the config and throws if negative scale is disallowed.
var negScaleType: DecimalType = null
withSQLConf("spark.sql.legacy.allowNegativeScaleOfDecimal" -> "true") {
negScaleType = DecimalType(7, -2)
}
withSQLConf("spark.sql.legacy.allowNegativeScaleOfDecimal" -> "false") {
assert(
CometCast.isSupported(
negScaleType,
DataTypes.StringType,
None,
CometEvalMode.LEGACY) == Incompatible())
}
}
test("cast DecimalType(10,2) to TimestampType") {
castTest(generateDecimalsPrecision10Scale2(), DataTypes.TimestampType)
}
test("cast DecimalType(38,10) to TimestampType") {
castTest(generateDecimalsPrecision38Scale18(), DataTypes.TimestampType)
}
// CAST from StringType
test("cast StringType to BooleanType") {
val testValues =
(Seq("TRUE", "True", "true", "FALSE", "False", "false", "1", "0", "", null) ++
gen.generateStrings(dataSize, "truefalseTRUEFALSEyesno10" + whitespaceChars, 8)).toDF("a")
castTest(testValues, DataTypes.BooleanType)
}
private val castStringToIntegralInputs: Seq[String] = Seq(
"",
".",
"+",
"-",
"+.",
"-.",
"-0",
"+1",
"-1",
".2",
"-.2",
"1e1",
"1.1d",
"1.1f",
Byte.MinValue.toString,
(Byte.MinValue.toShort - 1).toString,
Byte.MaxValue.toString,
(Byte.MaxValue.toShort + 1).toString,
Short.MinValue.toString,
(Short.MinValue.toInt - 1).toString,
Short.MaxValue.toString,
(Short.MaxValue.toInt + 1).toString,
Int.MinValue.toString,
(Int.MinValue.toLong - 1).toString,
Int.MaxValue.toString,
(Int.MaxValue.toLong + 1).toString,
Long.MinValue.toString,
Long.MaxValue.toString,
"-9223372036854775809", // Long.MinValue -1
"9223372036854775808" // Long.MaxValue + 1
)
test("cast StringType to ByteType") {
// test with hand-picked values
castTest(castStringToIntegralInputs.toDF("a"), DataTypes.ByteType)
// fuzz test
castTest(gen.generateStrings(dataSize, numericPattern, 4).toDF("a"), DataTypes.ByteType)
}
test("cast StringType to ShortType") {
// test with hand-picked values
castTest(castStringToIntegralInputs.toDF("a"), DataTypes.ShortType)
// fuzz test
castTest(gen.generateStrings(dataSize, numericPattern, 5).toDF("a"), DataTypes.ShortType)
}
test("cast StringType to IntegerType") {
// test with hand-picked values
castTest(castStringToIntegralInputs.toDF("a"), DataTypes.IntegerType)
// fuzz test
castTest(gen.generateStrings(dataSize, numericPattern, 8).toDF("a"), DataTypes.IntegerType)
}
test("cast StringType to LongType") {
// test with hand-picked values
castTest(castStringToIntegralInputs.toDF("a"), DataTypes.LongType)
// fuzz test
castTest(gen.generateStrings(dataSize, numericPattern, 8).toDF("a"), DataTypes.LongType)
}
test("cast StringType to DoubleType") {
// https://github.com/apache/datafusion-comet/issues/326
castTest(gen.generateStrings(dataSize, numericPattern, 8).toDF("a"), DataTypes.DoubleType)
}
test("cast StringType to FloatType") {
castTest(gen.generateStrings(dataSize, numericPattern, 8).toDF("a"), DataTypes.FloatType)
}
val specialValues: Seq[String] = Seq(
"1.5f",
"1.5F",
"2.0d",
"2.0D",
"3.14159265358979d",
"inf",
"Inf",
"INF",
"+inf",
"+Infinity",
"-inf",
"-Infinity",
"NaN",
"nan",
"NAN",
"1.23e4",
"1.23E4",
"-1.23e-4",
" 123.456789 ",
"0.0",
"-0.0",
"",
"xyz",
null)
test("cast StringType to FloatType special values") {
Seq(true, false).foreach { ansiMode =>
castTest(specialValues.toDF("a"), DataTypes.FloatType, testAnsi = ansiMode)
}
}
test("cast StringType to DoubleType special values") {
Seq(true, false).foreach { ansiMode =>
castTest(specialValues.toDF("a"), DataTypes.DoubleType, testAnsi = ansiMode)
}
}
// This is to pass the first `all cast combinations are covered`
test("cast StringType to DecimalType(10,2)") {
val values = gen.generateStrings(dataSize, numericPattern, 12).toDF("a")
castTest(values, DataTypes.createDecimalType(10, 2), testAnsi = false)
}
test("cast StringType to DecimalType(10,2) fuzz") {
val values = gen.generateStrings(dataSize, numericPattern, 12).toDF("a")
Seq(true, false).foreach(ansiEnabled =>
castTest(values, DataTypes.createDecimalType(10, 2), testAnsi = ansiEnabled))
}
test("cast StringType to DecimalType(2,2)") {
val values = gen.generateStrings(dataSize, numericPattern, 12).toDF("a")
Seq(true, false).foreach(ansiEnabled =>
castTest(values, DataTypes.createDecimalType(2, 2), testAnsi = ansiEnabled))
}
test("cast StringType to DecimalType check if right exception message is thrown") {
val values = Seq("d11307\n").toDF("a")
Seq(true, false).foreach(ansiEnabled =>
castTest(values, DataTypes.createDecimalType(2, 2), testAnsi = ansiEnabled))
}
test("cast StringType to DecimalType(2,2) check if right exception is being thrown") {
val values = gen.generateInts(10000).map(" " + _).toDF("a")
Seq(true, false).foreach(ansiEnabled =>
castTest(values, DataTypes.createDecimalType(2, 2), testAnsi = ansiEnabled))
}
test("cast StringType to DecimalType(38,10) high precision - check 0 mantissa") {
val values = Seq("0e31", "000e3375", "0e40", "0E+695", "0e5887677").toDF("a")
Seq(true, false).foreach(ansiEnabled =>
castTest(values, DataTypes.createDecimalType(38, 10), testAnsi = ansiEnabled))
}
test("cast StringType to DecimalType(38,10) high precision") {
val values = gen.generateStrings(dataSize, numericPattern, 38).toDF("a")
Seq(true, false).foreach(ansiEnabled =>
castTest(values, DataTypes.createDecimalType(38, 10), testAnsi = ansiEnabled))
}
test("cast StringType to DecimalType - null bytes and fullwidth digits") {
// Spark trims null bytes (\u0000) from both ends of a string before parsing,
// matching its whitespace-trim behavior. Null bytes in the middle produce NULL.
// Fullwidth digits (U+FF10-U+FF19) are treated as numeric equivalents to ASCII digits.
val values = Seq(
// null byte positions
"123\u0000",
"\u0000123",
"12\u00003",
"1\u00002\u00003",
"\u0000",
// null byte with decimal point
"12\u0000.45",
"12.\u000045",
// fullwidth digits (U+FF10-U+FF19)
"123.45", // "123.45" in fullwidth
"123",
"-123.45",
"+123.45",
"123.45E2",
// mixed fullwidth and ASCII
"123.45",
null).toDF("a")
castTest(values, DataTypes.createDecimalType(10, 2))
}
test("cast StringType to DecimalType(10,2) basic values") {
val values = Seq(
"123.45",
"-67.89",
"-67.89",
"-67.895",
"67.895",
"0.001",
"999.99",
"123.456",
"123.45D",
".5",
"5.",
"+123.45",
" 123.45 ",
"inf",