You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iceberg.apache.org by bl...@apache.org on 2019/07/02 15:39:06 UTC
[incubator-iceberg] branch master updated: Update iceberg-spark to
use HiveTables (#239)
This is an automated email from the ASF dual-hosted git repository.
blue pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-iceberg.git
The following commit(s) were added to refs/heads/master by this push:
new b898129 Update iceberg-spark to use HiveTables (#239)
b898129 is described below
commit b898129580d1f97eaabba64a25832cb11c607292
Author: Anton Okolnychyi <ao...@apple.com>
AuthorDate: Tue Jul 2 16:39:00 2019 +0100
Update iceberg-spark to use HiveTables (#239)
---
.../apache/iceberg/catalog/TableIdentifier.java | 10 ++
.../iceberg/catalog/TestTableIdentifier.java | 44 +++++++
build.gradle | 15 +++
.../java/org/apache/iceberg/hive/HiveCatalogs.java | 40 +++++++
.../org/apache/iceberg/hive/HiveTableBaseTest.java | 103 ++--------------
.../org/apache/iceberg/hive/TestHiveMetastore.java | 132 +++++++++++++++++++++
.../apache/iceberg/spark/source/IcebergSource.java | 21 ++--
.../spark/source/TestIcebergSourceHiveTables.java | 117 ++++++++++++++++++
8 files changed, 383 insertions(+), 99 deletions(-)
diff --git a/api/src/main/java/org/apache/iceberg/catalog/TableIdentifier.java b/api/src/main/java/org/apache/iceberg/catalog/TableIdentifier.java
index 2a539e1..cede38f 100644
--- a/api/src/main/java/org/apache/iceberg/catalog/TableIdentifier.java
+++ b/api/src/main/java/org/apache/iceberg/catalog/TableIdentifier.java
@@ -20,12 +20,17 @@
package org.apache.iceberg.catalog;
import com.google.common.base.Preconditions;
+import com.google.common.base.Splitter;
+import com.google.common.collect.Iterables;
import java.util.Arrays;
/**
* Identifies a table in iceberg catalog.
*/
public class TableIdentifier {
+
+ private static final Splitter DOT = Splitter.on('.');
+
private final Namespace namespace;
private final String name;
@@ -38,6 +43,11 @@ public class TableIdentifier {
return new TableIdentifier(namespace, name);
}
+ public static TableIdentifier parse(String identifier) {
+ Iterable<String> parts = DOT.split(identifier);
+ return TableIdentifier.of(Iterables.toArray(parts, String.class));
+ }
+
private TableIdentifier(Namespace namespace, String name) {
Preconditions.checkArgument(name != null && !name.isEmpty(), "Invalid table name %s", name);
this.namespace = namespace;
diff --git a/api/src/test/java/org/apache/iceberg/catalog/TestTableIdentifier.java b/api/src/test/java/org/apache/iceberg/catalog/TestTableIdentifier.java
new file mode 100644
index 0000000..1216403
--- /dev/null
+++ b/api/src/test/java/org/apache/iceberg/catalog/TestTableIdentifier.java
@@ -0,0 +1,44 @@
+/*
+ * 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.iceberg.catalog;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class TestTableIdentifier {
+
+ @Test
+ public void testTableIdentifierParsing() {
+ TableIdentifier oneLevelIdentifier = TableIdentifier.parse("tbl");
+ Assert.assertFalse(oneLevelIdentifier.hasNamespace());
+ Assert.assertEquals("tbl", oneLevelIdentifier.name());
+
+ TableIdentifier twoLevelIdentifier = TableIdentifier.parse("userdb.tbl");
+ Assert.assertEquals(1, twoLevelIdentifier.namespace().levels().length);
+ Assert.assertEquals("userdb", twoLevelIdentifier.namespace().levels()[0]);
+ Assert.assertEquals("tbl", twoLevelIdentifier.name());
+
+ TableIdentifier threeLevelIdentifier = TableIdentifier.parse("catalog.userdb.tbl");
+ Assert.assertEquals(2, threeLevelIdentifier.namespace().levels().length);
+ Assert.assertEquals("catalog", threeLevelIdentifier.namespace().levels()[0]);
+ Assert.assertEquals("userdb", threeLevelIdentifier.namespace().levels()[1]);
+ Assert.assertEquals("tbl", threeLevelIdentifier.name());
+ }
+}
diff --git a/build.gradle b/build.gradle
index fcf2682..a8170f4 100644
--- a/build.gradle
+++ b/build.gradle
@@ -275,6 +275,19 @@ project(':iceberg-hive') {
exclude group: 'org.slf4j', module: 'slf4j-log4j12'
}
}
+
+ task testJar(type: Jar){
+ archiveClassifier = 'tests'
+ from sourceSets.test.output
+ }
+
+ configurations {
+ testArtifacts
+ }
+
+ artifacts {
+ testArtifacts testJar
+ }
}
project(':iceberg-orc') {
@@ -317,6 +330,7 @@ project(':iceberg-spark') {
compile project(':iceberg-core')
compile project(':iceberg-orc')
compile project(':iceberg-parquet')
+ compile project(':iceberg-hive')
compileOnly "org.apache.avro:avro:$avroVersion"
compileOnly("org.apache.spark:spark-hive_$scalaVersion:$sparkVersion") {
@@ -328,6 +342,7 @@ project(':iceberg-spark') {
testCompile("org.apache.hadoop:hadoop-minicluster:$hadoopVersion") {
exclude group: 'org.apache.avro', module: 'avro'
}
+ testCompile project(path: ':iceberg-hive', configuration: 'testArtifacts')
}
}
diff --git a/hive/src/main/java/org/apache/iceberg/hive/HiveCatalogs.java b/hive/src/main/java/org/apache/iceberg/hive/HiveCatalogs.java
new file mode 100644
index 0000000..7c8ed56
--- /dev/null
+++ b/hive/src/main/java/org/apache/iceberg/hive/HiveCatalogs.java
@@ -0,0 +1,40 @@
+/*
+ * 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.iceberg.hive;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hive.conf.HiveConf;
+
+public final class HiveCatalogs {
+
+ private static final Cache<String, HiveCatalog> CATALOG_CACHE = Caffeine.newBuilder()
+ .weakValues()
+ .build();
+
+ private HiveCatalogs() {}
+
+ public static HiveCatalog loadCatalog(Configuration conf) {
+ // metastore URI can be null in local mode
+ String metastoreUri = conf.get(HiveConf.ConfVars.METASTOREURIS.varname, "");
+ return CATALOG_CACHE.get(metastoreUri, uri -> new HiveCatalog(conf));
+ }
+}
diff --git a/hive/src/test/java/org/apache/iceberg/hive/HiveTableBaseTest.java b/hive/src/test/java/org/apache/iceberg/hive/HiveTableBaseTest.java
index e3e2bf2..305ca6b 100644
--- a/hive/src/test/java/org/apache/iceberg/hive/HiveTableBaseTest.java
+++ b/hive/src/test/java/org/apache/iceberg/hive/HiveTableBaseTest.java
@@ -19,48 +19,25 @@
package org.apache.iceberg.hive;
-import java.io.BufferedReader;
import java.io.File;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.Reader;
-import java.net.URL;
import java.nio.file.Paths;
-import java.sql.Connection;
-import java.sql.DriverManager;
-import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
import java.util.stream.Collectors;
-import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.HiveMetaStore;
import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
-import org.apache.hadoop.hive.metastore.IHMSHandler;
-import org.apache.hadoop.hive.metastore.RetryingHMSHandler;
-import org.apache.hadoop.hive.metastore.TSetIpAddressProcessor;
import org.apache.hadoop.hive.metastore.api.Database;
import org.apache.iceberg.PartitionSpec;
import org.apache.iceberg.Schema;
import org.apache.iceberg.catalog.TableIdentifier;
import org.apache.iceberg.types.Types;
-import org.apache.thrift.protocol.TBinaryProtocol;
-import org.apache.thrift.server.TServer;
-import org.apache.thrift.server.TThreadPoolServer;
-import org.apache.thrift.transport.TServerSocket;
-import org.apache.thrift.transport.TTransportFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
-import static java.nio.file.Files.createTempDirectory;
-import static java.nio.file.attribute.PosixFilePermissions.asFileAttribute;
-import static java.nio.file.attribute.PosixFilePermissions.fromString;
import static org.apache.iceberg.PartitionSpec.builderFor;
import static org.apache.iceberg.TableMetadataParser.getFileExtension;
import static org.apache.iceberg.types.Types.NestedField.optional;
@@ -83,28 +60,20 @@ public class HiveTableBaseTest {
private static final PartitionSpec partitionSpec = builderFor(schema).identity("id").build();
private static HiveConf hiveConf;
- private static File hiveLocalDir;
-
- private static ExecutorService executorService;
- private static TServer server;
+ private static TestHiveMetastore metastore;
protected static HiveMetaStoreClient metastoreClient;
protected static HiveCatalog catalog;
@BeforeClass
public static void startMetastore() throws Exception {
- HiveTableBaseTest.executorService = Executors.newSingleThreadExecutor();
- HiveTableBaseTest.hiveLocalDir = createTempDirectory("hive", asFileAttribute(fromString("rwxrwxrwx"))).toFile();
- File derbyLogFile = new File(hiveLocalDir, "derby.log");
- System.setProperty("derby.stream.error.file", derbyLogFile.getAbsolutePath());
- setupDB("jdbc:derby:" + getDerbyPath() + ";create=true");
-
- HiveTableBaseTest.server = thriftServer();
- executorService.submit(() -> server.serve());
-
+ HiveTableBaseTest.metastore = new TestHiveMetastore();
+ metastore.start();
+ HiveTableBaseTest.hiveConf = metastore.hiveConf();
HiveTableBaseTest.metastoreClient = new HiveMetaStoreClient(hiveConf);
- metastoreClient.createDatabase(new Database(DB_NAME, "description", getDBPath(), new HashMap<>()));
-
+ String dbPath = metastore.getDatabasePath(DB_NAME);
+ Database db = new Database(DB_NAME, "description", dbPath, new HashMap<>());
+ metastoreClient.createDatabase(db);
HiveTableBaseTest.catalog = new HiveCatalog(hiveConf);
}
@@ -115,15 +84,8 @@ public class HiveTableBaseTest {
metastoreClient.close();
HiveTableBaseTest.metastoreClient = null;
- if (server != null) {
- server.stop();
- }
-
- executorService.shutdown();
-
- if (hiveLocalDir != null) {
- hiveLocalDir.delete();
- }
+ metastore.stop();
+ HiveTableBaseTest.metastore = null;
}
private Path tableLocation;
@@ -140,52 +102,9 @@ public class HiveTableBaseTest {
catalog.dropTable(TABLE_IDENTIFIER);
}
- private static HiveConf hiveConf(Configuration conf, int port) {
- final HiveConf newHiveConf = new HiveConf(conf, HiveTableBaseTest.class);
- newHiveConf.set(HiveConf.ConfVars.METASTOREURIS.varname, "thrift://localhost:" + port);
- newHiveConf.set(HiveConf.ConfVars.METASTOREWAREHOUSE.varname, "file:" + hiveLocalDir.getAbsolutePath());
- return newHiveConf;
- }
-
- private static String getDerbyPath() {
- final File metastoreDb = new File(hiveLocalDir, "metastore_db");
- return metastoreDb.getPath();
- }
-
- private static TServer thriftServer() throws Exception {
- TServerSocket socket = new TServerSocket(0);
- HiveTableBaseTest.hiveConf = hiveConf(new Configuration(), socket.getServerSocket().getLocalPort());
- HiveConf serverConf = new HiveConf(hiveConf);
- serverConf.set(HiveConf.ConfVars.METASTORECONNECTURLKEY.varname, "jdbc:derby:" + getDerbyPath() + ";create=true");
- HiveMetaStore.HMSHandler baseHandler = new HiveMetaStore.HMSHandler("new db based metaserver", serverConf);
- IHMSHandler handler = RetryingHMSHandler.getProxy(serverConf, baseHandler, false);
-
- TThreadPoolServer.Args args = new TThreadPoolServer.Args(socket)
- .processor(new TSetIpAddressProcessor<>(handler))
- .transportFactory(new TTransportFactory())
- .protocolFactory(new TBinaryProtocol.Factory())
- .minWorkerThreads(3)
- .maxWorkerThreads(5);
-
- return new TThreadPoolServer(args);
- }
-
- private static void setupDB(String dbURL) throws SQLException, IOException {
- Connection connection = DriverManager.getConnection(dbURL);
- ScriptRunner scriptRunner = new ScriptRunner(connection, true, true);
-
- URL hiveSqlScript = HiveTableBaseTest.class.getClassLoader().getResource("hive-schema-3.1.0.derby.sql");
- try (Reader reader = new BufferedReader(new FileReader(new File(hiveSqlScript.getFile())))) {
- scriptRunner.runScript(reader);
- }
- }
-
- private static String getDBPath() {
- return Paths.get(hiveLocalDir.getAbsolutePath(), DB_NAME + ".db").toAbsolutePath().toString();
- }
-
private static String getTableBasePath(String tableName) {
- return Paths.get(getDBPath(), tableName).toAbsolutePath().toString();
+ String databasePath = metastore.getDatabasePath(DB_NAME);
+ return Paths.get(databasePath, tableName).toAbsolutePath().toString();
}
protected static String getTableLocation(String tableName) {
diff --git a/hive/src/test/java/org/apache/iceberg/hive/TestHiveMetastore.java b/hive/src/test/java/org/apache/iceberg/hive/TestHiveMetastore.java
new file mode 100644
index 0000000..a5a315e
--- /dev/null
+++ b/hive/src/test/java/org/apache/iceberg/hive/TestHiveMetastore.java
@@ -0,0 +1,132 @@
+/*
+ * 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.iceberg.hive;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.HiveMetaStore;
+import org.apache.hadoop.hive.metastore.IHMSHandler;
+import org.apache.hadoop.hive.metastore.RetryingHMSHandler;
+import org.apache.hadoop.hive.metastore.TSetIpAddressProcessor;
+import org.apache.thrift.protocol.TBinaryProtocol;
+import org.apache.thrift.server.TServer;
+import org.apache.thrift.server.TThreadPoolServer;
+import org.apache.thrift.transport.TServerSocket;
+import org.apache.thrift.transport.TTransportFactory;
+
+import static java.nio.file.Files.createTempDirectory;
+import static java.nio.file.attribute.PosixFilePermissions.asFileAttribute;
+import static java.nio.file.attribute.PosixFilePermissions.fromString;
+
+public class TestHiveMetastore {
+
+ private File hiveLocalDir;
+ private HiveConf hiveConf;
+ private ExecutorService executorService;
+ private TServer server;
+
+ public void start() {
+ try {
+ hiveLocalDir = createTempDirectory("hive", asFileAttribute(fromString("rwxrwxrwx"))).toFile();
+ File derbyLogFile = new File(hiveLocalDir, "derby.log");
+ System.setProperty("derby.stream.error.file", derbyLogFile.getAbsolutePath());
+ setupMetastoreDB("jdbc:derby:" + getDerbyPath() + ";create=true");
+
+ TServerSocket socket = new TServerSocket(0);
+ int port = socket.getServerSocket().getLocalPort();
+ hiveConf = newHiveConf(port);
+ server = newThriftServer(socket, hiveConf);
+ executorService = Executors.newSingleThreadExecutor();
+ executorService.submit(() -> server.serve());
+ } catch (Exception e) {
+ throw new RuntimeException("Cannot start TestHiveMetastore", e);
+ }
+ }
+
+ public void stop() {
+ if (server != null) {
+ server.stop();
+ }
+ if (executorService != null) {
+ executorService.shutdown();
+ }
+ if (hiveLocalDir != null) {
+ hiveLocalDir.delete();
+ }
+ }
+
+ public HiveConf hiveConf() {
+ return hiveConf;
+ }
+
+ public String getDatabasePath(String dbName) {
+ File dbDir = new File(hiveLocalDir, dbName + ".db");
+ return dbDir.getPath();
+ }
+
+ private TServer newThriftServer(TServerSocket socket, HiveConf conf) throws Exception {
+ HiveConf serverConf = new HiveConf(conf);
+ serverConf.set(HiveConf.ConfVars.METASTORECONNECTURLKEY.varname, "jdbc:derby:" + getDerbyPath() + ";create=true");
+ HiveMetaStore.HMSHandler baseHandler = new HiveMetaStore.HMSHandler("new db based metaserver", serverConf);
+ IHMSHandler handler = RetryingHMSHandler.getProxy(serverConf, baseHandler, false);
+
+ TThreadPoolServer.Args args = new TThreadPoolServer.Args(socket)
+ .processor(new TSetIpAddressProcessor<>(handler))
+ .transportFactory(new TTransportFactory())
+ .protocolFactory(new TBinaryProtocol.Factory())
+ .minWorkerThreads(3)
+ .maxWorkerThreads(5);
+
+ return new TThreadPoolServer(args);
+ }
+
+ private HiveConf newHiveConf(int port) {
+ HiveConf newHiveConf = new HiveConf(new Configuration(), TestHiveMetastore.class);
+ newHiveConf.set(HiveConf.ConfVars.METASTOREURIS.varname, "thrift://localhost:" + port);
+ newHiveConf.set(HiveConf.ConfVars.METASTOREWAREHOUSE.varname, "file:" + hiveLocalDir.getAbsolutePath());
+ return newHiveConf;
+ }
+
+ private void setupMetastoreDB(String dbURL) throws SQLException, IOException {
+ Connection connection = DriverManager.getConnection(dbURL);
+ ScriptRunner scriptRunner = new ScriptRunner(connection, true, true);
+
+ ClassLoader classLoader = ClassLoader.getSystemClassLoader();
+ InputStream inputStream = classLoader.getResourceAsStream("hive-schema-3.1.0.derby.sql");
+ try (Reader reader = new InputStreamReader(inputStream)) {
+ scriptRunner.runScript(reader);
+ }
+ }
+
+ private String getDerbyPath() {
+ File metastoreDB = new File(hiveLocalDir, "metastore_db");
+ return metastoreDB.getPath();
+ }
+}
diff --git a/spark/src/main/java/org/apache/iceberg/spark/source/IcebergSource.java b/spark/src/main/java/org/apache/iceberg/spark/source/IcebergSource.java
index be34947..545a1b8 100644
--- a/spark/src/main/java/org/apache/iceberg/spark/source/IcebergSource.java
+++ b/spark/src/main/java/org/apache/iceberg/spark/source/IcebergSource.java
@@ -28,7 +28,10 @@ import org.apache.hadoop.conf.Configuration;
import org.apache.iceberg.FileFormat;
import org.apache.iceberg.Schema;
import org.apache.iceberg.Table;
+import org.apache.iceberg.catalog.TableIdentifier;
import org.apache.iceberg.hadoop.HadoopTables;
+import org.apache.iceberg.hive.HiveCatalog;
+import org.apache.iceberg.hive.HiveCatalogs;
import org.apache.iceberg.spark.SparkSchemaUtil;
import org.apache.iceberg.types.CheckCompatibility;
import org.apache.spark.sql.SaveMode;
@@ -96,13 +99,17 @@ public class IcebergSource implements DataSourceV2, ReadSupport, WriteSupport, D
}
protected Table findTable(DataSourceOptions options, Configuration conf) {
- Optional<String> location = options.get("path");
- Preconditions.checkArgument(location.isPresent(),
- "Cannot open table without a location: path is not set");
-
- HadoopTables tables = new HadoopTables(conf);
-
- return tables.load(location.get());
+ Optional<String> path = options.get("path");
+ Preconditions.checkArgument(path.isPresent(), "Cannot open table: path is not set");
+
+ if (path.get().contains("/")) {
+ HadoopTables tables = new HadoopTables(conf);
+ return tables.load(path.get());
+ } else {
+ HiveCatalog hiveCatalog = HiveCatalogs.loadCatalog(conf);
+ TableIdentifier tableIdentifier = TableIdentifier.parse(path.get());
+ return hiveCatalog.loadTable(tableIdentifier);
+ }
}
private SparkSession lazySparkSession() {
diff --git a/spark/src/test/java/org/apache/iceberg/spark/source/TestIcebergSourceHiveTables.java b/spark/src/test/java/org/apache/iceberg/spark/source/TestIcebergSourceHiveTables.java
new file mode 100644
index 0000000..72fd1b2
--- /dev/null
+++ b/spark/src/test/java/org/apache/iceberg/spark/source/TestIcebergSourceHiveTables.java
@@ -0,0 +1,117 @@
+/*
+ * 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.iceberg.spark.source;
+
+import com.google.common.collect.Lists;
+import java.util.HashMap;
+import java.util.List;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
+import org.apache.hadoop.hive.metastore.api.Database;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.iceberg.hive.HiveCatalog;
+import org.apache.iceberg.hive.TestHiveMetastore;
+import org.apache.iceberg.types.Types;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Encoders;
+import org.apache.spark.sql.Row;
+import org.apache.spark.sql.SaveMode;
+import org.apache.spark.sql.SparkSession;
+import org.apache.thrift.TException;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import static org.apache.hadoop.hive.conf.HiveConf.ConfVars.METASTOREURIS;
+import static org.apache.iceberg.types.Types.NestedField.optional;
+
+public class TestIcebergSourceHiveTables {
+
+ private static final String DB_NAME = "hivedb";
+ private static final String TABLE_NAME = "tbl";
+ private static final TableIdentifier TABLE_IDENTIFIER = TableIdentifier.of(DB_NAME, TABLE_NAME);
+ private static final Schema SCHEMA = new Schema(
+ optional(1, "id", Types.IntegerType.get()),
+ optional(2, "data", Types.StringType.get())
+ );
+
+ private static SparkSession spark;
+ private static TestHiveMetastore metastore;
+ private static HiveConf hiveConf;
+ private static HiveMetaStoreClient metastoreClient;
+
+ @BeforeClass
+ public static void startMetastoreAndSpark() throws Exception {
+ TestIcebergSourceHiveTables.metastore = new TestHiveMetastore();
+ metastore.start();
+ TestIcebergSourceHiveTables.hiveConf = metastore.hiveConf();
+ TestIcebergSourceHiveTables.metastoreClient = new HiveMetaStoreClient(hiveConf);
+ String dbPath = metastore.getDatabasePath(DB_NAME);
+ Database db = new Database(DB_NAME, "desc", dbPath, new HashMap<>());
+ metastoreClient.createDatabase(db);
+
+ TestIcebergSourceHiveTables.spark = SparkSession.builder()
+ .master("local[2]")
+ .config("spark.hadoop." + METASTOREURIS.varname, hiveConf.get(METASTOREURIS.varname))
+ .getOrCreate();
+ }
+
+ @AfterClass
+ public static void stopMetastoreAndSpark() {
+ metastoreClient.close();
+ TestIcebergSourceHiveTables.metastoreClient = null;
+ metastore.stop();
+ TestIcebergSourceHiveTables.metastore = null;
+ spark.stop();
+ TestIcebergSourceHiveTables.spark = null;
+ }
+
+ @Test
+ public void testHiveTablesSupport() throws TException {
+ try (HiveCatalog catalog = new HiveCatalog(hiveConf)) {
+ catalog.createTable(TABLE_IDENTIFIER, SCHEMA, PartitionSpec.unpartitioned());
+
+ List<SimpleRecord> expectedRecords = Lists.newArrayList(
+ new SimpleRecord(1, "1"),
+ new SimpleRecord(2, "2"),
+ new SimpleRecord(3, "3"));
+
+ Dataset<Row> inputDf = spark.createDataFrame(expectedRecords, SimpleRecord.class);
+ inputDf.select("id", "data").write()
+ .format("iceberg")
+ .mode(SaveMode.Append)
+ .save(TABLE_IDENTIFIER.toString());
+
+ Dataset<Row> resultDf = spark.read()
+ .format("iceberg")
+ .load(TABLE_IDENTIFIER.toString());
+ List<SimpleRecord> actualRecords = resultDf.orderBy("id")
+ .as(Encoders.bean(SimpleRecord.class))
+ .collectAsList();
+
+ Assert.assertEquals("Records should match", expectedRecords, actualRecords);
+ } finally {
+ metastoreClient.dropTable(DB_NAME, TABLE_NAME);
+ }
+ }
+}