/
DataSourceV2SQLSuite.scala
1745 lines (1469 loc) · 65.3 KB
/
DataSourceV2SQLSuite.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.connector
import scala.collection.JavaConverters._
import org.apache.spark.SparkException
import org.apache.spark.sql._
import org.apache.spark.sql.catalyst.analysis.{CannotReplaceMissingTableException, NamespaceAlreadyExistsException, NoSuchDatabaseException, NoSuchNamespaceException, NoSuchTableException, TableAlreadyExistsException}
import org.apache.spark.sql.connector.catalog._
import org.apache.spark.sql.connector.catalog.CatalogManager.SESSION_CATALOG_NAME
import org.apache.spark.sql.execution.datasources.v2.V2SessionCatalog
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.internal.SQLConf.V2_SESSION_CATALOG_IMPLEMENTATION
import org.apache.spark.sql.sources.SimpleScanSource
import org.apache.spark.sql.types.{BooleanType, LongType, StringType, StructType}
import org.apache.spark.sql.util.CaseInsensitiveStringMap
class DataSourceV2SQLSuite
extends InsertIntoTests(supportsDynamicOverwrite = true, includeSQLOnlyTests = true)
with AlterTableTests {
import org.apache.spark.sql.connector.catalog.CatalogV2Implicits._
private val v2Source = classOf[FakeV2Provider].getName
override protected val v2Format = v2Source
override protected val catalogAndNamespace = "testcat.ns1.ns2."
private def catalog(name: String): CatalogPlugin = {
spark.sessionState.catalogManager.catalog(name)
}
protected def doInsert(tableName: String, insert: DataFrame, mode: SaveMode): Unit = {
val tmpView = "tmp_view"
withTempView(tmpView) {
insert.createOrReplaceTempView(tmpView)
val overwrite = if (mode == SaveMode.Overwrite) "OVERWRITE" else "INTO"
sql(s"INSERT $overwrite TABLE $tableName SELECT * FROM $tmpView")
}
}
override def verifyTable(tableName: String, expected: DataFrame): Unit = {
checkAnswer(spark.table(tableName), expected)
}
override def getTableMetadata(tableName: String): Table = {
val nameParts = spark.sessionState.sqlParser.parseMultipartIdentifier(tableName)
val v2Catalog = catalog(nameParts.head).asTableCatalog
val namespace = nameParts.drop(1).init.toArray
v2Catalog.loadTable(Identifier.of(namespace, nameParts.last))
}
before {
spark.conf.set("spark.sql.catalog.testcat", classOf[InMemoryTableCatalog].getName)
spark.conf.set(
"spark.sql.catalog.testcat_atomic", classOf[StagingInMemoryTableCatalog].getName)
spark.conf.set("spark.sql.catalog.testcat2", classOf[InMemoryTableCatalog].getName)
spark.conf.set(
V2_SESSION_CATALOG_IMPLEMENTATION.key, classOf[InMemoryTableSessionCatalog].getName)
val df = spark.createDataFrame(Seq((1L, "a"), (2L, "b"), (3L, "c"))).toDF("id", "data")
df.createOrReplaceTempView("source")
val df2 = spark.createDataFrame(Seq((4L, "d"), (5L, "e"), (6L, "f"))).toDF("id", "data")
df2.createOrReplaceTempView("source2")
}
after {
spark.sessionState.catalog.reset()
spark.sessionState.catalogManager.reset()
spark.sessionState.conf.clear()
}
test("CreateTable: use v2 plan because catalog is set") {
spark.sql("CREATE TABLE testcat.table_name (id bigint, data string) USING foo")
val testCatalog = catalog("testcat").asTableCatalog
val table = testCatalog.loadTable(Identifier.of(Array(), "table_name"))
assert(table.name == "testcat.table_name")
assert(table.partitioning.isEmpty)
assert(table.properties == Map("provider" -> "foo").asJava)
assert(table.schema == new StructType().add("id", LongType).add("data", StringType))
val rdd = spark.sparkContext.parallelize(table.asInstanceOf[InMemoryTable].rows)
checkAnswer(spark.internalCreateDataFrame(rdd, table.schema), Seq.empty)
}
test("DescribeTable using v2 catalog") {
spark.sql("CREATE TABLE testcat.table_name (id bigint, data string)" +
" USING foo" +
" PARTITIONED BY (id)")
val descriptionDf = spark.sql("DESCRIBE TABLE testcat.table_name")
assert(descriptionDf.schema.map(field => (field.name, field.dataType)) ===
Seq(
("col_name", StringType),
("data_type", StringType),
("comment", StringType)))
val description = descriptionDf.collect()
assert(description === Seq(
Row("id", "bigint", ""),
Row("data", "string", "")))
}
test("DescribeTable with v2 catalog when table does not exist.") {
intercept[AnalysisException] {
spark.sql("DESCRIBE TABLE testcat.table_name")
}
}
test("DescribeTable extended using v2 catalog") {
spark.sql("CREATE TABLE testcat.table_name (id bigint, data string)" +
" USING foo" +
" PARTITIONED BY (id)" +
" TBLPROPERTIES ('bar'='baz')")
val descriptionDf = spark.sql("DESCRIBE TABLE EXTENDED testcat.table_name")
assert(descriptionDf.schema.map(field => (field.name, field.dataType))
=== Seq(
("col_name", StringType),
("data_type", StringType),
("comment", StringType)))
assert(descriptionDf.collect()
.map(_.toSeq)
.map(_.toArray.map(_.toString.trim)) === Array(
Array("id", "bigint", ""),
Array("data", "string", ""),
Array("", "", ""),
Array("Partitioning", "", ""),
Array("--------------", "", ""),
Array("Part 0", "id", ""),
Array("", "", ""),
Array("Table Property", "Value", ""),
Array("----------------", "-------", ""),
Array("bar", "baz", ""),
Array("provider", "foo", "")))
}
test("CreateTable: use v2 plan and session catalog when provider is v2") {
spark.sql(s"CREATE TABLE table_name (id bigint, data string) USING $v2Source")
val testCatalog = catalog(SESSION_CATALOG_NAME).asTableCatalog
val table = testCatalog.loadTable(Identifier.of(Array(), "table_name"))
assert(table.name == "default.table_name")
assert(table.partitioning.isEmpty)
assert(table.properties == Map("provider" -> v2Source).asJava)
assert(table.schema == new StructType().add("id", LongType).add("data", StringType))
val rdd = spark.sparkContext.parallelize(table.asInstanceOf[InMemoryTable].rows)
checkAnswer(spark.internalCreateDataFrame(rdd, table.schema), Seq.empty)
}
test("CreateTable: fail if table exists") {
spark.sql("CREATE TABLE testcat.table_name (id bigint, data string) USING foo")
val testCatalog = catalog("testcat").asTableCatalog
val table = testCatalog.loadTable(Identifier.of(Array(), "table_name"))
assert(table.name == "testcat.table_name")
assert(table.partitioning.isEmpty)
assert(table.properties == Map("provider" -> "foo").asJava)
assert(table.schema == new StructType().add("id", LongType).add("data", StringType))
// run a second create query that should fail
val exc = intercept[TableAlreadyExistsException] {
spark.sql("CREATE TABLE testcat.table_name (id bigint, data string, id2 bigint) USING bar")
}
assert(exc.getMessage.contains("table_name"))
// table should not have changed
val table2 = testCatalog.loadTable(Identifier.of(Array(), "table_name"))
assert(table2.name == "testcat.table_name")
assert(table2.partitioning.isEmpty)
assert(table2.properties == Map("provider" -> "foo").asJava)
assert(table2.schema == new StructType().add("id", LongType).add("data", StringType))
// check that the table is still empty
val rdd = spark.sparkContext.parallelize(table.asInstanceOf[InMemoryTable].rows)
checkAnswer(spark.internalCreateDataFrame(rdd, table.schema), Seq.empty)
}
test("CreateTable: if not exists") {
spark.sql(
"CREATE TABLE IF NOT EXISTS testcat.table_name (id bigint, data string) USING foo")
val testCatalog = catalog("testcat").asTableCatalog
val table = testCatalog.loadTable(Identifier.of(Array(), "table_name"))
assert(table.name == "testcat.table_name")
assert(table.partitioning.isEmpty)
assert(table.properties == Map("provider" -> "foo").asJava)
assert(table.schema == new StructType().add("id", LongType).add("data", StringType))
spark.sql("CREATE TABLE IF NOT EXISTS testcat.table_name (id bigint, data string) USING bar")
// table should not have changed
val table2 = testCatalog.loadTable(Identifier.of(Array(), "table_name"))
assert(table2.name == "testcat.table_name")
assert(table2.partitioning.isEmpty)
assert(table2.properties == Map("provider" -> "foo").asJava)
assert(table2.schema == new StructType().add("id", LongType).add("data", StringType))
// check that the table is still empty
val rdd2 = spark.sparkContext.parallelize(table.asInstanceOf[InMemoryTable].rows)
checkAnswer(spark.internalCreateDataFrame(rdd2, table.schema), Seq.empty)
}
test("CreateTable: use default catalog for v2 sources when default catalog is set") {
spark.conf.set(SQLConf.DEFAULT_CATALOG.key, "testcat")
spark.sql(s"CREATE TABLE table_name (id bigint, data string) USING foo")
val testCatalog = catalog("testcat").asTableCatalog
val table = testCatalog.loadTable(Identifier.of(Array(), "table_name"))
assert(table.name == "testcat.table_name")
assert(table.partitioning.isEmpty)
assert(table.properties == Map("provider" -> "foo").asJava)
assert(table.schema == new StructType().add("id", LongType).add("data", StringType))
// check that the table is empty
val rdd = spark.sparkContext.parallelize(table.asInstanceOf[InMemoryTable].rows)
checkAnswer(spark.internalCreateDataFrame(rdd, table.schema), Seq.empty)
}
test("CreateTableAsSelect: use v2 plan because catalog is set") {
val basicCatalog = catalog("testcat").asTableCatalog
val atomicCatalog = catalog("testcat_atomic").asTableCatalog
val basicIdentifier = "testcat.table_name"
val atomicIdentifier = "testcat_atomic.table_name"
Seq((basicCatalog, basicIdentifier), (atomicCatalog, atomicIdentifier)).foreach {
case (catalog, identifier) =>
spark.sql(s"CREATE TABLE $identifier USING foo AS SELECT id, data FROM source")
val table = catalog.loadTable(Identifier.of(Array(), "table_name"))
assert(table.name == identifier)
assert(table.partitioning.isEmpty)
assert(table.properties == Map("provider" -> "foo").asJava)
assert(table.schema == new StructType()
.add("id", LongType)
.add("data", StringType))
val rdd = spark.sparkContext.parallelize(table.asInstanceOf[InMemoryTable].rows)
checkAnswer(spark.internalCreateDataFrame(rdd, table.schema), spark.table("source"))
}
}
test("ReplaceTableAsSelect: basic v2 implementation.") {
val basicCatalog = catalog("testcat").asTableCatalog
val atomicCatalog = catalog("testcat_atomic").asTableCatalog
val basicIdentifier = "testcat.table_name"
val atomicIdentifier = "testcat_atomic.table_name"
Seq((basicCatalog, basicIdentifier), (atomicCatalog, atomicIdentifier)).foreach {
case (catalog, identifier) =>
spark.sql(s"CREATE TABLE $identifier USING foo AS SELECT id, data FROM source")
val originalTable = catalog.loadTable(Identifier.of(Array(), "table_name"))
spark.sql(s"REPLACE TABLE $identifier USING foo AS SELECT id FROM source")
val replacedTable = catalog.loadTable(Identifier.of(Array(), "table_name"))
assert(replacedTable != originalTable, "Table should have been replaced.")
assert(replacedTable.name == identifier)
assert(replacedTable.partitioning.isEmpty)
assert(replacedTable.properties == Map("provider" -> "foo").asJava)
assert(replacedTable.schema == new StructType().add("id", LongType))
val rdd = spark.sparkContext.parallelize(replacedTable.asInstanceOf[InMemoryTable].rows)
checkAnswer(
spark.internalCreateDataFrame(rdd, replacedTable.schema),
spark.table("source").select("id"))
}
}
test("ReplaceTableAsSelect: Non-atomic catalog drops the table if the write fails.") {
spark.sql("CREATE TABLE testcat.table_name USING foo AS SELECT id, data FROM source")
val testCatalog = catalog("testcat").asTableCatalog
val table = testCatalog.loadTable(Identifier.of(Array(), "table_name"))
assert(table.asInstanceOf[InMemoryTable].rows.nonEmpty)
intercept[Exception] {
spark.sql("REPLACE TABLE testcat.table_name" +
s" USING foo OPTIONS (`${InMemoryTable.SIMULATE_FAILED_WRITE_OPTION}`=true)" +
s" AS SELECT id FROM source")
}
assert(!testCatalog.tableExists(Identifier.of(Array(), "table_name")),
"Table should have been dropped as a result of the replace.")
}
test("ReplaceTableAsSelect: Non-atomic catalog drops the table permanently if the" +
" subsequent table creation fails.") {
spark.sql("CREATE TABLE testcat.table_name USING foo AS SELECT id, data FROM source")
val testCatalog = catalog("testcat").asTableCatalog
val table = testCatalog.loadTable(Identifier.of(Array(), "table_name"))
assert(table.asInstanceOf[InMemoryTable].rows.nonEmpty)
intercept[Exception] {
spark.sql("REPLACE TABLE testcat.table_name" +
s" USING foo" +
s" TBLPROPERTIES (`${InMemoryTableCatalog.SIMULATE_FAILED_CREATE_PROPERTY}`=true)" +
s" AS SELECT id FROM source")
}
assert(!testCatalog.tableExists(Identifier.of(Array(), "table_name")),
"Table should have been dropped and failed to be created.")
}
test("ReplaceTableAsSelect: Atomic catalog does not drop the table when replace fails.") {
spark.sql("CREATE TABLE testcat_atomic.table_name USING foo AS SELECT id, data FROM source")
val testCatalog = catalog("testcat_atomic").asTableCatalog
val table = testCatalog.loadTable(Identifier.of(Array(), "table_name"))
intercept[Exception] {
spark.sql("REPLACE TABLE testcat_atomic.table_name" +
s" USING foo OPTIONS (`${InMemoryTable.SIMULATE_FAILED_WRITE_OPTION}=true)" +
s" AS SELECT id FROM source")
}
var maybeReplacedTable = testCatalog.loadTable(Identifier.of(Array(), "table_name"))
assert(maybeReplacedTable === table, "Table should not have changed.")
intercept[Exception] {
spark.sql("REPLACE TABLE testcat_atomic.table_name" +
s" USING foo" +
s" TBLPROPERTIES (`${InMemoryTableCatalog.SIMULATE_FAILED_CREATE_PROPERTY}`=true)" +
s" AS SELECT id FROM source")
}
maybeReplacedTable = testCatalog.loadTable(Identifier.of(Array(), "table_name"))
assert(maybeReplacedTable === table, "Table should not have changed.")
}
test("ReplaceTable: Erases the table contents and changes the metadata.") {
spark.sql(s"CREATE TABLE testcat.table_name USING $v2Source AS SELECT id, data FROM source")
val testCatalog = catalog("testcat").asTableCatalog
val table = testCatalog.loadTable(Identifier.of(Array(), "table_name"))
assert(table.asInstanceOf[InMemoryTable].rows.nonEmpty)
spark.sql("REPLACE TABLE testcat.table_name (id bigint) USING foo")
val replaced = testCatalog.loadTable(Identifier.of(Array(), "table_name"))
assert(replaced.asInstanceOf[InMemoryTable].rows.isEmpty,
"Replaced table should have no rows after committing.")
assert(replaced.schema().fields.length === 1,
"Replaced table should have new schema.")
assert(replaced.schema().fields(0).name === "id",
"Replaced table should have new schema.")
}
test("ReplaceTableAsSelect: CREATE OR REPLACE new table has same behavior as CTAS.") {
Seq("testcat", "testcat_atomic").foreach { catalogName =>
spark.sql(
s"""
|CREATE TABLE $catalogName.created USING $v2Source
|AS SELECT id, data FROM source
""".stripMargin)
spark.sql(
s"""
|CREATE OR REPLACE TABLE $catalogName.replaced USING $v2Source
|AS SELECT id, data FROM source
""".stripMargin)
val testCatalog = catalog(catalogName).asTableCatalog
val createdTable = testCatalog.loadTable(Identifier.of(Array(), "created"))
val replacedTable = testCatalog.loadTable(Identifier.of(Array(), "replaced"))
assert(createdTable.asInstanceOf[InMemoryTable].rows ===
replacedTable.asInstanceOf[InMemoryTable].rows)
assert(createdTable.schema === replacedTable.schema)
}
}
test("ReplaceTableAsSelect: REPLACE TABLE throws exception if table does not exist.") {
Seq("testcat", "testcat_atomic").foreach { catalog =>
spark.sql(s"CREATE TABLE $catalog.created USING $v2Source AS SELECT id, data FROM source")
intercept[CannotReplaceMissingTableException] {
spark.sql(s"REPLACE TABLE $catalog.replaced USING $v2Source AS SELECT id, data FROM source")
}
}
}
test("ReplaceTableAsSelect: REPLACE TABLE throws exception if table is dropped before commit.") {
import InMemoryTableCatalog._
spark.sql(s"CREATE TABLE testcat_atomic.created USING $v2Source AS SELECT id, data FROM source")
intercept[CannotReplaceMissingTableException] {
spark.sql(s"REPLACE TABLE testcat_atomic.replaced" +
s" USING $v2Source" +
s" TBLPROPERTIES (`$SIMULATE_DROP_BEFORE_REPLACE_PROPERTY`=true)" +
s" AS SELECT id, data FROM source")
}
}
test("CreateTableAsSelect: use v2 plan and session catalog when provider is v2") {
spark.sql(s"CREATE TABLE table_name USING $v2Source AS SELECT id, data FROM source")
val testCatalog = catalog(SESSION_CATALOG_NAME).asTableCatalog
val table = testCatalog.loadTable(Identifier.of(Array(), "table_name"))
assert(table.name == "default.table_name")
assert(table.partitioning.isEmpty)
assert(table.properties == Map("provider" -> v2Source).asJava)
assert(table.schema == new StructType()
.add("id", LongType)
.add("data", StringType))
val rdd = spark.sparkContext.parallelize(table.asInstanceOf[InMemoryTable].rows)
checkAnswer(spark.internalCreateDataFrame(rdd, table.schema), spark.table("source"))
}
test("CreateTableAsSelect: fail if table exists") {
spark.sql("CREATE TABLE testcat.table_name USING foo AS SELECT id, data FROM source")
val testCatalog = catalog("testcat").asTableCatalog
val table = testCatalog.loadTable(Identifier.of(Array(), "table_name"))
assert(table.name == "testcat.table_name")
assert(table.partitioning.isEmpty)
assert(table.properties == Map("provider" -> "foo").asJava)
assert(table.schema == new StructType()
.add("id", LongType)
.add("data", StringType))
val rdd = spark.sparkContext.parallelize(table.asInstanceOf[InMemoryTable].rows)
checkAnswer(spark.internalCreateDataFrame(rdd, table.schema), spark.table("source"))
// run a second CTAS query that should fail
val exc = intercept[TableAlreadyExistsException] {
spark.sql(
"CREATE TABLE testcat.table_name USING bar AS SELECT id, data, id as id2 FROM source2")
}
assert(exc.getMessage.contains("table_name"))
// table should not have changed
val table2 = testCatalog.loadTable(Identifier.of(Array(), "table_name"))
assert(table2.name == "testcat.table_name")
assert(table2.partitioning.isEmpty)
assert(table2.properties == Map("provider" -> "foo").asJava)
assert(table2.schema == new StructType()
.add("id", LongType)
.add("data", StringType))
val rdd2 = spark.sparkContext.parallelize(table.asInstanceOf[InMemoryTable].rows)
checkAnswer(spark.internalCreateDataFrame(rdd2, table.schema), spark.table("source"))
}
test("CreateTableAsSelect: if not exists") {
spark.sql(
"CREATE TABLE IF NOT EXISTS testcat.table_name USING foo AS SELECT id, data FROM source")
val testCatalog = catalog("testcat").asTableCatalog
val table = testCatalog.loadTable(Identifier.of(Array(), "table_name"))
assert(table.name == "testcat.table_name")
assert(table.partitioning.isEmpty)
assert(table.properties == Map("provider" -> "foo").asJava)
assert(table.schema == new StructType()
.add("id", LongType)
.add("data", StringType))
val rdd = spark.sparkContext.parallelize(table.asInstanceOf[InMemoryTable].rows)
checkAnswer(spark.internalCreateDataFrame(rdd, table.schema), spark.table("source"))
spark.sql(
"CREATE TABLE IF NOT EXISTS testcat.table_name USING foo AS SELECT id, data FROM source2")
// check that the table contains data from just the first CTAS
val rdd2 = spark.sparkContext.parallelize(table.asInstanceOf[InMemoryTable].rows)
checkAnswer(spark.internalCreateDataFrame(rdd2, table.schema), spark.table("source"))
}
test("CreateTableAsSelect: use default catalog for v2 sources when default catalog is set") {
spark.conf.set(SQLConf.DEFAULT_CATALOG.key, "testcat")
val df = spark.createDataFrame(Seq((1L, "a"), (2L, "b"), (3L, "c"))).toDF("id", "data")
df.createOrReplaceTempView("source")
// setting the default catalog breaks the reference to source because the default catalog is
// used and AsTableIdentifier no longer matches
spark.sql(s"CREATE TABLE table_name USING foo AS SELECT id, data FROM source")
val testCatalog = catalog("testcat").asTableCatalog
val table = testCatalog.loadTable(Identifier.of(Array(), "table_name"))
assert(table.name == "testcat.table_name")
assert(table.partitioning.isEmpty)
assert(table.properties == Map("provider" -> "foo").asJava)
assert(table.schema == new StructType()
.add("id", LongType)
.add("data", StringType))
val rdd = sparkContext.parallelize(table.asInstanceOf[InMemoryTable].rows)
checkAnswer(spark.internalCreateDataFrame(rdd, table.schema), spark.table("source"))
}
test("CreateTableAsSelect: v2 session catalog can load v1 source table") {
// unset this config to use the default v2 session catalog.
spark.conf.unset(V2_SESSION_CATALOG_IMPLEMENTATION.key)
val df = spark.createDataFrame(Seq((1L, "a"), (2L, "b"), (3L, "c"))).toDF("id", "data")
df.createOrReplaceTempView("source")
sql(s"CREATE TABLE table_name USING parquet AS SELECT id, data FROM source")
checkAnswer(sql(s"TABLE default.table_name"), spark.table("source"))
// The fact that the following line doesn't throw an exception means, the session catalog
// can load the table.
val t = catalog(SESSION_CATALOG_NAME).asTableCatalog
.loadTable(Identifier.of(Array.empty, "table_name"))
assert(t.isInstanceOf[V1Table], "V1 table wasn't returned as an unresolved table")
}
test("CreateTableAsSelect: nullable schema") {
val basicCatalog = catalog("testcat").asTableCatalog
val atomicCatalog = catalog("testcat_atomic").asTableCatalog
val basicIdentifier = "testcat.table_name"
val atomicIdentifier = "testcat_atomic.table_name"
Seq((basicCatalog, basicIdentifier), (atomicCatalog, atomicIdentifier)).foreach {
case (catalog, identifier) =>
spark.sql(s"CREATE TABLE $identifier USING foo AS SELECT 1 i")
val table = catalog.loadTable(Identifier.of(Array(), "table_name"))
assert(table.name == identifier)
assert(table.partitioning.isEmpty)
assert(table.properties == Map("provider" -> "foo").asJava)
assert(table.schema == new StructType().add("i", "int"))
val rdd = spark.sparkContext.parallelize(table.asInstanceOf[InMemoryTable].rows)
checkAnswer(spark.internalCreateDataFrame(rdd, table.schema), Row(1))
sql(s"INSERT INTO $identifier SELECT CAST(null AS INT)")
val rdd2 = spark.sparkContext.parallelize(table.asInstanceOf[InMemoryTable].rows)
checkAnswer(spark.internalCreateDataFrame(rdd2, table.schema), Seq(Row(1), Row(null)))
}
}
test("DropTable: basic") {
val tableName = "testcat.ns1.ns2.tbl"
val ident = Identifier.of(Array("ns1", "ns2"), "tbl")
sql(s"CREATE TABLE $tableName USING foo AS SELECT id, data FROM source")
assert(catalog("testcat").asTableCatalog.tableExists(ident) === true)
sql(s"DROP TABLE $tableName")
assert(catalog("testcat").asTableCatalog.tableExists(ident) === false)
}
test("DropTable: if exists") {
intercept[NoSuchTableException] {
sql(s"DROP TABLE testcat.db.notbl")
}
sql(s"DROP TABLE IF EXISTS testcat.db.notbl")
}
test("Relation: basic") {
val t1 = "testcat.ns1.ns2.tbl"
withTable(t1) {
sql(s"CREATE TABLE $t1 USING foo AS SELECT id, data FROM source")
checkAnswer(sql(s"TABLE $t1"), spark.table("source"))
checkAnswer(sql(s"SELECT * FROM $t1"), spark.table("source"))
}
}
test("Relation: SparkSession.table()") {
val t1 = "testcat.ns1.ns2.tbl"
withTable(t1) {
sql(s"CREATE TABLE $t1 USING foo AS SELECT id, data FROM source")
checkAnswer(spark.table(s"$t1"), spark.table("source"))
}
}
test("Relation: CTE") {
val t1 = "testcat.ns1.ns2.tbl"
withTable(t1) {
sql(s"CREATE TABLE $t1 USING foo AS SELECT id, data FROM source")
checkAnswer(
sql(s"""
|WITH cte AS (SELECT * FROM $t1)
|SELECT * FROM cte
""".stripMargin),
spark.table("source"))
}
}
test("Relation: view text") {
val t1 = "testcat.ns1.ns2.tbl"
withTable(t1) {
withView("view1") { v1: String =>
sql(s"CREATE TABLE $t1 USING foo AS SELECT id, data FROM source")
sql(s"CREATE VIEW $v1 AS SELECT * from $t1")
checkAnswer(sql(s"TABLE $v1"), spark.table("source"))
}
}
}
test("Relation: join tables in 2 catalogs") {
val t1 = "testcat.ns1.ns2.tbl"
val t2 = "testcat2.v2tbl"
withTable(t1, t2) {
sql(s"CREATE TABLE $t1 USING foo AS SELECT id, data FROM source")
sql(s"CREATE TABLE $t2 USING foo AS SELECT id, data FROM source2")
val df1 = spark.table("source")
val df2 = spark.table("source2")
val df_joined = df1.join(df2).where(df1("id") + 1 === df2("id"))
checkAnswer(
sql(s"""
|SELECT *
|FROM $t1 t1, $t2 t2
|WHERE t1.id + 1 = t2.id
""".stripMargin),
df_joined)
}
}
test("InsertInto: append - across catalog") {
val t1 = "testcat.ns1.ns2.tbl"
val t2 = "testcat2.db.tbl"
withTable(t1, t2) {
sql(s"CREATE TABLE $t1 USING foo AS SELECT * FROM source")
sql(s"CREATE TABLE $t2 (id bigint, data string) USING foo")
sql(s"INSERT INTO $t2 SELECT * FROM $t1")
checkAnswer(spark.table(t2), spark.table("source"))
}
}
test("ShowTables: using v2 catalog") {
spark.sql("CREATE TABLE testcat.db.table_name (id bigint, data string) USING foo")
spark.sql("CREATE TABLE testcat.n1.n2.db.table_name (id bigint, data string) USING foo")
runShowTablesSql("SHOW TABLES FROM testcat.db", Seq(Row("db", "table_name")))
runShowTablesSql(
"SHOW TABLES FROM testcat.n1.n2.db",
Seq(Row("n1.n2.db", "table_name")))
}
test("ShowTables: using v2 catalog with a pattern") {
spark.sql("CREATE TABLE testcat.db.table (id bigint, data string) USING foo")
spark.sql("CREATE TABLE testcat.db.table_name_1 (id bigint, data string) USING foo")
spark.sql("CREATE TABLE testcat.db.table_name_2 (id bigint, data string) USING foo")
spark.sql("CREATE TABLE testcat.db2.table_name_2 (id bigint, data string) USING foo")
runShowTablesSql(
"SHOW TABLES FROM testcat.db",
Seq(
Row("db", "table"),
Row("db", "table_name_1"),
Row("db", "table_name_2")))
runShowTablesSql(
"SHOW TABLES FROM testcat.db LIKE '*name*'",
Seq(Row("db", "table_name_1"), Row("db", "table_name_2")))
runShowTablesSql(
"SHOW TABLES FROM testcat.db LIKE '*2'",
Seq(Row("db", "table_name_2")))
}
test("ShowTables: using v2 catalog, namespace doesn't exist") {
runShowTablesSql("SHOW TABLES FROM testcat.unknown", Seq())
}
test("ShowTables: using v1 catalog") {
runShowTablesSql(
"SHOW TABLES FROM default",
Seq(Row("", "source", true), Row("", "source2", true)),
expectV2Catalog = false)
}
test("ShowTables: using v1 catalog, db doesn't exist ") {
// 'db' below resolves to a database name for v1 catalog because there is no catalog named
// 'db' and there is no default catalog set.
val exception = intercept[NoSuchDatabaseException] {
runShowTablesSql("SHOW TABLES FROM db", Seq(), expectV2Catalog = false)
}
assert(exception.getMessage.contains("Database 'db' not found"))
}
test("ShowTables: using v1 catalog, db name with multipartIdentifier ('a.b') is not allowed.") {
val exception = intercept[AnalysisException] {
runShowTablesSql("SHOW TABLES FROM a.b", Seq(), expectV2Catalog = false)
}
assert(exception.getMessage.contains("The database name is not valid: a.b"))
}
test("ShowTables: using v2 catalog with empty namespace") {
spark.sql("CREATE TABLE testcat.table (id bigint, data string) USING foo")
runShowTablesSql("SHOW TABLES FROM testcat", Seq(Row("", "table")))
}
test("ShowTables: namespace is not specified and default v2 catalog is set") {
spark.conf.set(SQLConf.DEFAULT_CATALOG.key, "testcat")
spark.sql("CREATE TABLE testcat.table (id bigint, data string) USING foo")
// v2 catalog is used where default namespace is empty for TestInMemoryTableCatalog.
runShowTablesSql("SHOW TABLES", Seq(Row("", "table")))
}
test("ShowTables: namespace not specified and default v2 catalog not set - fallback to v1") {
runShowTablesSql(
"SHOW TABLES",
Seq(Row("", "source", true), Row("", "source2", true)),
expectV2Catalog = false)
runShowTablesSql(
"SHOW TABLES LIKE '*2'",
Seq(Row("", "source2", true)),
expectV2Catalog = false)
}
test("ShowTables: change current catalog and namespace with USE statements") {
sql("CREATE TABLE testcat.ns1.ns2.table (id bigint) USING foo")
// Initially, the v2 session catalog (current catalog) is used.
runShowTablesSql(
"SHOW TABLES", Seq(Row("", "source", true), Row("", "source2", true)),
expectV2Catalog = false)
// Update the current catalog, and no table is matched since the current namespace is Array().
sql("USE testcat")
runShowTablesSql("SHOW TABLES", Seq())
// Update the current namespace to match ns1.ns2.table.
sql("USE testcat.ns1.ns2")
runShowTablesSql("SHOW TABLES", Seq(Row("ns1.ns2", "table")))
}
private def runShowTablesSql(
sqlText: String,
expected: Seq[Row],
expectV2Catalog: Boolean = true): Unit = {
val schema = if (expectV2Catalog) {
new StructType()
.add("namespace", StringType, nullable = false)
.add("tableName", StringType, nullable = false)
} else {
new StructType()
.add("database", StringType, nullable = false)
.add("tableName", StringType, nullable = false)
.add("isTemporary", BooleanType, nullable = false)
}
val df = spark.sql(sqlText)
assert(df.schema === schema)
assert(expected === df.collect())
}
test("SHOW TABLE EXTENDED not valid v1 database") {
def testV1CommandNamespace(sqlCommand: String, namespace: String): Unit = {
val e = intercept[AnalysisException] {
sql(sqlCommand)
}
assert(e.message.contains(s"The database name is not valid: ${namespace}"))
}
val namespace = "testcat.ns1.ns2"
val table = "tbl"
withTable(s"$namespace.$table") {
sql(s"CREATE TABLE $namespace.$table (id bigint, data string) " +
s"USING foo PARTITIONED BY (id)")
testV1CommandNamespace(s"SHOW TABLE EXTENDED FROM $namespace LIKE 'tb*'",
namespace)
testV1CommandNamespace(s"SHOW TABLE EXTENDED IN $namespace LIKE 'tb*'",
namespace)
testV1CommandNamespace("SHOW TABLE EXTENDED " +
s"FROM $namespace LIKE 'tb*' PARTITION(id=1)",
namespace)
testV1CommandNamespace("SHOW TABLE EXTENDED " +
s"IN $namespace LIKE 'tb*' PARTITION(id=1)",
namespace)
}
}
test("SHOW TABLE EXTENDED valid v1") {
val expected = Seq(Row("", "source", true), Row("", "source2", true))
val schema = new StructType()
.add("database", StringType, nullable = false)
.add("tableName", StringType, nullable = false)
.add("isTemporary", BooleanType, nullable = false)
.add("information", StringType, nullable = false)
val df = sql("SHOW TABLE EXTENDED FROM default LIKE '*source*'")
val result = df.collect()
val resultWithoutInfo = result.map{ case Row(db, table, temp, _) => Row(db, table, temp)}
assert(df.schema === schema)
assert(resultWithoutInfo === expected)
result.foreach{ case Row(_, _, _, info: String) => assert(info.nonEmpty)}
}
test("CreateNameSpace: basic tests") {
// Session catalog is used.
withNamespace("ns") {
sql("CREATE NAMESPACE ns")
testShowNamespaces("SHOW NAMESPACES", Seq("default", "ns"))
}
// V2 non-session catalog is used.
withNamespace("testcat.ns1.ns2") {
sql("CREATE NAMESPACE testcat.ns1.ns2")
testShowNamespaces("SHOW NAMESPACES IN testcat", Seq("ns1"))
testShowNamespaces("SHOW NAMESPACES IN testcat.ns1", Seq("ns1.ns2"))
}
withNamespace("testcat.test") {
withTempDir { tmpDir =>
val path = tmpDir.getCanonicalPath
sql(s"CREATE NAMESPACE testcat.test LOCATION '$path'")
val metadata =
catalog("testcat").asNamespaceCatalog.loadNamespaceMetadata(Array("test")).asScala
val catalogPath = metadata(V2SessionCatalog.LOCATION_TABLE_PROP)
assert(catalogPath.equals(catalogPath))
}
}
// TODO: Add tests for validating namespace metadata when DESCRIBE NAMESPACE is available.
}
test("CreateNameSpace: test handling of 'IF NOT EXIST'") {
withNamespace("testcat.ns1") {
sql("CREATE NAMESPACE IF NOT EXISTS testcat.ns1")
// The 'ns1' namespace already exists, so this should fail.
val exception = intercept[NamespaceAlreadyExistsException] {
sql("CREATE NAMESPACE testcat.ns1")
}
assert(exception.getMessage.contains("Namespace 'ns1' already exists"))
// The following will be no-op since the namespace already exists.
sql("CREATE NAMESPACE IF NOT EXISTS testcat.ns1")
}
}
test("DropNamespace: basic tests") {
// Session catalog is used.
sql("CREATE NAMESPACE ns")
testShowNamespaces("SHOW NAMESPACES", Seq("default", "ns"))
sql("DROP NAMESPACE ns")
testShowNamespaces("SHOW NAMESPACES", Seq("default"))
// V2 non-session catalog is used.
sql("CREATE NAMESPACE testcat.ns1")
testShowNamespaces("SHOW NAMESPACES IN testcat", Seq("ns1"))
sql("DROP NAMESPACE testcat.ns1")
testShowNamespaces("SHOW NAMESPACES IN testcat", Seq())
}
test("DropNamespace: drop non-empty namespace with a non-cascading mode") {
sql("CREATE TABLE testcat.ns1.table (id bigint) USING foo")
sql("CREATE TABLE testcat.ns1.ns2.table (id bigint) USING foo")
testShowNamespaces("SHOW NAMESPACES IN testcat", Seq("ns1"))
testShowNamespaces("SHOW NAMESPACES IN testcat.ns1", Seq("ns1.ns2"))
def assertDropFails(): Unit = {
val e = intercept[SparkException] {
sql("DROP NAMESPACE testcat.ns1")
}
assert(e.getMessage.contains("Cannot drop a non-empty namespace: ns1"))
}
// testcat.ns1.table is present, thus testcat.ns1 cannot be dropped.
assertDropFails()
sql("DROP TABLE testcat.ns1.table")
// testcat.ns1.ns2.table is present, thus testcat.ns1 cannot be dropped.
assertDropFails()
sql("DROP TABLE testcat.ns1.ns2.table")
// testcat.ns1.ns2 namespace is present, thus testcat.ns1 cannot be dropped.
assertDropFails()
sql("DROP NAMESPACE testcat.ns1.ns2")
// Now that testcat.ns1 is empty, it can be dropped.
sql("DROP NAMESPACE testcat.ns1")
testShowNamespaces("SHOW NAMESPACES IN testcat", Seq())
}
test("DropNamespace: drop non-empty namespace with a cascade mode") {
sql("CREATE TABLE testcat.ns1.table (id bigint) USING foo")
sql("CREATE TABLE testcat.ns1.ns2.table (id bigint) USING foo")
testShowNamespaces("SHOW NAMESPACES IN testcat", Seq("ns1"))
testShowNamespaces("SHOW NAMESPACES IN testcat.ns1", Seq("ns1.ns2"))
sql("DROP NAMESPACE testcat.ns1 CASCADE")
testShowNamespaces("SHOW NAMESPACES IN testcat", Seq())
}
test("DropNamespace: test handling of 'IF EXISTS'") {
sql("DROP NAMESPACE IF EXISTS testcat.unknown")
val exception = intercept[NoSuchNamespaceException] {
sql("DROP NAMESPACE testcat.ns1")
}
assert(exception.getMessage.contains("Namespace 'ns1' not found"))
}
test("ShowNamespaces: show root namespaces with default v2 catalog") {
spark.conf.set(SQLConf.DEFAULT_CATALOG.key, "testcat")
testShowNamespaces("SHOW NAMESPACES", Seq())
spark.sql("CREATE TABLE testcat.ns1.table (id bigint) USING foo")
spark.sql("CREATE TABLE testcat.ns1.ns1_1.table (id bigint) USING foo")
spark.sql("CREATE TABLE testcat.ns2.table (id bigint) USING foo")
testShowNamespaces("SHOW NAMESPACES", Seq("ns1", "ns2"))
testShowNamespaces("SHOW NAMESPACES LIKE '*1*'", Seq("ns1"))
}
test("ShowNamespaces: show namespaces with v2 catalog") {
spark.sql("CREATE TABLE testcat.ns1.table (id bigint) USING foo")
spark.sql("CREATE TABLE testcat.ns1.ns1_1.table (id bigint) USING foo")
spark.sql("CREATE TABLE testcat.ns1.ns1_2.table (id bigint) USING foo")
spark.sql("CREATE TABLE testcat.ns2.table (id bigint) USING foo")
spark.sql("CREATE TABLE testcat.ns2.ns2_1.table (id bigint) USING foo")
// Look up only with catalog name, which should list root namespaces.
testShowNamespaces("SHOW NAMESPACES IN testcat", Seq("ns1", "ns2"))
// Look up sub-namespaces.
testShowNamespaces("SHOW NAMESPACES IN testcat.ns1", Seq("ns1.ns1_1", "ns1.ns1_2"))
testShowNamespaces("SHOW NAMESPACES IN testcat.ns1 LIKE '*2*'", Seq("ns1.ns1_2"))
testShowNamespaces("SHOW NAMESPACES IN testcat.ns2", Seq("ns2.ns2_1"))
// Try to look up namespaces that do not exist.
testShowNamespaces("SHOW NAMESPACES IN testcat.ns3", Seq())
testShowNamespaces("SHOW NAMESPACES IN testcat.ns1.ns3", Seq())
}
test("ShowNamespaces: default v2 catalog is not set") {
spark.sql("CREATE TABLE testcat.ns.table (id bigint) USING foo")
// The current catalog is resolved to a v2 session catalog.
testShowNamespaces("SHOW NAMESPACES", Seq("default"))
}
test("ShowNamespaces: default v2 catalog doesn't support namespace") {
spark.conf.set(
"spark.sql.catalog.testcat_no_namspace",
classOf[BasicInMemoryTableCatalog].getName)
spark.conf.set(SQLConf.DEFAULT_CATALOG.key, "testcat_no_namspace")
val exception = intercept[AnalysisException] {
sql("SHOW NAMESPACES")
}
assert(exception.getMessage.contains("does not support namespaces"))
}
test("ShowNamespaces: v2 catalog doesn't support namespace") {
spark.conf.set(
"spark.sql.catalog.testcat_no_namspace",
classOf[BasicInMemoryTableCatalog].getName)
val exception = intercept[AnalysisException] {
sql("SHOW NAMESPACES in testcat_no_namspace")
}
assert(exception.getMessage.contains("does not support namespaces"))
}
test("ShowNamespaces: session catalog is used and namespace doesn't exist") {
val exception = intercept[AnalysisException] {
sql("SHOW NAMESPACES in dummy")
}
assert(exception.getMessage.contains("Namespace 'dummy' not found"))
}
test("ShowNamespaces: change catalog and namespace with USE statements") {
sql("CREATE TABLE testcat.ns1.ns2.table (id bigint) USING foo")
// Initially, the current catalog is a v2 session catalog.
testShowNamespaces("SHOW NAMESPACES", Seq("default"))
// Update the current catalog to 'testcat'.
sql("USE testcat")
testShowNamespaces("SHOW NAMESPACES", Seq("ns1"))