-
Notifications
You must be signed in to change notification settings - Fork 28k
/
DDLParserSuite.scala
1526 lines (1380 loc) · 59.2 KB
/
DDLParserSuite.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.execution.command
import java.net.URI
import java.util.Locale
import scala.reflect.{classTag, ClassTag}
import org.apache.spark.sql.{AnalysisException, SaveMode}
import org.apache.spark.sql.catalyst.TableIdentifier
import org.apache.spark.sql.catalyst.analysis.{AnalysisTest, UnresolvedAttribute}
import org.apache.spark.sql.catalyst.catalog._
import org.apache.spark.sql.catalyst.dsl.expressions._
import org.apache.spark.sql.catalyst.dsl.plans
import org.apache.spark.sql.catalyst.dsl.plans.DslLogicalPlan
import org.apache.spark.sql.catalyst.expressions.JsonTuple
import org.apache.spark.sql.catalyst.parser.ParseException
import org.apache.spark.sql.catalyst.plans.logical.{Generate, InsertIntoDir, LogicalPlan, Project, ScriptTransformation}
import org.apache.spark.sql.execution.SparkSqlParser
import org.apache.spark.sql.execution.datasources.CreateTable
import org.apache.spark.sql.internal.{HiveSerDe, SQLConf}
import org.apache.spark.sql.test.SharedSparkSession
import org.apache.spark.sql.types.{IntegerType, StructField, StructType}
class DDLParserSuite extends AnalysisTest with SharedSparkSession {
private lazy val parser = new SparkSqlParser(new SQLConf)
private def assertUnsupported(sql: String, containsThesePhrases: Seq[String] = Seq()): Unit = {
val e = intercept[ParseException] {
parser.parsePlan(sql)
}
assert(e.getMessage.toLowerCase(Locale.ROOT).contains("operation not allowed"))
containsThesePhrases.foreach { p =>
assert(e.getMessage.toLowerCase(Locale.ROOT).contains(p.toLowerCase(Locale.ROOT)))
}
}
private def intercept(sqlCommand: String, messages: String*): Unit =
interceptParseException(parser.parsePlan)(sqlCommand, messages: _*)
private def parseAs[T: ClassTag](query: String): T = {
parser.parsePlan(query) match {
case t: T => t
case other =>
fail(s"Expected to parse ${classTag[T].runtimeClass} from query," +
s"got ${other.getClass.getName}: $query")
}
}
private def compareTransformQuery(sql: String, expected: LogicalPlan): Unit = {
val plan = parser.parsePlan(sql).asInstanceOf[ScriptTransformation].copy(ioschema = null)
comparePlans(plan, expected, checkAnalysis = false)
}
private def extractTableDesc(sql: String): (CatalogTable, Boolean) = {
parser.parsePlan(sql).collect {
case CreateTable(tableDesc, mode, _) => (tableDesc, mode == SaveMode.Ignore)
}.head
}
test("create database") {
val sql =
"""
|CREATE DATABASE IF NOT EXISTS database_name
|WITH DBPROPERTIES ('a'='a', 'b'='b', 'c'='c')
|COMMENT 'database_comment' LOCATION '/home/user/db'
""".stripMargin
val parsed = parser.parsePlan(sql)
val expected = CreateDatabaseCommand(
"database_name",
ifNotExists = true,
Some("/home/user/db"),
Some("database_comment"),
Map("a" -> "a", "b" -> "b", "c" -> "c"))
comparePlans(parsed, expected)
}
test("create database -- check duplicates") {
def createDatabase(duplicateClause: String): String = {
s"""
|CREATE DATABASE IF NOT EXISTS database_name
|$duplicateClause
|$duplicateClause
""".stripMargin
}
val sql1 = createDatabase("COMMENT 'database_comment'")
val sql2 = createDatabase("LOCATION '/home/user/db'")
val sql3 = createDatabase("WITH DBPROPERTIES ('a'='a', 'b'='b', 'c'='c')")
intercept(sql1, "Found duplicate clauses: COMMENT")
intercept(sql2, "Found duplicate clauses: LOCATION")
intercept(sql3, "Found duplicate clauses: WITH DBPROPERTIES")
}
test("create database - property values must be set") {
assertUnsupported(
sql = "CREATE DATABASE my_db WITH DBPROPERTIES('key_without_value', 'key_with_value'='x')",
containsThesePhrases = Seq("key_without_value"))
}
test("drop database") {
val sql1 = "DROP DATABASE IF EXISTS database_name RESTRICT"
val sql2 = "DROP DATABASE IF EXISTS database_name CASCADE"
val sql3 = "DROP SCHEMA IF EXISTS database_name RESTRICT"
val sql4 = "DROP SCHEMA IF EXISTS database_name CASCADE"
// The default is restrict=true
val sql5 = "DROP DATABASE IF EXISTS database_name"
// The default is ifExists=false
val sql6 = "DROP DATABASE database_name"
val sql7 = "DROP DATABASE database_name CASCADE"
val parsed1 = parser.parsePlan(sql1)
val parsed2 = parser.parsePlan(sql2)
val parsed3 = parser.parsePlan(sql3)
val parsed4 = parser.parsePlan(sql4)
val parsed5 = parser.parsePlan(sql5)
val parsed6 = parser.parsePlan(sql6)
val parsed7 = parser.parsePlan(sql7)
val expected1 = DropDatabaseCommand(
"database_name",
ifExists = true,
cascade = false)
val expected2 = DropDatabaseCommand(
"database_name",
ifExists = true,
cascade = true)
val expected3 = DropDatabaseCommand(
"database_name",
ifExists = false,
cascade = false)
val expected4 = DropDatabaseCommand(
"database_name",
ifExists = false,
cascade = true)
comparePlans(parsed1, expected1)
comparePlans(parsed2, expected2)
comparePlans(parsed3, expected1)
comparePlans(parsed4, expected2)
comparePlans(parsed5, expected1)
comparePlans(parsed6, expected3)
comparePlans(parsed7, expected4)
}
test("alter database set dbproperties") {
// ALTER (DATABASE|SCHEMA) database_name SET DBPROPERTIES (property_name=property_value, ...)
val sql1 = "ALTER DATABASE database_name SET DBPROPERTIES ('a'='a', 'b'='b', 'c'='c')"
val sql2 = "ALTER SCHEMA database_name SET DBPROPERTIES ('a'='a')"
val parsed1 = parser.parsePlan(sql1)
val parsed2 = parser.parsePlan(sql2)
val expected1 = AlterDatabasePropertiesCommand(
"database_name",
Map("a" -> "a", "b" -> "b", "c" -> "c"))
val expected2 = AlterDatabasePropertiesCommand(
"database_name",
Map("a" -> "a"))
comparePlans(parsed1, expected1)
comparePlans(parsed2, expected2)
}
test("alter database - property values must be set") {
assertUnsupported(
sql = "ALTER DATABASE my_db SET DBPROPERTIES('key_without_value', 'key_with_value'='x')",
containsThesePhrases = Seq("key_without_value"))
}
test("alter database set location") {
// ALTER (DATABASE|SCHEMA) database_name SET LOCATION
val sql1 = "ALTER DATABASE database_name SET LOCATION '/home/user/db'"
val parsed1 = parser.parsePlan(sql1)
val expected1 = AlterDatabaseSetLocationCommand("database_name", "/home/user/db")
comparePlans(parsed1, expected1)
}
test("describe database") {
// DESCRIBE DATABASE [EXTENDED] db_name;
val sql1 = "DESCRIBE DATABASE EXTENDED db_name"
val sql2 = "DESCRIBE DATABASE db_name"
val parsed1 = parser.parsePlan(sql1)
val parsed2 = parser.parsePlan(sql2)
val expected1 = DescribeDatabaseCommand(
"db_name",
extended = true)
val expected2 = DescribeDatabaseCommand(
"db_name",
extended = false)
comparePlans(parsed1, expected1)
comparePlans(parsed2, expected2)
}
test("create function") {
val sql1 =
"""
|CREATE TEMPORARY FUNCTION helloworld as
|'com.matthewrathbone.example.SimpleUDFExample' USING JAR '/path/to/jar1',
|JAR '/path/to/jar2'
""".stripMargin
val sql2 =
"""
|CREATE FUNCTION hello.world as
|'com.matthewrathbone.example.SimpleUDFExample' USING ARCHIVE '/path/to/archive',
|FILE '/path/to/file'
""".stripMargin
val sql3 =
"""
|CREATE OR REPLACE TEMPORARY FUNCTION helloworld3 as
|'com.matthewrathbone.example.SimpleUDFExample' USING JAR '/path/to/jar1',
|JAR '/path/to/jar2'
""".stripMargin
val sql4 =
"""
|CREATE OR REPLACE FUNCTION hello.world1 as
|'com.matthewrathbone.example.SimpleUDFExample' USING ARCHIVE '/path/to/archive',
|FILE '/path/to/file'
""".stripMargin
val sql5 =
"""
|CREATE FUNCTION IF NOT EXISTS hello.world2 as
|'com.matthewrathbone.example.SimpleUDFExample' USING ARCHIVE '/path/to/archive',
|FILE '/path/to/file'
""".stripMargin
val parsed1 = parser.parsePlan(sql1)
val parsed2 = parser.parsePlan(sql2)
val parsed3 = parser.parsePlan(sql3)
val parsed4 = parser.parsePlan(sql4)
val parsed5 = parser.parsePlan(sql5)
val expected1 = CreateFunctionCommand(
None,
"helloworld",
"com.matthewrathbone.example.SimpleUDFExample",
Seq(
FunctionResource(FunctionResourceType.fromString("jar"), "/path/to/jar1"),
FunctionResource(FunctionResourceType.fromString("jar"), "/path/to/jar2")),
isTemp = true, ignoreIfExists = false, replace = false)
val expected2 = CreateFunctionCommand(
Some("hello"),
"world",
"com.matthewrathbone.example.SimpleUDFExample",
Seq(
FunctionResource(FunctionResourceType.fromString("archive"), "/path/to/archive"),
FunctionResource(FunctionResourceType.fromString("file"), "/path/to/file")),
isTemp = false, ignoreIfExists = false, replace = false)
val expected3 = CreateFunctionCommand(
None,
"helloworld3",
"com.matthewrathbone.example.SimpleUDFExample",
Seq(
FunctionResource(FunctionResourceType.fromString("jar"), "/path/to/jar1"),
FunctionResource(FunctionResourceType.fromString("jar"), "/path/to/jar2")),
isTemp = true, ignoreIfExists = false, replace = true)
val expected4 = CreateFunctionCommand(
Some("hello"),
"world1",
"com.matthewrathbone.example.SimpleUDFExample",
Seq(
FunctionResource(FunctionResourceType.fromString("archive"), "/path/to/archive"),
FunctionResource(FunctionResourceType.fromString("file"), "/path/to/file")),
isTemp = false, ignoreIfExists = false, replace = true)
val expected5 = CreateFunctionCommand(
Some("hello"),
"world2",
"com.matthewrathbone.example.SimpleUDFExample",
Seq(
FunctionResource(FunctionResourceType.fromString("archive"), "/path/to/archive"),
FunctionResource(FunctionResourceType.fromString("file"), "/path/to/file")),
isTemp = false, ignoreIfExists = true, replace = false)
comparePlans(parsed1, expected1)
comparePlans(parsed2, expected2)
comparePlans(parsed3, expected3)
comparePlans(parsed4, expected4)
comparePlans(parsed5, expected5)
}
test("drop function") {
val sql1 = "DROP TEMPORARY FUNCTION helloworld"
val sql2 = "DROP TEMPORARY FUNCTION IF EXISTS helloworld"
val sql3 = "DROP FUNCTION hello.world"
val sql4 = "DROP FUNCTION IF EXISTS hello.world"
val parsed1 = parser.parsePlan(sql1)
val parsed2 = parser.parsePlan(sql2)
val parsed3 = parser.parsePlan(sql3)
val parsed4 = parser.parsePlan(sql4)
val expected1 = DropFunctionCommand(
None,
"helloworld",
ifExists = false,
isTemp = true)
val expected2 = DropFunctionCommand(
None,
"helloworld",
ifExists = true,
isTemp = true)
val expected3 = DropFunctionCommand(
Some("hello"),
"world",
ifExists = false,
isTemp = false)
val expected4 = DropFunctionCommand(
Some("hello"),
"world",
ifExists = true,
isTemp = false)
comparePlans(parsed1, expected1)
comparePlans(parsed2, expected2)
comparePlans(parsed3, expected3)
comparePlans(parsed4, expected4)
}
test("create hive table - table file format") {
val allSources = Seq("parquet", "parquetfile", "orc", "orcfile", "avro", "avrofile",
"sequencefile", "rcfile", "textfile")
allSources.foreach { s =>
val query = s"CREATE TABLE my_tab STORED AS $s"
val ct = parseAs[CreateTable](query)
val hiveSerde = HiveSerDe.sourceToSerDe(s)
assert(hiveSerde.isDefined)
assert(ct.tableDesc.storage.serde ==
hiveSerde.get.serde.orElse(Some("org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe")))
assert(ct.tableDesc.storage.inputFormat == hiveSerde.get.inputFormat)
assert(ct.tableDesc.storage.outputFormat == hiveSerde.get.outputFormat)
}
}
test("create hive table - row format and table file format") {
val createTableStart = "CREATE TABLE my_tab ROW FORMAT"
val fileFormat = s"STORED AS INPUTFORMAT 'inputfmt' OUTPUTFORMAT 'outputfmt'"
val query1 = s"$createTableStart SERDE 'anything' $fileFormat"
val query2 = s"$createTableStart DELIMITED FIELDS TERMINATED BY ' ' $fileFormat"
// No conflicting serdes here, OK
val parsed1 = parseAs[CreateTable](query1)
assert(parsed1.tableDesc.storage.serde == Some("anything"))
assert(parsed1.tableDesc.storage.inputFormat == Some("inputfmt"))
assert(parsed1.tableDesc.storage.outputFormat == Some("outputfmt"))
val parsed2 = parseAs[CreateTable](query2)
assert(parsed2.tableDesc.storage.serde ==
Some("org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe"))
assert(parsed2.tableDesc.storage.inputFormat == Some("inputfmt"))
assert(parsed2.tableDesc.storage.outputFormat == Some("outputfmt"))
}
test("create hive table - row format serde and generic file format") {
val allSources = Seq("parquet", "orc", "avro", "sequencefile", "rcfile", "textfile")
val supportedSources = Set("sequencefile", "rcfile", "textfile")
allSources.foreach { s =>
val query = s"CREATE TABLE my_tab ROW FORMAT SERDE 'anything' STORED AS $s"
if (supportedSources.contains(s)) {
val ct = parseAs[CreateTable](query)
val hiveSerde = HiveSerDe.sourceToSerDe(s)
assert(hiveSerde.isDefined)
assert(ct.tableDesc.storage.serde == Some("anything"))
assert(ct.tableDesc.storage.inputFormat == hiveSerde.get.inputFormat)
assert(ct.tableDesc.storage.outputFormat == hiveSerde.get.outputFormat)
} else {
assertUnsupported(query, Seq("row format serde", "incompatible", s))
}
}
}
test("create hive table - row format delimited and generic file format") {
val allSources = Seq("parquet", "orc", "avro", "sequencefile", "rcfile", "textfile")
val supportedSources = Set("textfile")
allSources.foreach { s =>
val query = s"CREATE TABLE my_tab ROW FORMAT DELIMITED FIELDS TERMINATED BY ' ' STORED AS $s"
if (supportedSources.contains(s)) {
val ct = parseAs[CreateTable](query)
val hiveSerde = HiveSerDe.sourceToSerDe(s)
assert(hiveSerde.isDefined)
assert(ct.tableDesc.storage.serde ==
hiveSerde.get.serde.orElse(Some("org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe")))
assert(ct.tableDesc.storage.inputFormat == hiveSerde.get.inputFormat)
assert(ct.tableDesc.storage.outputFormat == hiveSerde.get.outputFormat)
} else {
assertUnsupported(query, Seq("row format delimited", "only compatible with 'textfile'", s))
}
}
}
test("create hive external table - location must be specified") {
assertUnsupported(
sql = "CREATE EXTERNAL TABLE my_tab",
containsThesePhrases = Seq("create external table", "location"))
val query = "CREATE EXTERNAL TABLE my_tab LOCATION '/something/anything'"
val ct = parseAs[CreateTable](query)
assert(ct.tableDesc.tableType == CatalogTableType.EXTERNAL)
assert(ct.tableDesc.storage.locationUri == Some(new URI("/something/anything")))
}
test("create hive table - property values must be set") {
assertUnsupported(
sql = "CREATE TABLE my_tab TBLPROPERTIES('key_without_value', 'key_with_value'='x')",
containsThesePhrases = Seq("key_without_value"))
assertUnsupported(
sql = "CREATE TABLE my_tab ROW FORMAT SERDE 'serde' " +
"WITH SERDEPROPERTIES('key_without_value', 'key_with_value'='x')",
containsThesePhrases = Seq("key_without_value"))
}
test("create hive table - location implies external") {
val query = "CREATE TABLE my_tab LOCATION '/something/anything'"
val ct = parseAs[CreateTable](query)
assert(ct.tableDesc.tableType == CatalogTableType.EXTERNAL)
assert(ct.tableDesc.storage.locationUri == Some(new URI("/something/anything")))
}
test("Duplicate clauses - create hive table") {
def createTableHeader(duplicateClause: String): String = {
s"CREATE TABLE my_tab(a INT, b STRING) STORED AS parquet $duplicateClause $duplicateClause"
}
intercept(createTableHeader("TBLPROPERTIES('test' = 'test2')"),
"Found duplicate clauses: TBLPROPERTIES")
intercept(createTableHeader("LOCATION '/tmp/file'"),
"Found duplicate clauses: LOCATION")
intercept(createTableHeader("COMMENT 'a table'"),
"Found duplicate clauses: COMMENT")
intercept(createTableHeader("CLUSTERED BY(b) INTO 256 BUCKETS"),
"Found duplicate clauses: CLUSTERED BY")
intercept(createTableHeader("PARTITIONED BY (k int)"),
"Found duplicate clauses: PARTITIONED BY")
intercept(createTableHeader("STORED AS parquet"),
"Found duplicate clauses: STORED AS/BY")
intercept(
createTableHeader("ROW FORMAT SERDE 'parquet.hive.serde.ParquetHiveSerDe'"),
"Found duplicate clauses: ROW FORMAT")
}
test("insert overwrite directory") {
val v1 = "INSERT OVERWRITE DIRECTORY '/tmp/file' USING parquet SELECT 1 as a"
parser.parsePlan(v1) match {
case InsertIntoDir(_, storage, provider, query, overwrite) =>
assert(storage.locationUri.isDefined && storage.locationUri.get.toString == "/tmp/file")
case other =>
fail(s"Expected to parse ${classOf[InsertIntoDataSourceDirCommand].getClass.getName}" +
" from query," + s" got ${other.getClass.getName}: $v1")
}
val v2 = "INSERT OVERWRITE DIRECTORY USING parquet SELECT 1 as a"
val e2 = intercept[ParseException] {
parser.parsePlan(v2)
}
assert(e2.message.contains(
"Directory path and 'path' in OPTIONS should be specified one, but not both"))
val v3 =
"""
| INSERT OVERWRITE DIRECTORY USING json
| OPTIONS ('path' '/tmp/file', a 1, b 0.1, c TRUE)
| SELECT 1 as a
""".stripMargin
parser.parsePlan(v3) match {
case InsertIntoDir(_, storage, provider, query, overwrite) =>
assert(storage.locationUri.isDefined && provider == Some("json"))
assert(storage.properties.get("a") == Some("1"))
assert(storage.properties.get("b") == Some("0.1"))
assert(storage.properties.get("c") == Some("true"))
assert(!storage.properties.contains("abc"))
assert(!storage.properties.contains("path"))
case other =>
fail(s"Expected to parse ${classOf[InsertIntoDataSourceDirCommand].getClass.getName}" +
" from query," + s"got ${other.getClass.getName}: $v1")
}
val v4 =
"""
| INSERT OVERWRITE DIRECTORY '/tmp/file' USING json
| OPTIONS ('path' '/tmp/file', a 1, b 0.1, c TRUE)
| SELECT 1 as a
""".stripMargin
val e4 = intercept[ParseException] {
parser.parsePlan(v4)
}
assert(e4.message.contains(
"Directory path and 'path' in OPTIONS should be specified one, but not both"))
}
// ALTER TABLE table_name RENAME TO new_table_name;
// ALTER VIEW view_name RENAME TO new_view_name;
test("alter table/view: rename table/view") {
val sql_table = "ALTER TABLE table_name RENAME TO new_table_name"
val sql_view = sql_table.replace("TABLE", "VIEW")
val parsed_table = parser.parsePlan(sql_table)
val parsed_view = parser.parsePlan(sql_view)
val expected_table = AlterTableRenameCommand(
TableIdentifier("table_name"),
TableIdentifier("new_table_name"),
isView = false)
val expected_view = AlterTableRenameCommand(
TableIdentifier("table_name"),
TableIdentifier("new_table_name"),
isView = true)
comparePlans(parsed_table, expected_table)
comparePlans(parsed_view, expected_view)
}
test("alter table: rename table with database") {
val query = "ALTER TABLE db1.tbl RENAME TO db1.tbl2"
val plan = parseAs[AlterTableRenameCommand](query)
assert(plan.oldName == TableIdentifier("tbl", Some("db1")))
assert(plan.newName == TableIdentifier("tbl2", Some("db1")))
}
test("alter table - property values must be set") {
assertUnsupported(
sql = "ALTER TABLE my_tab SET TBLPROPERTIES('key_without_value', 'key_with_value'='x')",
containsThesePhrases = Seq("key_without_value"))
}
test("alter table unset properties - property values must NOT be set") {
assertUnsupported(
sql = "ALTER TABLE my_tab UNSET TBLPROPERTIES('key_without_value', 'key_with_value'='x')",
containsThesePhrases = Seq("key_with_value"))
}
test("alter table: SerDe properties") {
val sql1 = "ALTER TABLE table_name SET SERDE 'org.apache.class'"
val sql2 =
"""
|ALTER TABLE table_name SET SERDE 'org.apache.class'
|WITH SERDEPROPERTIES ('columns'='foo,bar', 'field.delim' = ',')
""".stripMargin
val sql3 =
"""
|ALTER TABLE table_name SET SERDEPROPERTIES ('columns'='foo,bar',
|'field.delim' = ',')
""".stripMargin
val sql4 =
"""
|ALTER TABLE table_name PARTITION (test=1, dt='2008-08-08',
|country='us') SET SERDE 'org.apache.class' WITH SERDEPROPERTIES ('columns'='foo,bar',
|'field.delim' = ',')
""".stripMargin
val sql5 =
"""
|ALTER TABLE table_name PARTITION (test=1, dt='2008-08-08',
|country='us') SET SERDEPROPERTIES ('columns'='foo,bar', 'field.delim' = ',')
""".stripMargin
val parsed1 = parser.parsePlan(sql1)
val parsed2 = parser.parsePlan(sql2)
val parsed3 = parser.parsePlan(sql3)
val parsed4 = parser.parsePlan(sql4)
val parsed5 = parser.parsePlan(sql5)
val tableIdent = TableIdentifier("table_name", None)
val expected1 = AlterTableSerDePropertiesCommand(
tableIdent, Some("org.apache.class"), None, None)
val expected2 = AlterTableSerDePropertiesCommand(
tableIdent,
Some("org.apache.class"),
Some(Map("columns" -> "foo,bar", "field.delim" -> ",")),
None)
val expected3 = AlterTableSerDePropertiesCommand(
tableIdent, None, Some(Map("columns" -> "foo,bar", "field.delim" -> ",")), None)
val expected4 = AlterTableSerDePropertiesCommand(
tableIdent,
Some("org.apache.class"),
Some(Map("columns" -> "foo,bar", "field.delim" -> ",")),
Some(Map("test" -> "1", "dt" -> "2008-08-08", "country" -> "us")))
val expected5 = AlterTableSerDePropertiesCommand(
tableIdent,
None,
Some(Map("columns" -> "foo,bar", "field.delim" -> ",")),
Some(Map("test" -> "1", "dt" -> "2008-08-08", "country" -> "us")))
comparePlans(parsed1, expected1)
comparePlans(parsed2, expected2)
comparePlans(parsed3, expected3)
comparePlans(parsed4, expected4)
comparePlans(parsed5, expected5)
}
test("alter table - SerDe property values must be set") {
assertUnsupported(
sql = "ALTER TABLE my_tab SET SERDE 'serde' " +
"WITH SERDEPROPERTIES('key_without_value', 'key_with_value'='x')",
containsThesePhrases = Seq("key_without_value"))
}
// ALTER TABLE table_name ADD [IF NOT EXISTS] PARTITION partition_spec
// [LOCATION 'location1'] partition_spec [LOCATION 'location2'] ...;
test("alter table: add partition") {
val sql1 =
"""
|ALTER TABLE table_name ADD IF NOT EXISTS PARTITION
|(dt='2008-08-08', country='us') LOCATION 'location1' PARTITION
|(dt='2009-09-09', country='uk')
""".stripMargin
val sql2 = "ALTER TABLE table_name ADD PARTITION (dt='2008-08-08') LOCATION 'loc'"
val parsed1 = parser.parsePlan(sql1)
val parsed2 = parser.parsePlan(sql2)
val expected1 = AlterTableAddPartitionCommand(
TableIdentifier("table_name", None),
Seq(
(Map("dt" -> "2008-08-08", "country" -> "us"), Some("location1")),
(Map("dt" -> "2009-09-09", "country" -> "uk"), None)),
ifNotExists = true)
val expected2 = AlterTableAddPartitionCommand(
TableIdentifier("table_name", None),
Seq((Map("dt" -> "2008-08-08"), Some("loc"))),
ifNotExists = false)
comparePlans(parsed1, expected1)
comparePlans(parsed2, expected2)
}
test("alter table: recover partitions") {
val sql = "ALTER TABLE table_name RECOVER PARTITIONS"
val parsed = parser.parsePlan(sql)
val expected = AlterTableRecoverPartitionsCommand(
TableIdentifier("table_name", None))
comparePlans(parsed, expected)
}
test("alter view: add partition (not supported)") {
assertUnsupported(
"""
|ALTER VIEW view_name ADD IF NOT EXISTS PARTITION
|(dt='2008-08-08', country='us') PARTITION
|(dt='2009-09-09', country='uk')
""".stripMargin)
}
test("alter table: rename partition") {
val sql =
"""
|ALTER TABLE table_name PARTITION (dt='2008-08-08', country='us')
|RENAME TO PARTITION (dt='2008-09-09', country='uk')
""".stripMargin
val parsed = parser.parsePlan(sql)
val expected = AlterTableRenamePartitionCommand(
TableIdentifier("table_name", None),
Map("dt" -> "2008-08-08", "country" -> "us"),
Map("dt" -> "2008-09-09", "country" -> "uk"))
comparePlans(parsed, expected)
}
test("alter table: exchange partition (not supported)") {
assertUnsupported(
"""
|ALTER TABLE table_name_1 EXCHANGE PARTITION
|(dt='2008-08-08', country='us') WITH TABLE table_name_2
""".stripMargin)
}
// ALTER TABLE table_name DROP [IF EXISTS] PARTITION spec1[, PARTITION spec2, ...]
// ALTER VIEW table_name DROP [IF EXISTS] PARTITION spec1[, PARTITION spec2, ...]
test("alter table/view: drop partitions") {
val sql1_table =
"""
|ALTER TABLE table_name DROP IF EXISTS PARTITION
|(dt='2008-08-08', country='us'), PARTITION (dt='2009-09-09', country='uk')
""".stripMargin
val sql2_table =
"""
|ALTER TABLE table_name DROP PARTITION
|(dt='2008-08-08', country='us'), PARTITION (dt='2009-09-09', country='uk')
""".stripMargin
val sql1_view = sql1_table.replace("TABLE", "VIEW")
val sql2_view = sql2_table.replace("TABLE", "VIEW")
val parsed1_table = parser.parsePlan(sql1_table)
val parsed2_table = parser.parsePlan(sql2_table)
val parsed1_purge = parser.parsePlan(sql1_table + " PURGE")
assertUnsupported(sql1_view)
assertUnsupported(sql2_view)
val tableIdent = TableIdentifier("table_name", None)
val expected1_table = AlterTableDropPartitionCommand(
tableIdent,
Seq(
Map("dt" -> "2008-08-08", "country" -> "us"),
Map("dt" -> "2009-09-09", "country" -> "uk")),
ifExists = true,
purge = false,
retainData = false)
val expected2_table = expected1_table.copy(ifExists = false)
val expected1_purge = expected1_table.copy(purge = true)
comparePlans(parsed1_table, expected1_table)
comparePlans(parsed2_table, expected2_table)
comparePlans(parsed1_purge, expected1_purge)
}
test("alter table: archive partition (not supported)") {
assertUnsupported("ALTER TABLE table_name ARCHIVE PARTITION (dt='2008-08-08', country='us')")
}
test("alter table: unarchive partition (not supported)") {
assertUnsupported("ALTER TABLE table_name UNARCHIVE PARTITION (dt='2008-08-08', country='us')")
}
test("alter table: set file format (not allowed)") {
assertUnsupported(
"ALTER TABLE table_name SET FILEFORMAT INPUTFORMAT 'test' OUTPUTFORMAT 'test'")
assertUnsupported(
"ALTER TABLE table_name PARTITION (dt='2008-08-08', country='us') " +
"SET FILEFORMAT PARQUET")
}
test("alter table: set partition location") {
val sql2 = "ALTER TABLE table_name PARTITION (dt='2008-08-08', country='us') " +
"SET LOCATION 'new location'"
val parsed2 = parser.parsePlan(sql2)
val tableIdent = TableIdentifier("table_name", None)
val expected2 = AlterTableSetLocationCommand(
tableIdent,
Some(Map("dt" -> "2008-08-08", "country" -> "us")),
"new location")
comparePlans(parsed2, expected2)
}
test("alter table: change column name/type/comment") {
val sql1 = "ALTER TABLE table_name CHANGE COLUMN col_old_name col_new_name INT"
val sql2 = "ALTER TABLE table_name CHANGE COLUMN col_name col_name INT COMMENT 'new_comment'"
val parsed1 = parser.parsePlan(sql1)
val parsed2 = parser.parsePlan(sql2)
val tableIdent = TableIdentifier("table_name", None)
val expected1 = AlterTableChangeColumnCommand(
tableIdent,
"col_old_name",
StructField("col_new_name", IntegerType))
val expected2 = AlterTableChangeColumnCommand(
tableIdent,
"col_name",
StructField("col_name", IntegerType).withComment("new_comment"))
comparePlans(parsed1, expected1)
comparePlans(parsed2, expected2)
}
test("alter table: change column position (not supported)") {
assertUnsupported("ALTER TABLE table_name CHANGE COLUMN col_old_name col_new_name INT FIRST")
assertUnsupported(
"ALTER TABLE table_name CHANGE COLUMN col_old_name col_new_name INT AFTER other_col")
}
test("alter table: change column in partition spec") {
assertUnsupported("ALTER TABLE table_name PARTITION (a='1', a='2') CHANGE COLUMN a new_a INT")
}
test("alter table: touch (not supported)") {
assertUnsupported("ALTER TABLE table_name TOUCH")
assertUnsupported("ALTER TABLE table_name TOUCH PARTITION (dt='2008-08-08', country='us')")
}
test("alter table: compact (not supported)") {
assertUnsupported("ALTER TABLE table_name COMPACT 'compaction_type'")
assertUnsupported(
"""
|ALTER TABLE table_name PARTITION (dt='2008-08-08', country='us')
|COMPACT 'MAJOR'
""".stripMargin)
}
test("alter table: concatenate (not supported)") {
assertUnsupported("ALTER TABLE table_name CONCATENATE")
assertUnsupported(
"ALTER TABLE table_name PARTITION (dt='2008-08-08', country='us') CONCATENATE")
}
test("alter table: cluster by (not supported)") {
assertUnsupported(
"ALTER TABLE table_name CLUSTERED BY (col_name) SORTED BY (col2_name) INTO 3 BUCKETS")
assertUnsupported("ALTER TABLE table_name CLUSTERED BY (col_name) INTO 3 BUCKETS")
assertUnsupported("ALTER TABLE table_name NOT CLUSTERED")
assertUnsupported("ALTER TABLE table_name NOT SORTED")
}
test("alter table: skewed by (not supported)") {
assertUnsupported("ALTER TABLE table_name NOT SKEWED")
assertUnsupported("ALTER TABLE table_name NOT STORED AS DIRECTORIES")
assertUnsupported("ALTER TABLE table_name SET SKEWED LOCATION (col_name1=\"location1\"")
assertUnsupported("ALTER TABLE table_name SKEWED BY (key) ON (1,5,6) STORED AS DIRECTORIES")
}
test("alter table: replace columns (not allowed)") {
assertUnsupported(
"""
|ALTER TABLE table_name REPLACE COLUMNS (new_col1 INT
|COMMENT 'test_comment', new_col2 LONG COMMENT 'test_comment2') RESTRICT
""".stripMargin)
}
test("show tblproperties") {
val parsed1 = parser.parsePlan("SHOW TBLPROPERTIES tab1")
val expected1 = ShowTablePropertiesCommand(TableIdentifier("tab1", None), None)
val parsed2 = parser.parsePlan("SHOW TBLPROPERTIES tab1('propKey1')")
val expected2 = ShowTablePropertiesCommand(TableIdentifier("tab1", None), Some("propKey1"))
comparePlans(parsed1, expected1)
comparePlans(parsed2, expected2)
}
test("SPARK-14383: DISTRIBUTE and UNSET as non-keywords") {
val sql = "SELECT distribute, unset FROM x"
val parsed = parser.parsePlan(sql)
assert(parsed.isInstanceOf[Project])
}
test("duplicate keys in table properties") {
val e = intercept[ParseException] {
parser.parsePlan("ALTER TABLE dbx.tab1 SET TBLPROPERTIES ('key1' = '1', 'key1' = '2')")
}.getMessage
assert(e.contains("Found duplicate keys 'key1'"))
}
test("duplicate columns in partition specs") {
val e = intercept[ParseException] {
parser.parsePlan(
"ALTER TABLE dbx.tab1 PARTITION (a='1', a='2') RENAME TO PARTITION (a='100', a='200')")
}.getMessage
assert(e.contains("Found duplicate keys 'a'"))
}
test("empty values in non-optional partition specs") {
val e = intercept[ParseException] {
parser.parsePlan(
"SHOW PARTITIONS dbx.tab1 PARTITION (a='1', b)")
}.getMessage
assert(e.contains("Found an empty partition key 'b'"))
}
test("show columns") {
val sql1 = "SHOW COLUMNS FROM t1"
val sql2 = "SHOW COLUMNS IN db1.t1"
val sql3 = "SHOW COLUMNS FROM t1 IN db1"
val sql4 = "SHOW COLUMNS FROM db1.t1 IN db2"
val parsed1 = parser.parsePlan(sql1)
val expected1 = ShowColumnsCommand(None, TableIdentifier("t1", None))
val parsed2 = parser.parsePlan(sql2)
val expected2 = ShowColumnsCommand(None, TableIdentifier("t1", Some("db1")))
val parsed3 = parser.parsePlan(sql3)
val expected3 = ShowColumnsCommand(Some("db1"), TableIdentifier("t1", None))
val parsed4 = parser.parsePlan(sql4)
val expected4 = ShowColumnsCommand(Some("db2"), TableIdentifier("t1", Some("db1")))
comparePlans(parsed1, expected1)
comparePlans(parsed2, expected2)
comparePlans(parsed3, expected3)
comparePlans(parsed4, expected4)
}
test("show partitions") {
val sql1 = "SHOW PARTITIONS t1"
val sql2 = "SHOW PARTITIONS db1.t1"
val sql3 = "SHOW PARTITIONS t1 PARTITION(partcol1='partvalue', partcol2='partvalue')"
val parsed1 = parser.parsePlan(sql1)
val expected1 =
ShowPartitionsCommand(TableIdentifier("t1", None), None)
val parsed2 = parser.parsePlan(sql2)
val expected2 =
ShowPartitionsCommand(TableIdentifier("t1", Some("db1")), None)
val expected3 =
ShowPartitionsCommand(TableIdentifier("t1", None),
Some(Map("partcol1" -> "partvalue", "partcol2" -> "partvalue")))
val parsed3 = parser.parsePlan(sql3)
comparePlans(parsed1, expected1)
comparePlans(parsed2, expected2)
comparePlans(parsed3, expected3)
}
test("support for other types in DBPROPERTIES") {
val sql =
"""
|CREATE DATABASE database_name
|LOCATION '/home/user/db'
|WITH DBPROPERTIES ('a'=1, 'b'=0.1, 'c'=TRUE)
""".stripMargin
val parsed = parser.parsePlan(sql)
val expected = CreateDatabaseCommand(
"database_name",
ifNotExists = false,
Some("/home/user/db"),
None,
Map("a" -> "1", "b" -> "0.1", "c" -> "true"))
comparePlans(parsed, expected)
}
test("Test CTAS #1") {
val s1 =
"""
|CREATE EXTERNAL TABLE IF NOT EXISTS mydb.page_view
|COMMENT 'This is the staging page view table'
|STORED AS RCFILE
|LOCATION '/user/external/page_view'
|TBLPROPERTIES ('p1'='v1', 'p2'='v2')
|AS SELECT * FROM src
""".stripMargin
val s2 =
"""
|CREATE EXTERNAL TABLE IF NOT EXISTS mydb.page_view
|STORED AS RCFILE
|COMMENT 'This is the staging page view table'
|TBLPROPERTIES ('p1'='v1', 'p2'='v2')
|LOCATION '/user/external/page_view'
|AS SELECT * FROM src
""".stripMargin
val s3 =
"""
|CREATE EXTERNAL TABLE IF NOT EXISTS mydb.page_view
|TBLPROPERTIES ('p1'='v1', 'p2'='v2')
|LOCATION '/user/external/page_view'
|STORED AS RCFILE
|COMMENT 'This is the staging page view table'
|AS SELECT * FROM src
""".stripMargin
checkParsing(s1)
checkParsing(s2)
checkParsing(s3)
def checkParsing(sql: String): Unit = {
val (desc, exists) = extractTableDesc(sql)
assert(exists)
assert(desc.identifier.database == Some("mydb"))
assert(desc.identifier.table == "page_view")
assert(desc.tableType == CatalogTableType.EXTERNAL)
assert(desc.storage.locationUri == Some(new URI("/user/external/page_view")))
assert(desc.schema.isEmpty) // will be populated later when the table is actually created
assert(desc.comment == Some("This is the staging page view table"))
// TODO will be SQLText
assert(desc.viewText.isEmpty)
assert(desc.viewDefaultDatabase.isEmpty)
assert(desc.viewQueryColumnNames.isEmpty)
assert(desc.partitionColumnNames.isEmpty)
assert(desc.storage.inputFormat == Some("org.apache.hadoop.hive.ql.io.RCFileInputFormat"))
assert(desc.storage.outputFormat == Some("org.apache.hadoop.hive.ql.io.RCFileOutputFormat"))
assert(desc.storage.serde ==
Some("org.apache.hadoop.hive.serde2.columnar.LazyBinaryColumnarSerDe"))
assert(desc.properties == Map("p1" -> "v1", "p2" -> "v2"))
}
}
test("Test CTAS #2") {
val s1 =
"""
|CREATE EXTERNAL TABLE IF NOT EXISTS mydb.page_view
|COMMENT 'This is the staging page view table'
|ROW FORMAT SERDE 'parquet.hive.serde.ParquetHiveSerDe'
| STORED AS
| INPUTFORMAT 'parquet.hive.DeprecatedParquetInputFormat'
| OUTPUTFORMAT 'parquet.hive.DeprecatedParquetOutputFormat'
|LOCATION '/user/external/page_view'
|TBLPROPERTIES ('p1'='v1', 'p2'='v2')
|AS SELECT * FROM src
""".stripMargin
val s2 =
"""
|CREATE EXTERNAL TABLE IF NOT EXISTS mydb.page_view
|LOCATION '/user/external/page_view'
|TBLPROPERTIES ('p1'='v1', 'p2'='v2')
|ROW FORMAT SERDE 'parquet.hive.serde.ParquetHiveSerDe'
| STORED AS
| INPUTFORMAT 'parquet.hive.DeprecatedParquetInputFormat'
| OUTPUTFORMAT 'parquet.hive.DeprecatedParquetOutputFormat'
|COMMENT 'This is the staging page view table'
|AS SELECT * FROM src
""".stripMargin
checkParsing(s1)
checkParsing(s2)
def checkParsing(sql: String): Unit = {
val (desc, exists) = extractTableDesc(sql)