forked from apache/datafusion-comet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCometExpressionSuite.scala
More file actions
3066 lines (2797 loc) · 117 KB
/
CometExpressionSuite.scala
File metadata and controls
3066 lines (2797 loc) · 117 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.time.{Duration, Period}
import scala.util.Random
import org.scalactic.source.Position
import org.scalatest.Tag
import org.apache.hadoop.fs.Path
import org.apache.spark.sql.{CometTestBase, DataFrame, Row}
import org.apache.spark.sql.catalyst.expressions.{Alias, Cast, FromUnixTime, Literal, StructsToJson, TruncDate, TruncTimestamp}
import org.apache.spark.sql.catalyst.optimizer.SimplifyExtractValueOps
import org.apache.spark.sql.comet.CometProjectExec
import org.apache.spark.sql.execution.{ProjectExec, SparkPlan}
import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper
import org.apache.spark.sql.functions._
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.internal.SQLConf.SESSION_LOCAL_TIMEZONE
import org.apache.spark.sql.types._
import org.apache.comet.CometSparkSessionExtensions.isSpark40Plus
import org.apache.comet.testing.{DataGenOptions, FuzzDataGenerator}
class CometExpressionSuite extends CometTestBase with AdaptiveSparkPlanHelper {
import testImplicits._
override protected def test(testName: String, testTags: Tag*)(testFun: => Any)(implicit
pos: Position): Unit = {
super.test(testName, testTags: _*) {
withSQLConf(CometConf.COMET_NATIVE_SCAN_IMPL.key -> CometConf.SCAN_AUTO) {
testFun
}
}
}
val ARITHMETIC_OVERFLOW_EXCEPTION_MSG =
"""[ARITHMETIC_OVERFLOW] integer overflow. If necessary set "spark.sql.ansi.enabled" to "false" to bypass this error"""
val DIVIDE_BY_ZERO_EXCEPTION_MSG =
"""Division by zero. Use `try_divide` to tolerate divisor being 0 and return NULL instead"""
// Temporary test to verify checkSparkAnswer failure output labels Comet/Spark correctly.
ignore("check output labels on mismatch") {
val cometDf = Seq((1, "apple"), (2, "banana"), (3, "cherry")).toDF("id", "fruit")
val sparkAnswer = Seq(Row(1, "apple"), Row(2, "BANANA"), Row(3, "cherry"))
checkCometAnswer(cometDf, sparkAnswer)
}
test("sort floating point with negative zero") {
val schema = StructType(
Seq(
StructField("c0", DataTypes.FloatType, true),
StructField("c1", DataTypes.DoubleType, true)))
val df = FuzzDataGenerator.generateDataFrame(
new Random(42),
spark,
schema,
1000,
DataGenOptions(generateNegativeZero = true))
df.createOrReplaceTempView("tbl")
withSQLConf(
CometConf.getExprAllowIncompatConfigKey("SortOrder") -> "false",
CometConf.COMET_EXEC_STRICT_FLOATING_POINT.key -> "true") {
checkSparkAnswerAndFallbackReasons(
"select * from tbl order by 1, 2",
Set(
"unsupported range partitioning sort order",
"Sorting on floating-point is not 100% compatible with Spark"))
}
}
test("sort array of floating point with negative zero") {
val schema = StructType(
Seq(
StructField("c0", DataTypes.createArrayType(DataTypes.FloatType), true),
StructField("c1", DataTypes.createArrayType(DataTypes.DoubleType), true)))
val df = FuzzDataGenerator.generateDataFrame(
new Random(42),
spark,
schema,
1000,
DataGenOptions(generateNegativeZero = true))
df.createOrReplaceTempView("tbl")
withSQLConf(
CometConf.getExprAllowIncompatConfigKey("SortOrder") -> "false",
CometConf.COMET_EXEC_STRICT_FLOATING_POINT.key -> "true") {
checkSparkAnswerAndFallbackReason(
"select * from tbl order by 1, 2",
"unsupported range partitioning sort order")
}
}
test("sort struct containing floating point with negative zero") {
val schema = StructType(
Seq(
StructField(
"float_struct",
StructType(Seq(StructField("c0", DataTypes.FloatType, true)))),
StructField(
"float_double",
StructType(Seq(StructField("c0", DataTypes.DoubleType, true))))))
val df = FuzzDataGenerator.generateDataFrame(
new Random(42),
spark,
schema,
1000,
DataGenOptions(generateNegativeZero = true))
df.createOrReplaceTempView("tbl")
withSQLConf(
CometConf.getExprAllowIncompatConfigKey("SortOrder") -> "false",
CometConf.COMET_EXEC_STRICT_FLOATING_POINT.key -> "true") {
checkSparkAnswerAndFallbackReason(
"select * from tbl order by 1, 2",
"unsupported range partitioning sort order")
}
}
test("compare true/false to negative zero") {
Seq(false, true).foreach { dictionary =>
withSQLConf("parquet.enable.dictionary" -> dictionary.toString) {
val table = "test"
withTable(table) {
sql(s"create table $table(col1 boolean, col2 float) using parquet")
sql(s"insert into $table values(true, -0.0)")
sql(s"insert into $table values(false, -0.0)")
checkSparkAnswerAndOperator(
s"SELECT col1, negative(col2), cast(col1 as float), col1 = negative(col2) FROM $table")
}
}
}
}
test("parquet default values") {
withTable("t1") {
sql("create table t1(col1 boolean) using parquet")
sql("insert into t1 values(true)")
sql("alter table t1 add column col2 string default 'hello'")
checkSparkAnswerAndOperator("select * from t1")
}
}
test("decimals divide by zero") {
Seq(true, false).foreach { dictionary =>
withSQLConf(
SQLConf.PARQUET_WRITE_LEGACY_FORMAT.key -> "false",
"parquet.enable.dictionary" -> dictionary.toString) {
withTempPath { dir =>
val data = makeDecimalRDD(10, DecimalType(18, 10), dictionary)
data.write.parquet(dir.getCanonicalPath)
readParquetFile(dir.getCanonicalPath) { df =>
{
val decimalLiteral = Decimal(0.00)
val cometDf = df.select($"dec" / decimalLiteral, $"dec" % decimalLiteral)
checkSparkSchema(cometDf)
checkSparkAnswerAndOperator(cometDf)
}
}
}
}
}
}
test("Integral Division Overflow Handling Matches Spark Behavior") {
withTable("t1") {
val value = Long.MinValue
sql("create table t1(c1 long, c2 short) using parquet")
sql(s"insert into t1 values($value, -1)")
val res = sql("select c1 div c2 from t1 order by c1")
checkSparkAnswerAndOperator(res)
}
}
test("basic data type support - excluding u8/u16") {
// variant that skips _9 (UINT_8) and _10 (UINT_16) for default scan impl
Seq(true, false).foreach { dictionaryEnabled =>
withTempDir { dir =>
val path = new Path(dir.toURI.toString, "test.parquet")
makeParquetFileAllPrimitiveTypes(path, dictionaryEnabled = dictionaryEnabled, 10000)
withParquetTable(path.toString, "tbl") {
// select all columns except _9 (UINT_8) and _10 (UINT_16)
checkSparkAnswerAndOperator(
"""select _1, _2, _3, _4, _5, _6, _7, _8, _11, _12, _13, _14, _15, _16, _17,
|_18, _19, _20, _21, _id FROM tbl WHERE _2 > 100""".stripMargin)
}
}
}
}
test("uint data type support - excluding u8/u16") {
// variant that tests UINT_32 and UINT_64, skipping _9 (UINT_8) and _10 (UINT_16)
Seq(true, false).foreach { dictionaryEnabled =>
withTempDir { dir =>
val path = new Path(dir.toURI.toString, "testuint.parquet")
makeParquetFileAllPrimitiveTypes(
path,
dictionaryEnabled = dictionaryEnabled,
Byte.MinValue,
Byte.MaxValue)
withParquetTable(path.toString, "tbl") {
// test UINT_32 (_11) and UINT_64 (_12) only
checkSparkAnswerAndOperator("select _11, _12 from tbl order by _11")
}
}
}
}
test("null literals") {
val batchSize = 1000
Seq(true, false).foreach { dictionaryEnabled =>
withTempDir { dir =>
val path = new Path(dir.toURI.toString, "test.parquet")
makeParquetFileAllPrimitiveTypes(path, dictionaryEnabled = dictionaryEnabled, batchSize)
withParquetTable(path.toString, "tbl") {
val sqlString =
"""SELECT
|_4 + null,
|_15 - null,
|_16 * null,
|cast(null as struct<_1:int>),
|cast(null as map<int, int>),
|cast(null as array<int>)
|FROM tbl""".stripMargin
val df2 = sql(sqlString)
val rows = df2.collect()
assert(rows.length == batchSize)
assert(rows.forall(_ == Row(null, null, null, null, null, null)))
checkSparkAnswerAndOperator(sqlString)
}
}
}
}
test("date and timestamp type literals") {
Seq(true, false).foreach { dictionaryEnabled =>
withTempDir { dir =>
val path = new Path(dir.toURI.toString, "test.parquet")
makeParquetFileAllPrimitiveTypes(path, dictionaryEnabled = dictionaryEnabled, 10000)
withParquetTable(path.toString, "tbl") {
checkSparkAnswerAndOperator(
"SELECT _4 FROM tbl WHERE " +
"_20 > CAST('2020-01-01' AS DATE) AND _18 < CAST('2020-01-01' AS TIMESTAMP)")
}
}
}
}
test("date_add with int scalars") {
Seq(true, false).foreach { dictionaryEnabled =>
Seq("TINYINT", "SHORT", "INT").foreach { intType =>
withTempDir { dir =>
val path = new Path(dir.toURI.toString, "test.parquet")
makeParquetFileAllPrimitiveTypes(path, dictionaryEnabled = dictionaryEnabled, 10000)
withParquetTable(path.toString, "tbl") {
checkSparkAnswerAndOperator(f"SELECT _20 + CAST(2 as $intType) from tbl")
}
}
}
}
}
// TODO: https://github.com/apache/datafusion-comet/issues/2539
ignore("date_add with scalar overflow") {
Seq(true, false).foreach { dictionaryEnabled =>
withTempDir { dir =>
val path = new Path(dir.toURI.toString, "test.parquet")
makeParquetFileAllPrimitiveTypes(path, dictionaryEnabled = dictionaryEnabled, 10000)
withParquetTable(path.toString, "tbl") {
val (sparkErr, cometErr) =
checkSparkAnswerMaybeThrows(sql(s"SELECT _20 + ${Int.MaxValue} FROM tbl"))
if (isSpark40Plus) {
assert(sparkErr.get.getMessage.contains("EXPRESSION_DECODING_FAILED"))
} else {
assert(sparkErr.get.getMessage.contains("integer overflow"))
}
assert(cometErr.get.getMessage.contains("attempt to add with overflow"))
}
}
}
}
test("date_add with int arrays") {
Seq(true, false).foreach { dictionaryEnabled =>
Seq("_2", "_3", "_4").foreach { intColumn => // tinyint, short, int columns
withTempDir { dir =>
val path = new Path(dir.toURI.toString, "test.parquet")
makeParquetFileAllPrimitiveTypes(path, dictionaryEnabled = dictionaryEnabled, 10000)
withParquetTable(path.toString, "tbl") {
checkSparkAnswerAndOperator(f"SELECT _20 + $intColumn FROM tbl")
}
}
}
}
}
test("date_sub with int scalars") {
Seq(true, false).foreach { dictionaryEnabled =>
Seq("TINYINT", "SHORT", "INT").foreach { intType =>
withTempDir { dir =>
val path = new Path(dir.toURI.toString, "test.parquet")
makeParquetFileAllPrimitiveTypes(path, dictionaryEnabled = dictionaryEnabled, 10000)
withParquetTable(path.toString, "tbl") {
checkSparkAnswerAndOperator(f"SELECT _20 - CAST(2 as $intType) from tbl")
}
}
}
}
}
test("date_sub with scalar overflow") {
Seq(true, false).foreach { dictionaryEnabled =>
withTempDir { dir =>
val path = new Path(dir.toURI.toString, "test.parquet")
makeParquetFileAllPrimitiveTypes(path, dictionaryEnabled = dictionaryEnabled, 10000)
withParquetTable(path.toString, "tbl") {
val (sparkErr, cometErr) =
checkSparkAnswerMaybeThrows(sql(s"SELECT _20 - ${Int.MaxValue} FROM tbl"))
if (isSpark40Plus) {
assert(sparkErr.get.getMessage.contains("EXPRESSION_DECODING_FAILED"))
assert(cometErr.get.getMessage.contains("EXPRESSION_DECODING_FAILED"))
} else {
assert(sparkErr.get.getMessage.contains("integer overflow"))
assert(cometErr.get.getMessage.contains("integer overflow"))
}
}
}
}
}
test("date_sub with int arrays") {
Seq(true, false).foreach { dictionaryEnabled =>
Seq("_2", "_3", "_4").foreach { intColumn => // tinyint, short, int columns
withTempDir { dir =>
val path = new Path(dir.toURI.toString, "test.parquet")
makeParquetFileAllPrimitiveTypes(path, dictionaryEnabled = dictionaryEnabled, 10000)
withParquetTable(path.toString, "tbl") {
checkSparkAnswerAndOperator(f"SELECT _20 - $intColumn FROM tbl")
}
}
}
}
}
test("try_add") {
val data = Seq((1, 1))
withParquetTable(data, "tbl") {
checkSparkAnswerAndOperator(spark.sql("""
|SELECT
| try_add(2147483647, 1),
| try_add(-2147483648, -1),
| try_add(NULL, 5),
| try_add(5, NULL),
| try_add(9223372036854775807, 1),
| try_add(-9223372036854775808, -1)
| from tbl
| """.stripMargin))
}
}
test("try_subtract") {
val data = Seq((1, 1))
withParquetTable(data, "tbl") {
checkSparkAnswerAndOperator(spark.sql("""
|SELECT
| try_subtract(2147483647, -1),
| try_subtract(-2147483648, 1),
| try_subtract(NULL, 5),
| try_subtract(5, NULL),
| try_subtract(9223372036854775807, -1),
| try_subtract(-9223372036854775808, 1)
| FROM tbl
""".stripMargin))
}
}
test("try_multiply") {
val data = Seq((1, 1))
withParquetTable(data, "tbl") {
checkSparkAnswerAndOperator(spark.sql("""
|SELECT
| try_multiply(1073741824, 4),
| try_multiply(-1073741824, 4),
| try_multiply(NULL, 5),
| try_multiply(5, NULL),
| try_multiply(3037000499, 3037000500),
| try_multiply(-3037000499, 3037000500)
|FROM tbl
""".stripMargin))
}
}
test("try_divide") {
val data = Seq((15121991, 0))
withParquetTable(data, "tbl") {
checkSparkAnswerAndOperator("SELECT try_divide(_1, _2) FROM tbl")
checkSparkAnswerAndOperator("""
|SELECT
| try_divide(10, 0),
| try_divide(NULL, 5),
| try_divide(5, NULL),
| try_divide(-2147483648, -1),
| try_divide(-9223372036854775808, -1),
| try_divide(DECIMAL('9999999999999999999999999999'), 0.1)
| from tbl
|""".stripMargin)
}
}
test("try_integral_divide overflow cases") {
val data = Seq((15121991, 0))
withParquetTable(data, "tbl") {
checkSparkAnswerAndOperator("SELECT try_divide(_1, _2) FROM tbl")
checkSparkAnswerAndOperator("""
|SELECT try_divide(-128, -1),
|try_divide(-32768, -1),
|try_divide(-2147483648, -1),
|try_divide(-9223372036854775808, -1),
|try_divide(CAST(99999 AS DECIMAL(5,0)), CAST(0.0001 AS DECIMAL(5,4)))
|from tbl
|""".stripMargin)
}
}
test("dictionary arithmetic") {
// TODO: test ANSI mode
withSQLConf(SQLConf.ANSI_ENABLED.key -> "false", "parquet.enable.dictionary" -> "true") {
withParquetTable((0 until 10).map(i => (i % 5, i % 3)), "tbl") {
checkSparkAnswerAndOperator("SELECT _1 + _2, _1 - _2, _1 * _2, _1 / _2, _1 % _2 FROM tbl")
}
}
}
test("dictionary arithmetic with scalar") {
withSQLConf("parquet.enable.dictionary" -> "true") {
withParquetTable((0 until 10).map(i => (i % 5, i % 3)), "tbl") {
checkSparkAnswerAndOperator("SELECT _1 + 1, _1 - 1, _1 * 2, _1 / 2, _1 % 2 FROM tbl")
}
}
}
test("string type and substring") {
withParquetTable((0 until 5).map(i => (i.toString, (i + 100).toString)), "tbl") {
checkSparkAnswerAndOperator("SELECT _1, substring(_2, 2, 2) FROM tbl")
checkSparkAnswerAndOperator("SELECT _1, substring(_2, 2, -2) FROM tbl")
checkSparkAnswerAndOperator("SELECT _1, substring(_2, -2, 2) FROM tbl")
checkSparkAnswerAndOperator("SELECT _1, substring(_2, -2, -2) FROM tbl")
checkSparkAnswerAndOperator("SELECT _1, substring(_2, -2, 10) FROM tbl")
checkSparkAnswerAndOperator("SELECT _1, substring(_2, 0, 0) FROM tbl")
checkSparkAnswerAndOperator("SELECT _1, substring(_2, 1, 0) FROM tbl")
}
}
test("substring with start < 1") {
withTempPath { _ =>
withTable("t") {
sql("create table t (col string) using parquet")
sql("insert into t values('123456')")
checkSparkAnswerAndOperator(sql("select substring(col, 0) from t"))
checkSparkAnswerAndOperator(sql("select substring(col, -1) from t"))
}
}
}
test("substring with dictionary") {
val data = (0 until 1000)
.map(_ % 5) // reduce value space to trigger dictionary encoding
.map(i => (i.toString, (i + 100).toString))
withParquetTable(data, "tbl") {
checkSparkAnswerAndOperator("SELECT _1, substring(_2, 2, 2) FROM tbl")
}
}
test("hour, minute, second") {
Seq(true, false).foreach { dictionaryEnabled =>
withTempDir { dir =>
val path = new Path(dir.toURI.toString, "part-r-0.parquet")
val expected = makeRawTimeParquetFile(path, dictionaryEnabled = dictionaryEnabled, 10000)
readParquetFile(path.toString) { df =>
val query = df.select(expr("hour(_1)"), expr("minute(_1)"), expr("second(_1)"))
checkAnswer(
query,
expected.map {
case None =>
Row(null, null, null)
case Some(i) =>
val timestamp = new java.sql.Timestamp(i).toLocalDateTime
val hour = timestamp.getHour
val minute = timestamp.getMinute
val second = timestamp.getSecond
Row(hour, minute, second)
})
}
}
}
}
test("time expressions folded on jvm") {
val ts = "1969-12-31 16:23:45"
val functions = Map("hour" -> 16, "minute" -> 23, "second" -> 45)
functions.foreach { case (func, expectedValue) =>
val query = s"SELECT $func('$ts') AS result"
val df = spark.sql(query)
val optimizedPlan = df.queryExecution.optimizedPlan
val isFolded = optimizedPlan.expressions.exists {
case alias: Alias =>
alias.child match {
case Literal(value, _) => value == expectedValue
case _ => false
}
case _ => false
}
assert(isFolded, s"Expected '$func(...)' to be constant-folded to Literal($expectedValue)")
}
}
test("hour on int96 timestamp column") {
import testImplicits._
val N = 100
val ts = "2020-01-01 01:02:03.123456"
Seq(true, false).foreach { dictionaryEnabled =>
Seq(false, true).foreach { conversionEnabled =>
withSQLConf(
SQLConf.PARQUET_OUTPUT_TIMESTAMP_TYPE.key -> "INT96",
SQLConf.PARQUET_INT96_TIMESTAMP_CONVERSION.key -> conversionEnabled.toString) {
withTempPath { path =>
Seq
.tabulate(N)(_ => ts)
.toDF("ts1")
.select($"ts1".cast("timestamp").as("ts"))
.repartition(1)
.write
.option("parquet.enable.dictionary", dictionaryEnabled)
.parquet(path.getCanonicalPath)
checkAnswer(
spark.read.parquet(path.getCanonicalPath).select(expr("hour(ts)")),
Seq.tabulate(N)(_ => Row(1)))
}
}
}
}
}
test("cast timestamp and timestamp_ntz") {
withSQLConf(
SESSION_LOCAL_TIMEZONE.key -> "Asia/Kathmandu",
CometConf.getExprAllowIncompatConfigKey(classOf[Cast]) -> "true") {
Seq(true, false).foreach { dictionaryEnabled =>
withTempDir { dir =>
val path = new Path(dir.toURI.toString, "timestamp_trunc.parquet")
makeRawTimeParquetFile(path, dictionaryEnabled = dictionaryEnabled, 10000)
withParquetTable(path.toString, "timetbl") {
checkSparkAnswerAndOperator(
"SELECT " +
"cast(_2 as timestamp) tz_millis, " +
"cast(_3 as timestamp) ntz_millis, " +
"cast(_4 as timestamp) tz_micros, " +
"cast(_5 as timestamp) ntz_micros " +
" from timetbl")
}
}
}
}
}
test("cast timestamp and timestamp_ntz to string") {
withSQLConf(
SESSION_LOCAL_TIMEZONE.key -> "Asia/Kathmandu",
CometConf.getExprAllowIncompatConfigKey(classOf[Cast]) -> "true") {
Seq(true, false).foreach { dictionaryEnabled =>
withTempDir { dir =>
val path = new Path(dir.toURI.toString, "timestamp_trunc.parquet")
makeRawTimeParquetFile(path, dictionaryEnabled = dictionaryEnabled, 2001)
withParquetTable(path.toString, "timetbl") {
checkSparkAnswerAndOperator(
"SELECT " +
"cast(_2 as string) tz_millis, " +
"cast(_3 as string) ntz_millis, " +
"cast(_4 as string) tz_micros, " +
"cast(_5 as string) ntz_micros " +
" from timetbl")
}
}
}
}
}
test("cast timestamp and timestamp_ntz to long, date") {
withSQLConf(
SESSION_LOCAL_TIMEZONE.key -> "Asia/Kathmandu",
CometConf.getExprAllowIncompatConfigKey(classOf[Cast]) -> "true") {
Seq(true, false).foreach { dictionaryEnabled =>
withTempDir { dir =>
val path = new Path(dir.toURI.toString, "timestamp_trunc.parquet")
makeRawTimeParquetFile(path, dictionaryEnabled = dictionaryEnabled, 10000)
withParquetTable(path.toString, "timetbl") {
checkSparkAnswerAndOperator(
"SELECT " +
"cast(_2 as long) tz_millis, " +
"cast(_4 as long) tz_micros, " +
"cast(_2 as date) tz_millis_to_date, " +
"cast(_3 as date) ntz_millis_to_date, " +
"cast(_4 as date) tz_micros_to_date, " +
"cast(_5 as date) ntz_micros_to_date " +
" from timetbl")
}
}
}
}
}
test("trunc") {
Seq(true, false).foreach { dictionaryEnabled =>
withTempDir { dir =>
val path = new Path(dir.toURI.toString, "date_trunc.parquet")
makeParquetFileAllPrimitiveTypes(path, dictionaryEnabled = dictionaryEnabled, 10000)
withParquetTable(path.toString, "tbl") {
Seq("YEAR", "YYYY", "YY", "QUARTER", "MON", "MONTH", "MM", "WEEK").foreach { format =>
checkSparkAnswerAndOperator(s"SELECT trunc(_20, '$format') from tbl")
}
}
}
}
}
test("trunc with format array") {
val numRows = 1000
Seq(true, false).foreach { dictionaryEnabled =>
withTempDir { dir =>
val path = new Path(dir.toURI.toString, "date_trunc_with_format.parquet")
makeDateTimeWithFormatTable(path, dictionaryEnabled = dictionaryEnabled, numRows)
withParquetTable(path.toString, "dateformattbl") {
withSQLConf(CometConf.getExprAllowIncompatConfigKey(classOf[TruncDate]) -> "true") {
checkSparkAnswerAndOperator(
"SELECT " +
"dateformat, _7, " +
"trunc(_7, dateformat) " +
" from dateformattbl ")
}
}
}
}
}
test("date_trunc") {
withSQLConf(CometConf.getExprAllowIncompatConfigKey(classOf[TruncTimestamp]) -> "true") {
Seq(true, false).foreach { dictionaryEnabled =>
withTempDir { dir =>
val path = new Path(dir.toURI.toString, "timestamp_trunc.parquet")
makeRawTimeParquetFile(path, dictionaryEnabled = dictionaryEnabled, 10000)
withParquetTable(path.toString, "timetbl") {
Seq(
"YEAR",
"YYYY",
"YY",
"MON",
"MONTH",
"MM",
"QUARTER",
"WEEK",
"DAY",
"DD",
"HOUR",
"MINUTE",
"SECOND",
"MILLISECOND",
"MICROSECOND").foreach { format =>
checkSparkAnswerAndOperator(
"SELECT " +
s"date_trunc('$format', _0), " +
s"date_trunc('$format', _1), " +
s"date_trunc('$format', _2), " +
s"date_trunc('$format', _4) " +
" from timetbl")
}
}
}
}
}
}
test("date_trunc with timestamp_ntz") {
withSQLConf(
CometConf.getExprAllowIncompatConfigKey(classOf[Cast]) -> "true",
CometConf.getExprAllowIncompatConfigKey(classOf[TruncTimestamp]) -> "true") {
Seq(true, false).foreach { dictionaryEnabled =>
withTempDir { dir =>
val path = new Path(dir.toURI.toString, "timestamp_trunc.parquet")
makeRawTimeParquetFile(path, dictionaryEnabled = dictionaryEnabled, 10000)
withParquetTable(path.toString, "timetbl") {
Seq(
"YEAR",
"YYYY",
"YY",
"MON",
"MONTH",
"MM",
"QUARTER",
"WEEK",
"DAY",
"DD",
"HOUR",
"MINUTE",
"SECOND",
"MILLISECOND",
"MICROSECOND").foreach { format =>
checkSparkAnswerAndOperator(
"SELECT " +
s"date_trunc('$format', _3), " +
s"date_trunc('$format', _5) " +
" from timetbl")
}
}
}
}
}
}
test("date_trunc with format array") {
val numRows = 1000
Seq(true, false).foreach { dictionaryEnabled =>
withTempDir { dir =>
val path = new Path(dir.toURI.toString, "timestamp_trunc_with_format.parquet")
makeDateTimeWithFormatTable(path, dictionaryEnabled = dictionaryEnabled, numRows)
withParquetTable(path.toString, "timeformattbl") {
withSQLConf(
CometConf.getExprAllowIncompatConfigKey(classOf[Cast]) -> "true",
CometConf.getExprAllowIncompatConfigKey(classOf[TruncTimestamp]) -> "true") {
checkSparkAnswerAndOperator(
"SELECT " +
"format, _0, _1, _2, _3, _4, _5, " +
"date_trunc(format, _0), " +
"date_trunc(format, _1), " +
"date_trunc(format, _2), " +
"date_trunc(format, _3), " +
"date_trunc(format, _4), " +
"date_trunc(format, _5) " +
" from timeformattbl ")
}
}
}
}
}
test("date_trunc on int96 timestamp column") {
import testImplicits._
val N = 100
val ts = "2020-01-01 01:02:03.123456"
Seq(true, false).foreach { dictionaryEnabled =>
Seq(false, true).foreach { conversionEnabled =>
withSQLConf(
SQLConf.PARQUET_OUTPUT_TIMESTAMP_TYPE.key -> "INT96",
SQLConf.PARQUET_INT96_TIMESTAMP_CONVERSION.key -> conversionEnabled.toString,
CometConf.getExprAllowIncompatConfigKey(classOf[TruncTimestamp]) -> "true") {
withTempPath { path =>
Seq
.tabulate(N)(_ => ts)
.toDF("ts1")
.select($"ts1".cast("timestamp").as("ts"))
.repartition(1)
.write
.option("parquet.enable.dictionary", dictionaryEnabled)
.parquet(path.getCanonicalPath)
withParquetTable(path.toString, "int96timetbl") {
Seq(
"YEAR",
"YYYY",
"YY",
"MON",
"MONTH",
"MM",
"QUARTER",
"WEEK",
"DAY",
"DD",
"HOUR",
"MINUTE",
"SECOND",
"MILLISECOND",
"MICROSECOND").foreach { format =>
val sql = "SELECT " +
s"date_trunc('$format', ts )" +
" from int96timetbl"
if (conversionEnabled) {
// plugin is disabled if PARQUET_INT96_TIMESTAMP_CONVERSION is true
checkSparkAnswer(sql)
} else {
checkSparkAnswerAndOperator(sql)
}
}
}
}
}
}
}
}
test("charvarchar") {
Seq(false, true).foreach { dictionary =>
withSQLConf("parquet.enable.dictionary" -> dictionary.toString) {
val table = "char_tbl4"
withTable(table) {
val view = "str_view"
withView(view) {
sql(s"""create temporary view $view as select c, v from values
| (null, null), (null, null),
| (null, 'S'), (null, 'S'),
| ('N', 'N '), ('N', 'N '),
| ('Ne', 'Sp'), ('Ne', 'Sp'),
| ('Net ', 'Spa '), ('Net ', 'Spa '),
| ('NetE', 'Spar'), ('NetE', 'Spar'),
| ('NetEa ', 'Spark '), ('NetEa ', 'Spark '),
| ('NetEas ', 'Spark'), ('NetEas ', 'Spark'),
| ('NetEase', 'Spark-'), ('NetEase', 'Spark-') t(c, v);""".stripMargin)
sql(
s"create table $table(c7 char(7), c8 char(8), v varchar(6), s string) using parquet;")
sql(s"insert into $table select c, c, v, c from $view;")
val df = sql(s"""select substring(c7, 2), substring(c8, 2),
| substring(v, 3), substring(s, 2) from $table;""".stripMargin)
val expected = Row(" ", " ", "", "") ::
Row(null, null, "", null) :: Row(null, null, null, null) ::
Row("e ", "e ", "", "e") :: Row("et ", "et ", "a ", "et ") ::
Row("etE ", "etE ", "ar", "etE") ::
Row("etEa ", "etEa ", "ark ", "etEa ") ::
Row("etEas ", "etEas ", "ark", "etEas ") ::
Row("etEase", "etEase ", "ark-", "etEase") :: Nil
checkAnswer(df, expected ::: expected)
}
}
}
}
}
test("char varchar over length values") {
Seq("char", "varchar").foreach { typ =>
withTempPath { dir =>
withTable("t") {
sql("select '123456' as col").write.format("parquet").save(dir.toString)
sql(s"create table t (col $typ(2)) using parquet location '$dir'")
sql("insert into t values('1')")
checkSparkAnswerAndOperator(sql("select substring(col, 1) from t"))
checkSparkAnswerAndOperator(sql("select substring(col, 0) from t"))
checkSparkAnswerAndOperator(sql("select substring(col, -1) from t"))
}
}
}
}
test("like (LikeSimplification enabled)") {
val table = "names"
withTable(table) {
sql(s"create table $table(id int, name varchar(20)) using parquet")
sql(s"insert into $table values(1,'James Smith')")
sql(s"insert into $table values(2,'Michael Rose')")
sql(s"insert into $table values(3,'Robert Williams')")
sql(s"insert into $table values(4,'Rames Rose')")
sql(s"insert into $table values(5,'Rames rose')")
// Filter column having values 'Rames _ose', where any character matches for '_'
val query = sql(s"select id from $table where name like 'Rames _ose'")
checkAnswer(query, Row(4) :: Row(5) :: Nil)
// Filter rows that contains 'rose' in 'name' column
val queryContains = sql(s"select id from $table where name like '%rose%'")
checkAnswer(queryContains, Row(5) :: Nil)
// Filter rows that starts with 'R' following by any characters
val queryStartsWith = sql(s"select id from $table where name like 'R%'")
checkAnswer(queryStartsWith, Row(3) :: Row(4) :: Row(5) :: Nil)
// Filter rows that ends with 's' following by any characters
val queryEndsWith = sql(s"select id from $table where name like '%s'")
checkAnswer(queryEndsWith, Row(3) :: Nil)
}
}
test("like with custom escape") {
val table = "names"
withTable(table) {
sql(s"create table $table(id int, name varchar(20)) using parquet")
sql(s"insert into $table values(1,'James Smith')")
sql(s"insert into $table values(2,'Michael_Rose')")
sql(s"insert into $table values(3,'Robert_R_Williams')")
// Filter column having values that include underscores
val queryDefaultEscape = sql("select id from names where name like '%\\_%'")
checkSparkAnswerAndOperator(queryDefaultEscape)
val queryCustomEscape = sql("select id from names where name like '%$_%' escape '$'")
checkAnswer(queryCustomEscape, Row(2) :: Row(3) :: Nil)
}
}
test("rlike simple case") {
val table = "rlike_names"
Seq(false, true).foreach { withDictionary =>
val data = Seq("James Smith", "Michael Rose", "Rames Rose", "Rames rose") ++
// add repetitive data to trigger dictionary encoding
Range(0, 100).map(_ => "John Smith")
withParquetFile(data.zipWithIndex, withDictionary) { file =>
withSQLConf(CometConf.getExprAllowIncompatConfigKey("regexp") -> "true") {
spark.read.parquet(file).createOrReplaceTempView(table)
val query = sql(s"select _2 as id, _1 rlike 'R[a-z]+s [Rr]ose' from $table")
checkSparkAnswerAndOperator(query)
}
}
}
}
test("withInfo") {
val table = "with_info"
withTable(table) {
sql(s"create table $table(id int, name varchar(20)) using parquet")
sql(s"insert into $table values(1,'James Smith')")
val query = sql(s"select cast(id as string) from $table")
val (_, cometPlan) = checkSparkAnswerAndOperator(query)
val project = stripAQEPlan(cometPlan).collectFirst { case p: CometProjectExec => p }.get
val id = project.expressions.head
CometSparkSessionExtensions.withInfo(id, "reason 1")
CometSparkSessionExtensions.withInfo(project, "reason 2")
CometSparkSessionExtensions.withInfo(project, "reason 3", id)
CometSparkSessionExtensions.withInfo(project, id)
CometSparkSessionExtensions.withInfo(project, "reason 4")
CometSparkSessionExtensions.withInfo(project, "reason 5", id)
CometSparkSessionExtensions.withInfo(project, id)
CometSparkSessionExtensions.withInfo(project, "reason 6")
val explain = new ExtendedExplainInfo().generateExtendedInfo(project)
for (i <- 1 until 7) {
assert(explain.contains(s"reason $i"))
}
}
}
test("rlike fallback for non scalar pattern") {
val table = "rlike_fallback"
withTable(table) {
sql(s"create table $table(id int, name varchar(20)) using parquet")
sql(s"insert into $table values(1,'James Smith')")
withSQLConf(CometConf.getExprAllowIncompatConfigKey("regexp") -> "true") {
val query2 = sql(s"select id from $table where name rlike name")
val (_, cometPlan) = checkSparkAnswer(query2)
val explain = new ExtendedExplainInfo().generateExtendedInfo(cometPlan)
assert(explain.contains("Only scalar regexp patterns are supported"))
}
}
}
test("rlike whitespace") {
val table = "rlike_whitespace"
withTable(table) {
sql(s"create table $table(id int, name varchar(20)) using parquet")
val values =
Seq("James Smith", "\rJames\rSmith\r", "\nJames\nSmith\n", "\r\nJames\r\nSmith\r\n")
values.zipWithIndex.foreach { x =>
sql(s"insert into $table values (${x._2}, '${x._1}')")
}
val patterns = Seq(
"James",
"J[a-z]mes",
"^James",
"\\AJames",
"Smith",
"James$",
"James\\Z",