/
PlanParserSuite.scala
1354 lines (1205 loc) · 49.2 KB
/
PlanParserSuite.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.parser
import org.apache.spark.sql.catalyst.{FunctionIdentifier, TableIdentifier}
import org.apache.spark.sql.catalyst.analysis.{AnalysisTest, RelationTimeTravel, UnresolvedAlias, UnresolvedAttribute, UnresolvedFunction, UnresolvedGenerator, UnresolvedInlineTable, UnresolvedRelation, UnresolvedStar, UnresolvedSubqueryColumnAliases, UnresolvedTableValuedFunction}
import org.apache.spark.sql.catalyst.expressions._
import org.apache.spark.sql.catalyst.expressions.aggregate.{PercentileCont, PercentileDisc}
import org.apache.spark.sql.catalyst.plans._
import org.apache.spark.sql.catalyst.plans.logical._
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types.{Decimal, DecimalType, IntegerType, LongType, StringType}
/**
* Parser test cases for rules defined in [[CatalystSqlParser]] / [[AstBuilder]].
*
* There is also SparkSqlParserSuite in sql/core module for parser rules defined in sql/core module.
*/
class PlanParserSuite extends AnalysisTest {
import CatalystSqlParser._
import org.apache.spark.sql.catalyst.dsl.expressions._
import org.apache.spark.sql.catalyst.dsl.plans._
private def assertEqual(sqlCommand: String, plan: LogicalPlan): Unit = {
comparePlans(parsePlan(sqlCommand), plan, checkAnalysis = false)
}
private def intercept(sqlCommand: String, messages: String*): Unit =
interceptParseException(parsePlan)(sqlCommand, messages: _*)()
private def intercept(sqlCommand: String, errorClass: Option[String], messages: String*): Unit =
interceptParseException(parsePlan)(sqlCommand, messages: _*)(errorClass)
private def cte(
plan: LogicalPlan,
namedPlans: (String, (LogicalPlan, Seq[String]))*): UnresolvedWith = {
val ctes = namedPlans.map {
case (name, (cte, columnAliases)) =>
val subquery = if (columnAliases.isEmpty) {
cte
} else {
UnresolvedSubqueryColumnAliases(columnAliases, cte)
}
name -> SubqueryAlias(name, subquery)
}
UnresolvedWith(plan, ctes)
}
test("single comment case one") {
val plan = table("a").select(star())
assertEqual("-- single comment\nSELECT * FROM a", plan)
}
test("single comment case two") {
val plan = table("a").select(star())
assertEqual("-- single comment\\\nwith line continuity\nSELECT * FROM a", plan)
}
test("bracketed comment case one") {
val plan = table("a").select(star())
assertEqual(
"""
|/* This is an example of SQL which should not execute:
| * select 'multi-line';
| */
|SELECT * FROM a
""".stripMargin, plan)
}
test("bracketed comment case two") {
val plan = table("a").select(star())
assertEqual(
"""
|/*
|SELECT 'trailing' as x1; -- inside block comment
|*/
|SELECT * FROM a
""".stripMargin, plan)
}
test("nested bracketed comment case one") {
val plan = table("a").select(star())
assertEqual(
"""
|/* This block comment surrounds a query which itself has a block comment...
|SELECT /* embedded single line */ 'embedded' AS x2;
|*/
|SELECT * FROM a
""".stripMargin, plan)
}
test("nested bracketed comment case two") {
val plan = table("a").select(star())
assertEqual(
"""
|SELECT -- continued after the following block comments...
|/* Deeply nested comment.
| This includes a single apostrophe to make sure we aren't decoding this part as a string.
|SELECT 'deep nest' AS n1;
|/* Second level of nesting...
|SELECT 'deeper nest' as n2;
|/* Third level of nesting...
|SELECT 'deepest nest' as n3;
|*/
|Hoo boy. Still two deep...
|*/
|Now just one deep...
|*/
|* FROM a
""".stripMargin, plan)
}
test("nested bracketed comment case three") {
val plan = table("a").select(star())
assertEqual(
"""
|/* This block comment surrounds a query which itself has a block comment...
|//* I am a nested bracketed comment.
|*/
|*/
|SELECT * FROM a
""".stripMargin, plan)
}
test("nested bracketed comment case four") {
val plan = table("a").select(star())
assertEqual(
"""
|/*/**/*/
|SELECT * FROM a
""".stripMargin, plan)
}
test("nested bracketed comment case five") {
val plan = table("a").select(star())
assertEqual(
"""
|/*/*abc*/*/
|SELECT * FROM a
""".stripMargin, plan)
}
test("nested bracketed comment case six") {
val plan = table("a").select(star())
assertEqual(
"""
|/*/*foo*//*bar*/*/
|SELECT * FROM a
""".stripMargin, plan)
}
test("nested bracketed comment case seven") {
val plan = OneRowRelation().select(Literal(1).as("a"))
assertEqual(
"""
|/*abc*/
|select 1 as a
|/*
|
|2 as b
|/*abc */
|, 3 as c
|
|/**/
|*/
""".stripMargin, plan)
}
test("unclosed bracketed comment one") {
val query = """
|/*abc*/
|select 1 as a
|/*
|
|2 as b
|/*abc */
|, 3 as c
|
|/**/
|""".stripMargin
val e = intercept[ParseException](parsePlan(query))
assert(e.getMessage.contains(s"Unclosed bracketed comment"))
}
test("unclosed bracketed comment two") {
val query = """
|/*abc*/
|select 1 as a
|/*
|
|2 as b
|/*abc */
|, 3 as c
|
|/**/
|select 4 as d
|""".stripMargin
val e = intercept[ParseException](parsePlan(query))
assert(e.getMessage.contains(s"Unclosed bracketed comment"))
}
test("case insensitive") {
val plan = table("a").select(star())
assertEqual("sELEct * FroM a", plan)
assertEqual("select * fRoM a", plan)
assertEqual("SELECT * FROM a", plan)
}
test("explain") {
intercept("EXPLAIN logical SELECT 1", "Unsupported SQL statement")
intercept("EXPLAIN formatted SELECT 1", "Unsupported SQL statement")
}
test("set operations") {
val a = table("a").select(star())
val b = table("b").select(star())
assertEqual("select * from a union select * from b", Distinct(a.union(b)))
assertEqual("select * from a union distinct select * from b", Distinct(a.union(b)))
assertEqual("select * from a union all select * from b", a.union(b))
assertEqual("select * from a except select * from b", a.except(b, isAll = false))
assertEqual("select * from a except distinct select * from b", a.except(b, isAll = false))
assertEqual("select * from a except all select * from b", a.except(b, isAll = true))
assertEqual("select * from a minus select * from b", a.except(b, isAll = false))
assertEqual("select * from a minus all select * from b", a.except(b, isAll = true))
assertEqual("select * from a minus distinct select * from b", a.except(b, isAll = false))
assertEqual("select * from a " +
"intersect select * from b", a.intersect(b, isAll = false))
assertEqual("select * from a intersect distinct select * from b", a.intersect(b, isAll = false))
assertEqual("select * from a intersect all select * from b", a.intersect(b, isAll = true))
}
test("common table expressions") {
assertEqual(
"with cte1 as (select * from a) select * from cte1",
cte(table("cte1").select(star()), "cte1" -> ((table("a").select(star()), Seq.empty))))
assertEqual(
"with cte1 (select 1) select * from cte1",
cte(table("cte1").select(star()), "cte1" -> ((OneRowRelation().select(1), Seq.empty))))
assertEqual(
"with cte1 (select 1), cte2 as (select * from cte1) select * from cte2",
cte(table("cte2").select(star()),
"cte1" -> ((OneRowRelation().select(1), Seq.empty)),
"cte2" -> ((table("cte1").select(star()), Seq.empty))))
intercept(
"with cte1 (select 1), cte1 as (select 1 from cte1) select * from cte1",
"CTE definition can't have duplicate names: 'cte1'.")
}
test("simple select query") {
assertEqual("select 1", OneRowRelation().select(1))
assertEqual("select a, b", OneRowRelation().select($"a", $"b"))
assertEqual("select a, b from db.c", table("db", "c").select($"a", $"b"))
assertEqual("select a, b from db.c where x < 1",
table("db", "c").where($"x" < 1).select($"a", $"b"))
assertEqual(
"select a, b from db.c having x < 1",
table("db", "c").having()($"a", $"b")($"x" < 1))
assertEqual("select distinct a, b from db.c", Distinct(table("db", "c").select($"a", $"b")))
assertEqual("select all a, b from db.c", table("db", "c").select($"a", $"b"))
assertEqual("select from tbl", OneRowRelation().select($"from".as("tbl")))
assertEqual("select a from 1k.2m", table("1k", "2m").select($"a"))
}
test("hive-style single-FROM statement") {
assertEqual("from a select b, c", table("a").select($"b", $"c"))
assertEqual(
"from db.a select b, c where d < 1", table("db", "a").where($"d" < 1).select($"b", $"c"))
assertEqual("from a select distinct b, c", Distinct(table("a").select($"b", $"c")))
// Weird "FROM table" queries, should be invalid anyway
intercept("from a", "Syntax error at or near end of input")
intercept("from (from a union all from b) c select *", "Syntax error at or near 'union'")
}
test("multi select query") {
assertEqual(
"from a select * select * where s < 10",
table("a").select(star()).union(table("a").where($"s" < 10).select(star())))
intercept(
"from a select * select * from x where a.s < 10", Some("PARSE_SYNTAX_ERROR"),
"Syntax error at or near 'from'")
intercept(
"from a select * from b", Some("PARSE_SYNTAX_ERROR"),
"Syntax error at or near 'from'")
assertEqual(
"from a insert into tbl1 select * insert into tbl2 select * where s < 10",
table("a").select(star()).insertInto("tbl1").union(
table("a").where($"s" < 10).select(star()).insertInto("tbl2")))
assertEqual(
"select * from (from a select * select *)",
table("a").select(star())
.union(table("a").select(star()))
.as("__auto_generated_subquery_name").select(star()))
}
test("query organization") {
// Test all valid combinations of order by/sort by/distribute by/cluster by/limit/windows
val baseSql = "select * from t"
val basePlan = table("t").select(star())
val ws = Map("w1" -> WindowSpecDefinition(Seq.empty, Seq.empty, UnspecifiedFrame))
val limitWindowClauses = Seq(
("", (p: LogicalPlan) => p),
(" limit 10", (p: LogicalPlan) => p.limit(10)),
(" window w1 as ()", (p: LogicalPlan) => WithWindowDefinition(ws, p)),
(" window w1 as () limit 10", (p: LogicalPlan) => WithWindowDefinition(ws, p).limit(10))
)
val orderSortDistrClusterClauses = Seq(
("", basePlan),
(" order by a, b desc", basePlan.orderBy($"a".asc, $"b".desc)),
(" sort by a, b desc", basePlan.sortBy($"a".asc, $"b".desc))
)
orderSortDistrClusterClauses.foreach {
case (s1, p1) =>
limitWindowClauses.foreach {
case (s2, pf2) =>
assertEqual(baseSql + s1 + s2, pf2(p1))
}
}
val msg = "Combination of ORDER BY/SORT BY/DISTRIBUTE BY/CLUSTER BY is not supported"
intercept(s"$baseSql order by a sort by a", msg)
intercept(s"$baseSql cluster by a distribute by a", msg)
intercept(s"$baseSql order by a cluster by a", msg)
intercept(s"$baseSql order by a distribute by a", msg)
}
test("insert into") {
import org.apache.spark.sql.catalyst.dsl.expressions._
import org.apache.spark.sql.catalyst.dsl.plans._
val sql = "select * from t"
val plan = table("t").select(star())
def insert(
partition: Map[String, Option[String]],
overwrite: Boolean = false,
ifPartitionNotExists: Boolean = false): LogicalPlan =
InsertIntoStatement(table("s"), partition, Nil, plan, overwrite, ifPartitionNotExists)
// Single inserts
assertEqual(s"insert overwrite table s $sql",
insert(Map.empty, overwrite = true))
assertEqual(s"insert overwrite table s partition (e = 1) if not exists $sql",
insert(Map("e" -> Option("1")), overwrite = true, ifPartitionNotExists = true))
assertEqual(s"insert into s $sql",
insert(Map.empty))
assertEqual(s"insert into table s partition (c = 'd', e = 1) $sql",
insert(Map("c" -> Option("d"), "e" -> Option("1"))))
// Multi insert
val plan2 = table("t").where($"x" > 5).select(star())
assertEqual("from t insert into s select * limit 1 insert into u select * where x > 5",
plan.limit(1).insertInto("s").union(plan2.insertInto("u")))
}
test("aggregation") {
val sql = "select a, b, sum(c) as c from d group by a, b"
val sqlWithoutGroupBy = "select a, b, sum(c) as c from d"
// Normal
assertEqual(sql, table("d").groupBy($"a", $"b")($"a", $"b", $"sum".function($"c").as("c")))
// Cube
assertEqual(s"$sql with cube",
table("d").groupBy(Cube(Seq(Seq($"a"), Seq($"b"))))($"a", $"b", $"sum".function($"c")
.as("c")))
assertEqual(s"$sqlWithoutGroupBy group by cube(a, b)",
table("d").groupBy(Cube(Seq(Seq($"a"), Seq($"b"))))($"a", $"b", $"sum".function($"c")
.as("c")))
assertEqual(s"$sqlWithoutGroupBy group by cube (a, b)",
table("d").groupBy(Cube(Seq(Seq($"a"), Seq($"b"))))($"a", $"b", $"sum".function($"c")
.as("c")))
// Rollup
assertEqual(s"$sql with rollup",
table("d").groupBy(Rollup(Seq(Seq($"a"), Seq($"b"))))($"a", $"b", $"sum".function($"c")
.as("c")))
assertEqual(s"$sqlWithoutGroupBy group by rollup(a, b)",
table("d").groupBy(Rollup(Seq(Seq($"a"), Seq($"b"))))($"a", $"b", $"sum".function($"c")
.as("c")))
assertEqual(s"$sqlWithoutGroupBy group by rollup (a, b)",
table("d").groupBy(Rollup(Seq(Seq($"a"), Seq($"b"))))($"a", $"b", $"sum".function($"c")
.as("c")))
// Grouping Sets
assertEqual(s"$sql grouping sets((a, b), (a), ())",
Aggregate(Seq(GroupingSets(Seq(Seq($"a", $"b"), Seq($"a"), Seq()), Seq($"a", $"b"))),
Seq($"a", $"b", $"sum".function($"c").as("c")), table("d")))
assertEqual(s"$sqlWithoutGroupBy group by grouping sets((a, b), (a), ())",
Aggregate(Seq(GroupingSets(Seq(Seq($"a", $"b"), Seq($"a"), Seq()))),
Seq($"a", $"b", $"sum".function($"c").as("c")), table("d")))
val m = intercept[ParseException] {
parsePlan("SELECT a, b, count(distinct a, distinct b) as c FROM d GROUP BY a, b")
}.getMessage
assert(m.contains("Syntax error at or near 'b': extra input 'b'"))
}
test("limit") {
val sql = "select * from t"
val plan = table("t").select(star())
assertEqual(s"$sql limit 10", plan.limit(10))
assertEqual(s"$sql limit cast(9 / 4 as int)", plan.limit(Cast(Literal(9) / 4, IntegerType)))
}
test("window spec") {
// Note that WindowSpecs are testing in the ExpressionParserSuite
val sql = "select * from t"
val plan = table("t").select(star())
val spec = WindowSpecDefinition(Seq($"a", $"b"), Seq($"c".asc),
SpecifiedWindowFrame(RowFrame, -Literal(1), Literal(1)))
// Test window resolution.
val ws1 = Map("w1" -> spec, "w2" -> spec, "w3" -> spec)
assertEqual(
s"""$sql
|window w1 as (partition by a, b order by c rows between 1 preceding and 1 following),
| w2 as w1,
| w3 as w1""".stripMargin,
WithWindowDefinition(ws1, plan))
}
test("lateral view") {
val explode = UnresolvedGenerator(FunctionIdentifier("explode"), Seq($"x"))
val jsonTuple = UnresolvedGenerator(FunctionIdentifier("json_tuple"), Seq($"x", $"y"))
// Single lateral view
assertEqual(
"select * from t lateral view explode(x) expl as x",
table("t")
.generate(explode, alias = Some("expl"), outputNames = Seq("x"))
.select(star()))
// Multiple lateral views
assertEqual(
"""select *
|from t
|lateral view explode(x) expl
|lateral view outer json_tuple(x, y) jtup q, z""".stripMargin,
table("t")
.generate(explode, alias = Some("expl"))
.generate(jsonTuple, outer = true, alias = Some("jtup"), outputNames = Seq("q", "z"))
.select(star()))
// Multi-Insert lateral views.
val from = table("t1").generate(explode, alias = Some("expl"), outputNames = Seq("x"))
assertEqual(
"""from t1
|lateral view explode(x) expl as x
|insert into t2
|select *
|lateral view json_tuple(x, y) jtup q, z
|insert into t3
|select *
|where s < 10
""".stripMargin,
Union(from
.generate(jsonTuple, alias = Some("jtup"), outputNames = Seq("q", "z"))
.select(star())
.insertInto("t2"),
from.where($"s" < 10).select(star()).insertInto("t3")))
// Unresolved generator.
val expected = table("t")
.generate(
UnresolvedGenerator(FunctionIdentifier("posexplode"), Seq($"x")),
alias = Some("posexpl"),
outputNames = Seq("x", "y"))
.select(star())
assertEqual(
"select * from t lateral view posexplode(x) posexpl as x, y",
expected)
intercept(
"""select *
|from t
|lateral view explode(x) expl
|pivot (
| sum(x)
| FOR y IN ('a', 'b')
|)""".stripMargin,
"LATERAL cannot be used together with PIVOT in FROM clause")
}
test("joins") {
// Test single joins.
val testUnconditionalJoin = (sql: String, jt: JoinType) => {
assertEqual(
s"select * from t as tt $sql u",
table("t").as("tt").join(table("u"), jt, None).select(star()))
}
val testConditionalJoin = (sql: String, jt: JoinType) => {
assertEqual(
s"select * from t $sql u as uu on a = b",
table("t").join(table("u").as("uu"), jt, Option($"a" === $"b")).select(star()))
}
val testNaturalJoin = (sql: String, jt: JoinType) => {
assertEqual(
s"select * from t tt natural $sql u as uu",
table("t").as("tt").join(table("u").as("uu"), NaturalJoin(jt), None).select(star()))
}
val testUsingJoin = (sql: String, jt: JoinType) => {
assertEqual(
s"select * from t $sql u using(a, b)",
table("t").join(table("u"), UsingJoin(jt, Seq("a", "b")), None).select(star()))
}
val testLateralJoin = (sql: String, jt: JoinType) => {
assertEqual(
s"select * from t $sql lateral (select * from u) uu",
LateralJoin(
table("t"),
LateralSubquery(table("u").select(star()).as("uu")),
jt, None).select(star()))
}
val testAllExceptLateral = Seq(testUnconditionalJoin, testConditionalJoin, testNaturalJoin,
testUsingJoin)
val testAll = testAllExceptLateral :+ testLateralJoin
val testExistence = Seq(testUnconditionalJoin, testConditionalJoin, testUsingJoin)
def test(sql: String, jt: JoinType, tests: Seq[(String, JoinType) => Unit]): Unit = {
tests.foreach(_(sql, jt))
}
test("cross join", Cross, Seq(testUnconditionalJoin, testLateralJoin))
test(",", Inner, Seq(testUnconditionalJoin, testLateralJoin))
test("join", Inner, testAll)
test("inner join", Inner, testAll)
test("left join", LeftOuter, testAll)
test("left outer join", LeftOuter, testAll)
test("right join", RightOuter, testAllExceptLateral)
test("right outer join", RightOuter, testAllExceptLateral)
test("full join", FullOuter, testAllExceptLateral)
test("full outer join", FullOuter, testAllExceptLateral)
test("left semi join", LeftSemi, testExistence)
test("semi join", LeftSemi, testExistence)
test("left anti join", LeftAnti, testExistence)
test("anti join", LeftAnti, testExistence)
// Test natural cross join
intercept("select * from a natural cross join b")
// Test natural join with a condition
intercept("select * from a natural join b on a.id = b.id")
// Test multiple consecutive joins
assertEqual(
"select * from a join b join c right join d",
table("a").join(table("b")).join(table("c")).join(table("d"), RightOuter).select(star()))
// SPARK-17296
assertEqual(
"select * from t1 cross join t2 join t3 on t3.id = t1.id join t4 on t4.id = t1.id",
table("t1")
.join(table("t2"), Cross)
.join(table("t3"), Inner, Option($"t3.id" === $"t1.id"))
.join(table("t4"), Inner, Option($"t4.id" === $"t1.id"))
.select(star()))
// Test multiple on clauses.
intercept("select * from t1 inner join t2 inner join t3 on col3 = col2 on col3 = col1")
// Parenthesis
assertEqual(
"select * from t1 inner join (t2 inner join t3 on col3 = col2) on col3 = col1",
table("t1")
.join(table("t2")
.join(table("t3"), Inner, Option($"col3" === $"col2")), Inner,
Option($"col3" === $"col1"))
.select(star()))
assertEqual(
"select * from t1 inner join (t2 inner join t3) on col3 = col2",
table("t1")
.join(table("t2").join(table("t3"), Inner, None), Inner, Option($"col3" === $"col2"))
.select(star()))
assertEqual(
"select * from t1 inner join (t2 inner join t3 on col3 = col2)",
table("t1")
.join(table("t2").join(table("t3"), Inner, Option($"col3" === $"col2")), Inner, None)
.select(star()))
// Implicit joins.
assertEqual(
"select * from t1, t3 join t2 on t1.col1 = t2.col2",
table("t1")
.join(table("t3"))
.join(table("t2"), Inner, Option($"t1.col1" === $"t2.col2"))
.select(star()))
// Test lateral join with join conditions
assertEqual(
s"select * from t join lateral (select * from u) uu on true",
LateralJoin(
table("t"),
LateralSubquery(table("u").select(star()).as("uu")),
Inner, Option(true)).select(star()))
// Test multiple lateral joins
assertEqual(
"select * from a, lateral (select * from b) bb, lateral (select * from c) cc",
LateralJoin(
LateralJoin(
table("a"),
LateralSubquery(table("b").select(star()).as("bb")),
Inner, None),
LateralSubquery(table("c").select(star()).as("cc")),
Inner, None).select(star())
)
}
test("sampled relations") {
val sql = "select * from t"
assertEqual(s"$sql tablesample(100 rows)",
table("t").limit(100).select(star()))
assertEqual(s"$sql tablesample(43 percent) as x",
Sample(0, .43d, withReplacement = false, 10L, table("t").as("x")).select(star()))
assertEqual(s"$sql tablesample(bucket 4 out of 10) as x",
Sample(0, .4d, withReplacement = false, 10L, table("t").as("x")).select(star()))
intercept(s"$sql tablesample(bucket 4 out of 10 on x) as x",
"TABLESAMPLE(BUCKET x OUT OF y ON colname) is not supported")
intercept(s"$sql tablesample(bucket 11 out of 10) as x",
s"Sampling fraction (${11.0/10.0}) must be on interval [0, 1]")
intercept("SELECT * FROM parquet_t0 TABLESAMPLE(300M) s",
"TABLESAMPLE(byteLengthLiteral) is not supported")
intercept("SELECT * FROM parquet_t0 TABLESAMPLE(BUCKET 3 OUT OF 32 ON rand()) s",
"TABLESAMPLE(BUCKET x OUT OF y ON function) is not supported")
}
test("sub-query") {
val plan = table("t0").select($"id")
assertEqual("select id from (t0)", plan)
assertEqual("select id from ((((((t0))))))", plan)
assertEqual(
"(select * from t1) union distinct (select * from t2)",
Distinct(table("t1").select(star()).union(table("t2").select(star()))))
assertEqual(
"select * from ((select * from t1) union (select * from t2)) t",
Distinct(
table("t1").select(star()).union(table("t2").select(star()))).as("t").select(star()))
assertEqual(
"""select id
|from (((select id from t0)
| union all
| (select id from t0))
| union all
| (select id from t0)) as u_1
""".stripMargin,
plan.union(plan).union(plan).as("u_1").select($"id"))
}
test("scalar sub-query") {
assertEqual(
"select (select max(b) from s) ss from t",
table("t").select(ScalarSubquery(table("s").select($"max".function($"b"))).as("ss")))
assertEqual(
"select * from t where a = (select b from s)",
table("t").where($"a" === ScalarSubquery(table("s").select($"b"))).select(star()))
assertEqual(
"select g from t group by g having a > (select b from s)",
table("t")
.having($"g")($"g")($"a" > ScalarSubquery(table("s").select($"b"))))
}
test("table reference") {
assertEqual("table t", table("t"))
assertEqual("table d.t", table("d", "t"))
}
test("table valued function") {
assertEqual(
"select * from range(2)",
UnresolvedTableValuedFunction("range", Literal(2) :: Nil, Seq.empty).select(star()))
// SPARK-34627
intercept("select * from default.range(2)",
"table valued function cannot specify database name")
// SPARK-38957
intercept("select * from spark_catalog.default.range(2)",
"table valued function cannot specify database name")
}
test("SPARK-20311 range(N) as alias") {
assertEqual(
"SELECT * FROM range(10) AS t",
SubqueryAlias("t", UnresolvedTableValuedFunction("range", Literal(10) :: Nil, Seq.empty))
.select(star()))
assertEqual(
"SELECT * FROM range(7) AS t(a)",
SubqueryAlias("t", UnresolvedTableValuedFunction("range", Literal(7) :: Nil, "a" :: Nil))
.select(star()))
}
test("SPARK-20841 Support table column aliases in FROM clause") {
assertEqual(
"SELECT * FROM testData AS t(col1, col2)",
SubqueryAlias(
"t",
UnresolvedSubqueryColumnAliases(
Seq("col1", "col2"),
UnresolvedRelation(TableIdentifier("testData"))
)
).select(star()))
}
test("SPARK-20962 Support subquery column aliases in FROM clause") {
assertEqual(
"SELECT * FROM (SELECT a AS x, b AS y FROM t) t(col1, col2)",
SubqueryAlias(
"t",
UnresolvedSubqueryColumnAliases(
Seq("col1", "col2"),
UnresolvedRelation(TableIdentifier("t")).select($"a".as("x"), $"b".as("y"))
)
).select(star()))
}
test("SPARK-20963 Support aliases for join relations in FROM clause") {
val src1 = UnresolvedRelation(TableIdentifier("src1")).as("s1")
val src2 = UnresolvedRelation(TableIdentifier("src2")).as("s2")
assertEqual(
"SELECT * FROM (src1 s1 INNER JOIN src2 s2 ON s1.id = s2.id) dst(a, b, c, d)",
SubqueryAlias(
"dst",
UnresolvedSubqueryColumnAliases(
Seq("a", "b", "c", "d"),
src1.join(src2, Inner, Option($"s1.id" === $"s2.id"))
)
).select(star()))
}
test("SPARK-34335 Support referencing subquery with column aliases by table alias") {
assertEqual(
"SELECT t.col1, t.col2 FROM (SELECT a AS x, b AS y FROM t) t(col1, col2)",
SubqueryAlias(
"t",
UnresolvedSubqueryColumnAliases(
Seq("col1", "col2"),
UnresolvedRelation(TableIdentifier("t")).select($"a".as("x"), $"b".as("y")))
).select($"t.col1", $"t.col2")
)
}
test("inline table") {
assertEqual("values 1, 2, 3, 4",
UnresolvedInlineTable(Seq("col1"), Seq(1, 2, 3, 4).map(x => Seq(Literal(x)))))
assertEqual(
"values (1, 'a'), (2, 'b') as tbl(a, b)",
UnresolvedInlineTable(
Seq("a", "b"),
Seq(Literal(1), Literal("a")) :: Seq(Literal(2), Literal("b")) :: Nil).as("tbl"))
}
test("simple select query with !> and !<") {
// !< is equivalent to >=
assertEqual("select a, b from db.c where x !< 1",
table("db", "c").where($"x" >= 1).select($"a", $"b"))
// !> is equivalent to <=
assertEqual("select a, b from db.c where x !> 1",
table("db", "c").where($"x" <= 1).select($"a", $"b"))
}
test("select hint syntax") {
// Hive compatibility: Missing parameter raises ParseException.
intercept("SELECT /*+ HINT() */ * FROM t", Some("PARSE_SYNTAX_ERROR"),
"Syntax error at or near")
// Disallow space as the delimiter.
intercept("SELECT /*+ INDEX(a b c) */ * from default.t", Some("PARSE_SYNTAX_ERROR"),
"Syntax error at or near 'b'")
comparePlans(
parsePlan("SELECT /*+ HINT */ * FROM t"),
UnresolvedHint("HINT", Seq.empty, table("t").select(star())))
comparePlans(
parsePlan("SELECT /*+ BROADCASTJOIN(u) */ * FROM t"),
UnresolvedHint("BROADCASTJOIN", Seq($"u"), table("t").select(star())))
comparePlans(
parsePlan("SELECT /*+ MAPJOIN(u) */ * FROM t"),
UnresolvedHint("MAPJOIN", Seq($"u"), table("t").select(star())))
comparePlans(
parsePlan("SELECT /*+ STREAMTABLE(a,b,c) */ * FROM t"),
UnresolvedHint("STREAMTABLE", Seq($"a", $"b", $"c"), table("t").select(star())))
comparePlans(
parsePlan("SELECT /*+ INDEX(t, emp_job_ix) */ * FROM t"),
UnresolvedHint("INDEX", Seq($"t", $"emp_job_ix"), table("t").select(star())))
comparePlans(
parsePlan("SELECT /*+ MAPJOIN(`default.t`) */ * from `default.t`"),
UnresolvedHint("MAPJOIN", Seq(UnresolvedAttribute.quoted("default.t")),
table("default.t").select(star())))
comparePlans(
parsePlan("SELECT /*+ MAPJOIN(t) */ a from t where true group by a order by a"),
UnresolvedHint("MAPJOIN", Seq($"t"),
table("t").where(Literal(true)).groupBy($"a")($"a")).orderBy($"a".asc))
comparePlans(
parsePlan("SELECT /*+ COALESCE(10) */ * FROM t"),
UnresolvedHint("COALESCE", Seq(Literal(10)),
table("t").select(star())))
comparePlans(
parsePlan("SELECT /*+ REPARTITION(100) */ * FROM t"),
UnresolvedHint("REPARTITION", Seq(Literal(100)),
table("t").select(star())))
comparePlans(
parsePlan(
"INSERT INTO s SELECT /*+ REPARTITION(100), COALESCE(500), COALESCE(10) */ * FROM t"),
InsertIntoStatement(table("s"), Map.empty, Nil,
UnresolvedHint("REPARTITION", Seq(Literal(100)),
UnresolvedHint("COALESCE", Seq(Literal(500)),
UnresolvedHint("COALESCE", Seq(Literal(10)),
table("t").select(star())))), overwrite = false, ifPartitionNotExists = false))
comparePlans(
parsePlan("SELECT /*+ BROADCASTJOIN(u), REPARTITION(100) */ * FROM t"),
UnresolvedHint("BROADCASTJOIN", Seq($"u"),
UnresolvedHint("REPARTITION", Seq(Literal(100)),
table("t").select(star()))))
intercept("SELECT /*+ COALESCE(30 + 50) */ * FROM t", Some("PARSE_SYNTAX_ERROR"),
"Syntax error at or near")
comparePlans(
parsePlan("SELECT /*+ REPARTITION(c) */ * FROM t"),
UnresolvedHint("REPARTITION", Seq(UnresolvedAttribute("c")),
table("t").select(star())))
comparePlans(
parsePlan("SELECT /*+ REPARTITION(100, c) */ * FROM t"),
UnresolvedHint("REPARTITION", Seq(Literal(100), UnresolvedAttribute("c")),
table("t").select(star())))
comparePlans(
parsePlan("SELECT /*+ REPARTITION(100, c), COALESCE(50) */ * FROM t"),
UnresolvedHint("REPARTITION", Seq(Literal(100), UnresolvedAttribute("c")),
UnresolvedHint("COALESCE", Seq(Literal(50)),
table("t").select(star()))))
comparePlans(
parsePlan("SELECT /*+ REPARTITION(100, c), BROADCASTJOIN(u), COALESCE(50) */ * FROM t"),
UnresolvedHint("REPARTITION", Seq(Literal(100), UnresolvedAttribute("c")),
UnresolvedHint("BROADCASTJOIN", Seq($"u"),
UnresolvedHint("COALESCE", Seq(Literal(50)),
table("t").select(star())))))
comparePlans(
parsePlan(
"""
|SELECT
|/*+ REPARTITION(100, c), BROADCASTJOIN(u), COALESCE(50), REPARTITION(300, c) */
|* FROM t
""".stripMargin),
UnresolvedHint("REPARTITION", Seq(Literal(100), UnresolvedAttribute("c")),
UnresolvedHint("BROADCASTJOIN", Seq($"u"),
UnresolvedHint("COALESCE", Seq(Literal(50)),
UnresolvedHint("REPARTITION", Seq(Literal(300), UnresolvedAttribute("c")),
table("t").select(star()))))))
comparePlans(
parsePlan("SELECT /*+ REPARTITION_BY_RANGE(c) */ * FROM t"),
UnresolvedHint("REPARTITION_BY_RANGE", Seq(UnresolvedAttribute("c")),
table("t").select(star())))
comparePlans(
parsePlan("SELECT /*+ REPARTITION_BY_RANGE(100, c) */ * FROM t"),
UnresolvedHint("REPARTITION_BY_RANGE", Seq(Literal(100), UnresolvedAttribute("c")),
table("t").select(star())))
}
test("SPARK-20854: select hint syntax with expressions") {
comparePlans(
parsePlan("SELECT /*+ HINT1(a, array(1, 2, 3)) */ * from t"),
UnresolvedHint("HINT1", Seq($"a",
UnresolvedFunction("array", Literal(1) :: Literal(2) :: Literal(3) :: Nil, false)),
table("t").select(star())
)
)
comparePlans(
parsePlan("SELECT /*+ HINT1(a, 5, 'a', b) */ * from t"),
UnresolvedHint("HINT1", Seq($"a", Literal(5), Literal("a"), $"b"),
table("t").select(star())
)
)
comparePlans(
parsePlan("SELECT /*+ HINT1('a', (b, c), (1, 2)) */ * from t"),
UnresolvedHint("HINT1",
Seq(Literal("a"),
CreateStruct($"b" :: $"c" :: Nil),
CreateStruct(Literal(1) :: Literal(2) :: Nil)),
table("t").select(star())
)
)
}
test("SPARK-20854: multiple hints") {
comparePlans(
parsePlan("SELECT /*+ HINT1(a, 1) hint2(b, 2) */ * from t"),
UnresolvedHint("HINT1", Seq($"a", Literal(1)),
UnresolvedHint("hint2", Seq($"b", Literal(2)),
table("t").select(star())
)
)
)
comparePlans(
parsePlan("SELECT /*+ HINT1(a, 1),hint2(b, 2) */ * from t"),
UnresolvedHint("HINT1", Seq($"a", Literal(1)),
UnresolvedHint("hint2", Seq($"b", Literal(2)),
table("t").select(star())
)
)
)
comparePlans(
parsePlan("SELECT /*+ HINT1(a, 1) */ /*+ hint2(b, 2) */ * from t"),
UnresolvedHint("HINT1", Seq($"a", Literal(1)),
UnresolvedHint("hint2", Seq($"b", Literal(2)),
table("t").select(star())
)
)
)
comparePlans(
parsePlan("SELECT /*+ HINT1(a, 1), hint2(b, 2) */ /*+ hint3(c, 3) */ * from t"),
UnresolvedHint("HINT1", Seq($"a", Literal(1)),
UnresolvedHint("hint2", Seq($"b", Literal(2)),
UnresolvedHint("hint3", Seq($"c", Literal(3)),
table("t").select(star())
)
)
)
)
}
test("TRIM function") {
def assertTrimPlans(inputSQL: String, expectedExpression: Expression): Unit = {
comparePlans(
parsePlan(inputSQL),
Project(Seq(UnresolvedAlias(expectedExpression)), OneRowRelation())
)
}
intercept("select ltrim(both 'S' from 'SS abc S'", Some("PARSE_SYNTAX_ERROR"),
"Syntax error at or near 'from'") // expecting {')'
intercept("select rtrim(trailing 'S' from 'SS abc S'", Some("PARSE_SYNTAX_ERROR"),
"Syntax error at or near 'from'") // expecting {')'
assertTrimPlans(
"SELECT TRIM(BOTH '@$%&( )abc' FROM '@ $ % & ()abc ' )",
StringTrim(Literal("@ $ % & ()abc "), Some(Literal("@$%&( )abc")))
)
assertTrimPlans(
"SELECT TRIM(LEADING 'c []' FROM '[ ccccbcc ')",
StringTrimLeft(Literal("[ ccccbcc "), Some(Literal("c []")))
)
assertTrimPlans(
"SELECT TRIM(TRAILING 'c&^,.' FROM 'bc...,,,&&&ccc')",
StringTrimRight(Literal("bc...,,,&&&ccc"), Some(Literal("c&^,.")))
)
assertTrimPlans(
"SELECT TRIM(BOTH FROM ' bunch o blanks ')",
StringTrim(Literal(" bunch o blanks "), None)
)
assertTrimPlans(
"SELECT TRIM(LEADING FROM ' bunch o blanks ')",
StringTrimLeft(Literal(" bunch o blanks "), None)
)
assertTrimPlans(
"SELECT TRIM(TRAILING FROM ' bunch o blanks ')",
StringTrimRight(Literal(" bunch o blanks "), None)
)
assertTrimPlans(
"SELECT TRIM('xyz' FROM 'yxTomxx')",
StringTrim(Literal("yxTomxx"), Some(Literal("xyz")))