jackye1995 commented on a change in pull request #1870: URL: https://github.com/apache/iceberg/pull/1870#discussion_r557039855
########## File path: core/src/main/java/org/apache/iceberg/jdbc/JdbcCatalog.java ########## @@ -0,0 +1,403 @@ +/* + * 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.jdbc; + +import java.io.Closeable; +import java.sql.DatabaseMetaData; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.SQLIntegrityConstraintViolationException; +import java.sql.SQLNonTransientConnectionException; +import java.sql.SQLTimeoutException; +import java.sql.SQLTransientConnectionException; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import org.apache.hadoop.conf.Configurable; +import org.apache.hadoop.conf.Configuration; +import org.apache.iceberg.BaseMetastoreCatalog; +import org.apache.iceberg.CatalogProperties; +import org.apache.iceberg.CatalogUtil; +import org.apache.iceberg.TableMetadata; +import org.apache.iceberg.TableOperations; +import org.apache.iceberg.catalog.Namespace; +import org.apache.iceberg.catalog.SupportsNamespaces; +import org.apache.iceberg.catalog.TableIdentifier; +import org.apache.iceberg.exceptions.AlreadyExistsException; +import org.apache.iceberg.exceptions.NamespaceNotEmptyException; +import org.apache.iceberg.exceptions.NoSuchNamespaceException; +import org.apache.iceberg.exceptions.NoSuchTableException; +import org.apache.iceberg.hadoop.HadoopFileIO; +import org.apache.iceberg.io.FileIO; +import org.apache.iceberg.relocated.com.google.common.base.Joiner; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class JdbcCatalog extends BaseMetastoreCatalog implements Configurable, SupportsNamespaces, Closeable { + + public static final String PROPERTY_PREFIX = "connection.parameter."; + private static final Logger LOG = LoggerFactory.getLogger(JdbcCatalog.class); + private static final Joiner SLASH = Joiner.on("/"); + + private FileIO io; + private String catalogName = "jdbc"; + private String warehouseLocation; + private Configuration conf; + private JdbcClientPool connections; + + public JdbcCatalog() { + } + + @Override + public void initialize(String name, Map<String, String> properties) { + Preconditions.checkArgument(!properties.getOrDefault(CatalogProperties.HIVE_URI, "").isEmpty(), + "No connection url provided for jdbc catalog!"); + Preconditions.checkArgument(!properties.getOrDefault(CatalogProperties.WAREHOUSE_LOCATION, "").isEmpty(), Review comment: warehouse location is stored in the next line, so it make sense to first do `this.warehouseLocation = properties.getOrDefault(CatalogProperties.WAREHOUSE_LOCATION, "").replaceAll("/$", "")`, and then do all the condition checks against `this.warehouseLocation`. ########## File path: core/src/main/java/org/apache/iceberg/jdbc/JdbcCatalog.java ########## @@ -0,0 +1,403 @@ +/* + * 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.jdbc; + +import java.io.Closeable; +import java.sql.DatabaseMetaData; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.SQLIntegrityConstraintViolationException; +import java.sql.SQLNonTransientConnectionException; +import java.sql.SQLTimeoutException; +import java.sql.SQLTransientConnectionException; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import org.apache.hadoop.conf.Configurable; +import org.apache.hadoop.conf.Configuration; +import org.apache.iceberg.BaseMetastoreCatalog; +import org.apache.iceberg.CatalogProperties; +import org.apache.iceberg.CatalogUtil; +import org.apache.iceberg.TableMetadata; +import org.apache.iceberg.TableOperations; +import org.apache.iceberg.catalog.Namespace; +import org.apache.iceberg.catalog.SupportsNamespaces; +import org.apache.iceberg.catalog.TableIdentifier; +import org.apache.iceberg.exceptions.AlreadyExistsException; +import org.apache.iceberg.exceptions.NamespaceNotEmptyException; +import org.apache.iceberg.exceptions.NoSuchNamespaceException; +import org.apache.iceberg.exceptions.NoSuchTableException; +import org.apache.iceberg.hadoop.HadoopFileIO; +import org.apache.iceberg.io.FileIO; +import org.apache.iceberg.relocated.com.google.common.base.Joiner; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class JdbcCatalog extends BaseMetastoreCatalog implements Configurable, SupportsNamespaces, Closeable { + + public static final String PROPERTY_PREFIX = "connection.parameter."; + private static final Logger LOG = LoggerFactory.getLogger(JdbcCatalog.class); + private static final Joiner SLASH = Joiner.on("/"); + + private FileIO io; + private String catalogName = "jdbc"; + private String warehouseLocation; + private Configuration conf; + private JdbcClientPool connections; + + public JdbcCatalog() { + } + + @Override + public void initialize(String name, Map<String, String> properties) { + Preconditions.checkArgument(!properties.getOrDefault(CatalogProperties.HIVE_URI, "").isEmpty(), Review comment: Since this is now used by more than Hive, it does not make sense to say `HIVE_URI` now. Let me update that in another PR so that you can rebase it. ########## File path: core/src/main/java/org/apache/iceberg/jdbc/JdbcTableOperations.java ########## @@ -0,0 +1,218 @@ +/* + * 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.jdbc; + +import java.sql.DataTruncation; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.SQLIntegrityConstraintViolationException; +import java.sql.SQLNonTransientConnectionException; +import java.sql.SQLTimeoutException; +import java.sql.SQLTransientConnectionException; +import java.sql.SQLWarning; +import java.util.Map; +import java.util.Objects; +import org.apache.iceberg.BaseMetastoreTableOperations; +import org.apache.iceberg.TableMetadata; +import org.apache.iceberg.catalog.TableIdentifier; +import org.apache.iceberg.exceptions.AlreadyExistsException; +import org.apache.iceberg.exceptions.CommitFailedException; +import org.apache.iceberg.exceptions.NoSuchTableException; +import org.apache.iceberg.io.FileIO; +import org.apache.iceberg.relocated.com.google.common.collect.Maps; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +class JdbcTableOperations extends BaseMetastoreTableOperations { + + private static final Logger LOG = LoggerFactory.getLogger(JdbcTableOperations.class); + private final String catalogName; + private final TableIdentifier tableIdentifier; + private final FileIO fileIO; + private final JdbcClientPool connections; + + protected JdbcTableOperations(JdbcClientPool dbConnPool, FileIO fileIO, String catalogName, + TableIdentifier tableIdentifier) { + this.catalogName = catalogName; + this.tableIdentifier = tableIdentifier; + this.fileIO = fileIO; + this.connections = dbConnPool; + } + + @Override + public void doRefresh() { + Map<String, String> table; + + try { + table = getTable(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException("Interrupted during refresh", e); + } catch (SQLException e) { + // unknown exception happened when getting table from catalog + throw new UncheckedSQLException( + String.format("Failed to get table %s from catalog %s", tableIdentifier, catalogName), e); + } + + // Table not exists AND currentMetadataLocation is not NULL! + if (table.isEmpty() && currentMetadataLocation() != null) { + throw new NoSuchTableException("Failed to get table %s from catalog %s!" + + " maybe another process deleted it!", tableIdentifier, catalogName); + } + + // Table not exists in the catalog! metadataLocation is null here! + if (table.isEmpty()) { + refreshFromMetadataLocation(null); + return; + } + + // Table exists but metadataLocation is null + if (table.getOrDefault("metadata_location", null) == null) { + throw new RuntimeException(String.format("Failed to get metadata location of the table %s from catalog %s", + tableIdentifier, catalogName)); + } + + refreshFromMetadataLocation(table.get("metadata_location")); + } + + @Override + public void doCommit(TableMetadata base, TableMetadata metadata) { + String newMetadataLocation = writeNewMetadata(metadata, currentVersion() + 1); + try { + Map<String, String> table = getTable(); + + if (!table.isEmpty()) { + validateMetadataLocation(table, base); + String oldMetadataLocation = base.metadataFileLocation(); + // Start atomic update + updateTable(newMetadataLocation, oldMetadataLocation); + } else { + // table not exists create it! + createTable(newMetadataLocation); + } + + } catch (SQLIntegrityConstraintViolationException e) { + throw new AlreadyExistsException(e, "Table already exists! maybe another process created it!"); + } catch (SQLTimeoutException e) { + throw new UncheckedSQLException("Database Connection timeout!", e); + } catch (SQLTransientConnectionException | SQLNonTransientConnectionException e) { + throw new UncheckedSQLException("Database Connection failed!", e); + } catch (DataTruncation e) { + throw new UncheckedSQLException("Database data truncation error!", e); + } catch (SQLWarning e) { + throw new UncheckedSQLException("Database warning!", e); + } catch (SQLException e) { + throw new UncheckedSQLException("Failed to connect to database!", e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException("Interrupted during commit", e); + } + } + + private void updateTable(String newMetadataLocation, String oldMetadataLocation) + throws SQLException, InterruptedException { + int updatedRecords = connections.run(conn -> { + try (PreparedStatement sql = conn.prepareStatement(JdbcUtil.DO_COMMIT_SQL)) { + // UPDATE + sql.setString(1, newMetadataLocation); + sql.setString(2, oldMetadataLocation); + // WHERE + sql.setString(3, catalogName); + sql.setString(4, JdbcUtil.namespaceToString(tableIdentifier.namespace())); + sql.setString(5, tableIdentifier.name()); + sql.setString(6, oldMetadataLocation); + return sql.executeUpdate(); + } + }); + + if (updatedRecords == 1) { + LOG.debug("Successfully committed to existing table: {}", tableIdentifier); + } else { + throw new CommitFailedException("Failed to commit the table %s from catalog %s! " + + "Maybe another process changed it!", tableIdentifier, catalogName); + } + + } + + private void createTable(String newMetadataLocation) throws SQLException, InterruptedException { + int insertRecord = connections.run(conn -> { + try (PreparedStatement sql = conn.prepareStatement(JdbcUtil.DO_COMMIT_CREATE_SQL)) { + sql.setString(1, catalogName); + sql.setString(2, JdbcUtil.namespaceToString(tableIdentifier.namespace())); + sql.setString(3, tableIdentifier.name()); + sql.setString(4, newMetadataLocation); + return sql.executeUpdate(); + } + }); + + if (insertRecord == 1) { + LOG.debug("Successfully committed to new table: {}", tableIdentifier); + } else { + throw new CommitFailedException("Failed to commit the table %s from catalog %s", tableIdentifier, catalogName); + } + } + + private void validateMetadataLocation(Map<String, String> table, TableMetadata base) { + String catalogMetadataLocation = !table.isEmpty() ? table.get("metadata_location") : null; + String baseMetadataLocation = base != null ? base.metadataFileLocation() : null; + + if (!Objects.equals(baseMetadataLocation, catalogMetadataLocation)) { + throw new CommitFailedException( + "Cannot commit %s because base metadata location '%s' is not same as the current Catalog location '%s'", + tableIdentifier, baseMetadataLocation, catalogMetadataLocation); + } + } + + @Override + public FileIO io() { + return fileIO; + } + + @Override + protected String tableName() { + return tableIdentifier.toString(); + } + + private Map<String, String> getTable() throws UncheckedSQLException, SQLException, InterruptedException { + return connections.run(conn -> { + Map<String, String> table = Maps.newHashMap(); + + try (PreparedStatement sql = conn.prepareStatement(JdbcUtil.LOAD_TABLE_SQL)) { + sql.setString(1, catalogName); + sql.setString(2, JdbcUtil.namespaceToString(tableIdentifier.namespace())); + sql.setString(3, tableIdentifier.name()); + ResultSet rs = sql.executeQuery(); + + if (rs.next()) { + table.put("catalog_name", rs.getString("catalog_name")); Review comment: these column names should all be static variables in JdbcUtil ########## File path: core/src/main/java/org/apache/iceberg/jdbc/JdbcUtil.java ########## @@ -0,0 +1,80 @@ +/* + * 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.jdbc; + +import org.apache.iceberg.catalog.Namespace; +import org.apache.iceberg.catalog.TableIdentifier; +import org.apache.iceberg.relocated.com.google.common.base.Joiner; +import org.apache.iceberg.relocated.com.google.common.base.Splitter; +import org.apache.iceberg.relocated.com.google.common.collect.Iterables; + +public final class JdbcUtil { + protected static final String SQL_TABLE_NAME = "iceberg_tables"; Review comment: I think `CATALOG_TABLE_NAME` is a better name, in case we will introduce other tables in the future. Also as discussed above, I think we can use upper case for the table name. ########## File path: core/src/main/java/org/apache/iceberg/jdbc/JdbcCatalog.java ########## @@ -0,0 +1,403 @@ +/* + * 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.jdbc; + +import java.io.Closeable; +import java.sql.DatabaseMetaData; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.SQLIntegrityConstraintViolationException; +import java.sql.SQLNonTransientConnectionException; +import java.sql.SQLTimeoutException; +import java.sql.SQLTransientConnectionException; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import org.apache.hadoop.conf.Configurable; +import org.apache.hadoop.conf.Configuration; +import org.apache.iceberg.BaseMetastoreCatalog; +import org.apache.iceberg.CatalogProperties; +import org.apache.iceberg.CatalogUtil; +import org.apache.iceberg.TableMetadata; +import org.apache.iceberg.TableOperations; +import org.apache.iceberg.catalog.Namespace; +import org.apache.iceberg.catalog.SupportsNamespaces; +import org.apache.iceberg.catalog.TableIdentifier; +import org.apache.iceberg.exceptions.AlreadyExistsException; +import org.apache.iceberg.exceptions.NamespaceNotEmptyException; +import org.apache.iceberg.exceptions.NoSuchNamespaceException; +import org.apache.iceberg.exceptions.NoSuchTableException; +import org.apache.iceberg.hadoop.HadoopFileIO; +import org.apache.iceberg.io.FileIO; +import org.apache.iceberg.relocated.com.google.common.base.Joiner; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class JdbcCatalog extends BaseMetastoreCatalog implements Configurable, SupportsNamespaces, Closeable { + + public static final String PROPERTY_PREFIX = "connection.parameter."; + private static final Logger LOG = LoggerFactory.getLogger(JdbcCatalog.class); + private static final Joiner SLASH = Joiner.on("/"); + + private FileIO io; + private String catalogName = "jdbc"; + private String warehouseLocation; + private Configuration conf; + private JdbcClientPool connections; + + public JdbcCatalog() { + } + + @Override + public void initialize(String name, Map<String, String> properties) { + Preconditions.checkArgument(!properties.getOrDefault(CatalogProperties.HIVE_URI, "").isEmpty(), + "No connection url provided for jdbc catalog!"); + Preconditions.checkArgument(!properties.getOrDefault(CatalogProperties.WAREHOUSE_LOCATION, "").isEmpty(), + "Cannot initialize Jdbc Catalog because warehousePath must not be null!"); + + this.warehouseLocation = properties.get(CatalogProperties.WAREHOUSE_LOCATION).replaceAll("/$", ""); + this.catalogName = name == null ? "jdbc" : name; Review comment: `catalogName` is already `jdbc` if not set, so only need to do a `if` statement. ########## File path: core/src/main/java/org/apache/iceberg/jdbc/JdbcCatalog.java ########## @@ -0,0 +1,403 @@ +/* + * 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.jdbc; + +import java.io.Closeable; +import java.sql.DatabaseMetaData; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.SQLIntegrityConstraintViolationException; +import java.sql.SQLNonTransientConnectionException; +import java.sql.SQLTimeoutException; +import java.sql.SQLTransientConnectionException; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import org.apache.hadoop.conf.Configurable; +import org.apache.hadoop.conf.Configuration; +import org.apache.iceberg.BaseMetastoreCatalog; +import org.apache.iceberg.CatalogProperties; +import org.apache.iceberg.CatalogUtil; +import org.apache.iceberg.TableMetadata; +import org.apache.iceberg.TableOperations; +import org.apache.iceberg.catalog.Namespace; +import org.apache.iceberg.catalog.SupportsNamespaces; +import org.apache.iceberg.catalog.TableIdentifier; +import org.apache.iceberg.exceptions.AlreadyExistsException; +import org.apache.iceberg.exceptions.NamespaceNotEmptyException; +import org.apache.iceberg.exceptions.NoSuchNamespaceException; +import org.apache.iceberg.exceptions.NoSuchTableException; +import org.apache.iceberg.hadoop.HadoopFileIO; +import org.apache.iceberg.io.FileIO; +import org.apache.iceberg.relocated.com.google.common.base.Joiner; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class JdbcCatalog extends BaseMetastoreCatalog implements Configurable, SupportsNamespaces, Closeable { + + public static final String PROPERTY_PREFIX = "connection.parameter."; + private static final Logger LOG = LoggerFactory.getLogger(JdbcCatalog.class); + private static final Joiner SLASH = Joiner.on("/"); + + private FileIO io; + private String catalogName = "jdbc"; + private String warehouseLocation; + private Configuration conf; + private JdbcClientPool connections; + + public JdbcCatalog() { + } + + @Override + public void initialize(String name, Map<String, String> properties) { + Preconditions.checkArgument(!properties.getOrDefault(CatalogProperties.HIVE_URI, "").isEmpty(), + "No connection url provided for jdbc catalog!"); + Preconditions.checkArgument(!properties.getOrDefault(CatalogProperties.WAREHOUSE_LOCATION, "").isEmpty(), + "Cannot initialize Jdbc Catalog because warehousePath must not be null!"); + + this.warehouseLocation = properties.get(CatalogProperties.WAREHOUSE_LOCATION).replaceAll("/$", ""); + this.catalogName = name == null ? "jdbc" : name; + String fileIOImpl = properties.get(CatalogProperties.FILE_IO_IMPL); + this.io = fileIOImpl == null ? + new HadoopFileIO(conf) : + CatalogUtil.loadFileIO(fileIOImpl, properties, conf); + + try { + initializeConnection(properties); + } catch (SQLTimeoutException e) { + throw new UncheckedSQLException("Database Connection timeout!", e); + } catch (SQLTransientConnectionException | SQLNonTransientConnectionException e) { + throw new UncheckedSQLException("Database Connection failed!", e); + } catch (SQLException e) { + throw new UncheckedSQLException("Failed to initialize catalog!", e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException("Interrupted in call to initialize!", e); + } + } + + private void initializeConnection(Map<String, String> properties) throws SQLException, InterruptedException { + LOG.debug("Connecting to Jdbc database {}", properties.get(CatalogProperties.HIVE_URI)); + connections = new JdbcClientPool(properties.get(CatalogProperties.HIVE_URI), properties); + initializeCatalogTables(); + } + + private void initializeCatalogTables() throws InterruptedException, SQLException { + // need to check multiple times because some databases are using different naming standard. + // ex: H2db keeping table names as uppercase, PostgreSQL is keeping lowercase Review comment: I just verified, postgres can accept all upper letter table name in queries. The table name is case insensitve anyway in SQL standard. So I think it is better to only check for upper case table name. Also change `SQL_TABLE_NAME` value to upper case. ########## File path: core/src/main/java/org/apache/iceberg/jdbc/JdbcTableOperations.java ########## @@ -0,0 +1,218 @@ +/* + * 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.jdbc; + +import java.sql.DataTruncation; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.SQLIntegrityConstraintViolationException; +import java.sql.SQLNonTransientConnectionException; +import java.sql.SQLTimeoutException; +import java.sql.SQLTransientConnectionException; +import java.sql.SQLWarning; +import java.util.Map; +import java.util.Objects; +import org.apache.iceberg.BaseMetastoreTableOperations; +import org.apache.iceberg.TableMetadata; +import org.apache.iceberg.catalog.TableIdentifier; +import org.apache.iceberg.exceptions.AlreadyExistsException; +import org.apache.iceberg.exceptions.CommitFailedException; +import org.apache.iceberg.exceptions.NoSuchTableException; +import org.apache.iceberg.io.FileIO; +import org.apache.iceberg.relocated.com.google.common.collect.Maps; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +class JdbcTableOperations extends BaseMetastoreTableOperations { + + private static final Logger LOG = LoggerFactory.getLogger(JdbcTableOperations.class); + private final String catalogName; + private final TableIdentifier tableIdentifier; + private final FileIO fileIO; + private final JdbcClientPool connections; + + protected JdbcTableOperations(JdbcClientPool dbConnPool, FileIO fileIO, String catalogName, + TableIdentifier tableIdentifier) { + this.catalogName = catalogName; + this.tableIdentifier = tableIdentifier; + this.fileIO = fileIO; + this.connections = dbConnPool; + } + + @Override + public void doRefresh() { + Map<String, String> table; + + try { + table = getTable(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException("Interrupted during refresh", e); + } catch (SQLException e) { + // unknown exception happened when getting table from catalog + throw new UncheckedSQLException( + String.format("Failed to get table %s from catalog %s", tableIdentifier, catalogName), e); + } + + // Table not exists AND currentMetadataLocation is not NULL! + if (table.isEmpty() && currentMetadataLocation() != null) { + throw new NoSuchTableException("Failed to get table %s from catalog %s!" + + " maybe another process deleted it!", tableIdentifier, catalogName); + } + + // Table not exists in the catalog! metadataLocation is null here! + if (table.isEmpty()) { + refreshFromMetadataLocation(null); + return; + } + + // Table exists but metadataLocation is null + if (table.getOrDefault("metadata_location", null) == null) { + throw new RuntimeException(String.format("Failed to get metadata location of the table %s from catalog %s", + tableIdentifier, catalogName)); + } + + refreshFromMetadataLocation(table.get("metadata_location")); + } + + @Override + public void doCommit(TableMetadata base, TableMetadata metadata) { + String newMetadataLocation = writeNewMetadata(metadata, currentVersion() + 1); + try { + Map<String, String> table = getTable(); + + if (!table.isEmpty()) { + validateMetadataLocation(table, base); + String oldMetadataLocation = base.metadataFileLocation(); + // Start atomic update + updateTable(newMetadataLocation, oldMetadataLocation); + } else { + // table not exists create it! + createTable(newMetadataLocation); + } + + } catch (SQLIntegrityConstraintViolationException e) { + throw new AlreadyExistsException(e, "Table already exists! maybe another process created it!"); + } catch (SQLTimeoutException e) { + throw new UncheckedSQLException("Database Connection timeout!", e); + } catch (SQLTransientConnectionException | SQLNonTransientConnectionException e) { + throw new UncheckedSQLException("Database Connection failed!", e); + } catch (DataTruncation e) { + throw new UncheckedSQLException("Database data truncation error!", e); + } catch (SQLWarning e) { + throw new UncheckedSQLException("Database warning!", e); + } catch (SQLException e) { + throw new UncheckedSQLException("Failed to connect to database!", e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException("Interrupted during commit", e); + } + } + + private void updateTable(String newMetadataLocation, String oldMetadataLocation) + throws SQLException, InterruptedException { + int updatedRecords = connections.run(conn -> { + try (PreparedStatement sql = conn.prepareStatement(JdbcUtil.DO_COMMIT_SQL)) { + // UPDATE + sql.setString(1, newMetadataLocation); + sql.setString(2, oldMetadataLocation); + // WHERE + sql.setString(3, catalogName); + sql.setString(4, JdbcUtil.namespaceToString(tableIdentifier.namespace())); + sql.setString(5, tableIdentifier.name()); + sql.setString(6, oldMetadataLocation); + return sql.executeUpdate(); + } + }); + + if (updatedRecords == 1) { + LOG.debug("Successfully committed to existing table: {}", tableIdentifier); + } else { + throw new CommitFailedException("Failed to commit the table %s from catalog %s! " + + "Maybe another process changed it!", tableIdentifier, catalogName); + } + + } + + private void createTable(String newMetadataLocation) throws SQLException, InterruptedException { + int insertRecord = connections.run(conn -> { + try (PreparedStatement sql = conn.prepareStatement(JdbcUtil.DO_COMMIT_CREATE_SQL)) { + sql.setString(1, catalogName); + sql.setString(2, JdbcUtil.namespaceToString(tableIdentifier.namespace())); + sql.setString(3, tableIdentifier.name()); + sql.setString(4, newMetadataLocation); + return sql.executeUpdate(); + } + }); + + if (insertRecord == 1) { + LOG.debug("Successfully committed to new table: {}", tableIdentifier); + } else { + throw new CommitFailedException("Failed to commit the table %s from catalog %s", tableIdentifier, catalogName); Review comment: should indicate this is a create table operation, maybe message can be `fail to create the table ...`. Same for the update table exception above. ########## File path: core/src/main/java/org/apache/iceberg/jdbc/JdbcCatalog.java ########## @@ -0,0 +1,403 @@ +/* + * 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.jdbc; + +import java.io.Closeable; +import java.sql.DatabaseMetaData; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.SQLIntegrityConstraintViolationException; +import java.sql.SQLNonTransientConnectionException; +import java.sql.SQLTimeoutException; +import java.sql.SQLTransientConnectionException; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import org.apache.hadoop.conf.Configurable; +import org.apache.hadoop.conf.Configuration; +import org.apache.iceberg.BaseMetastoreCatalog; +import org.apache.iceberg.CatalogProperties; +import org.apache.iceberg.CatalogUtil; +import org.apache.iceberg.TableMetadata; +import org.apache.iceberg.TableOperations; +import org.apache.iceberg.catalog.Namespace; +import org.apache.iceberg.catalog.SupportsNamespaces; +import org.apache.iceberg.catalog.TableIdentifier; +import org.apache.iceberg.exceptions.AlreadyExistsException; +import org.apache.iceberg.exceptions.NamespaceNotEmptyException; +import org.apache.iceberg.exceptions.NoSuchNamespaceException; +import org.apache.iceberg.exceptions.NoSuchTableException; +import org.apache.iceberg.hadoop.HadoopFileIO; +import org.apache.iceberg.io.FileIO; +import org.apache.iceberg.relocated.com.google.common.base.Joiner; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class JdbcCatalog extends BaseMetastoreCatalog implements Configurable, SupportsNamespaces, Closeable { + + public static final String PROPERTY_PREFIX = "connection.parameter."; + private static final Logger LOG = LoggerFactory.getLogger(JdbcCatalog.class); + private static final Joiner SLASH = Joiner.on("/"); + + private FileIO io; + private String catalogName = "jdbc"; + private String warehouseLocation; + private Configuration conf; + private JdbcClientPool connections; + + public JdbcCatalog() { + } + + @Override + public void initialize(String name, Map<String, String> properties) { + Preconditions.checkArgument(!properties.getOrDefault(CatalogProperties.HIVE_URI, "").isEmpty(), + "No connection url provided for jdbc catalog!"); + Preconditions.checkArgument(!properties.getOrDefault(CatalogProperties.WAREHOUSE_LOCATION, "").isEmpty(), + "Cannot initialize Jdbc Catalog because warehousePath must not be null!"); + + this.warehouseLocation = properties.get(CatalogProperties.WAREHOUSE_LOCATION).replaceAll("/$", ""); + this.catalogName = name == null ? "jdbc" : name; + String fileIOImpl = properties.get(CatalogProperties.FILE_IO_IMPL); + this.io = fileIOImpl == null ? + new HadoopFileIO(conf) : + CatalogUtil.loadFileIO(fileIOImpl, properties, conf); + + try { + initializeConnection(properties); + } catch (SQLTimeoutException e) { + throw new UncheckedSQLException("Database Connection timeout!", e); + } catch (SQLTransientConnectionException | SQLNonTransientConnectionException e) { + throw new UncheckedSQLException("Database Connection failed!", e); + } catch (SQLException e) { + throw new UncheckedSQLException("Failed to initialize catalog!", e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException("Interrupted in call to initialize!", e); + } + } + + private void initializeConnection(Map<String, String> properties) throws SQLException, InterruptedException { + LOG.debug("Connecting to Jdbc database {}", properties.get(CatalogProperties.HIVE_URI)); + connections = new JdbcClientPool(properties.get(CatalogProperties.HIVE_URI), properties); + initializeCatalogTables(); + } + + private void initializeCatalogTables() throws InterruptedException, SQLException { + // need to check multiple times because some databases are using different naming standard. + // ex: H2db keeping table names as uppercase, PostgreSQL is keeping lowercase + + boolean exists = connections.run(conn -> { + boolean foundTable = false; + DatabaseMetaData dbMeta = conn.getMetaData(); + ResultSet tables = dbMeta.getTables(null, null, JdbcUtil.SQL_TABLE_NAME, null); + if (tables.next()) { + foundTable = true; + } + tables.close(); + ResultSet tablesUpper = dbMeta.getTables(null, null, JdbcUtil.SQL_TABLE_NAME.toUpperCase(), null); + if (tablesUpper.next()) { + foundTable = true; + } + tablesUpper.close(); + ResultSet tablesLower = dbMeta.getTables(null, null, JdbcUtil.SQL_TABLE_NAME.toLowerCase(), null); + if (tablesLower.next()) { + foundTable = true; + } + tablesLower.close(); + return foundTable; + }); + + // create table if not exits + if (!exists) { + connections.run(conn -> conn.prepareStatement(JdbcUtil.SQL_CREATE_CATALOG_TABLE).execute()); + LOG.debug("Created table {} to store iceberg tables!", JdbcUtil.SQL_TABLE_NAME); + } + } + + @Override + protected TableOperations newTableOps(TableIdentifier tableIdentifier) { + return new JdbcTableOperations(connections, io, catalogName, tableIdentifier); + } + + @Override + protected String defaultWarehouseLocation(TableIdentifier table) { + if (table.hasNamespace()) { + return SLASH.join(defaultNamespaceLocation(table.namespace()), table.name()); + } + return SLASH.join(defaultNamespaceLocation(table.namespace()), table.name()); + } + + @Override + public boolean dropTable(TableIdentifier identifier, boolean purge) { + + int deletedRecords; + try { + deletedRecords = connections.run(conn -> { + try (PreparedStatement sql = conn.prepareStatement(JdbcUtil.DROP_TABLE_SQL)) { + sql.setString(1, catalogName); + sql.setString(2, JdbcUtil.namespaceToString(identifier.namespace())); + sql.setString(3, identifier.name()); + return sql.executeUpdate(); + } + }); + } catch (SQLException e) { + throw new UncheckedSQLException("Failed to drop " + identifier, e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException("Interrupted in call to dropTable", e); + } + + if (deletedRecords > 0) { + LOG.debug("Successfully dropped table {}.", identifier); + } else { + LOG.debug("Cannot drop table: {}! table not found in the catalog.", identifier); + return false; + } + + TableOperations ops = newTableOps(identifier); + TableMetadata lastMetadata = ops.current(); + + if (purge && lastMetadata != null) { + CatalogUtil.dropTableData(ops.io(), lastMetadata); + LOG.info("Table {} data purged!", identifier); + } + return true; Review comment: nit: space after `if` statement ########## File path: core/src/main/java/org/apache/iceberg/jdbc/JdbcCatalog.java ########## @@ -0,0 +1,403 @@ +/* + * 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.jdbc; + +import java.io.Closeable; +import java.sql.DatabaseMetaData; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.SQLIntegrityConstraintViolationException; +import java.sql.SQLNonTransientConnectionException; +import java.sql.SQLTimeoutException; +import java.sql.SQLTransientConnectionException; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import org.apache.hadoop.conf.Configurable; +import org.apache.hadoop.conf.Configuration; +import org.apache.iceberg.BaseMetastoreCatalog; +import org.apache.iceberg.CatalogProperties; +import org.apache.iceberg.CatalogUtil; +import org.apache.iceberg.TableMetadata; +import org.apache.iceberg.TableOperations; +import org.apache.iceberg.catalog.Namespace; +import org.apache.iceberg.catalog.SupportsNamespaces; +import org.apache.iceberg.catalog.TableIdentifier; +import org.apache.iceberg.exceptions.AlreadyExistsException; +import org.apache.iceberg.exceptions.NamespaceNotEmptyException; +import org.apache.iceberg.exceptions.NoSuchNamespaceException; +import org.apache.iceberg.exceptions.NoSuchTableException; +import org.apache.iceberg.hadoop.HadoopFileIO; +import org.apache.iceberg.io.FileIO; +import org.apache.iceberg.relocated.com.google.common.base.Joiner; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class JdbcCatalog extends BaseMetastoreCatalog implements Configurable, SupportsNamespaces, Closeable { + + public static final String PROPERTY_PREFIX = "connection.parameter."; + private static final Logger LOG = LoggerFactory.getLogger(JdbcCatalog.class); + private static final Joiner SLASH = Joiner.on("/"); + + private FileIO io; + private String catalogName = "jdbc"; + private String warehouseLocation; + private Configuration conf; + private JdbcClientPool connections; + + public JdbcCatalog() { + } + + @Override + public void initialize(String name, Map<String, String> properties) { + Preconditions.checkArgument(!properties.getOrDefault(CatalogProperties.HIVE_URI, "").isEmpty(), + "No connection url provided for jdbc catalog!"); + Preconditions.checkArgument(!properties.getOrDefault(CatalogProperties.WAREHOUSE_LOCATION, "").isEmpty(), + "Cannot initialize Jdbc Catalog because warehousePath must not be null!"); + + this.warehouseLocation = properties.get(CatalogProperties.WAREHOUSE_LOCATION).replaceAll("/$", ""); + this.catalogName = name == null ? "jdbc" : name; + String fileIOImpl = properties.get(CatalogProperties.FILE_IO_IMPL); + this.io = fileIOImpl == null ? + new HadoopFileIO(conf) : + CatalogUtil.loadFileIO(fileIOImpl, properties, conf); + + try { + initializeConnection(properties); + } catch (SQLTimeoutException e) { + throw new UncheckedSQLException("Database Connection timeout!", e); + } catch (SQLTransientConnectionException | SQLNonTransientConnectionException e) { + throw new UncheckedSQLException("Database Connection failed!", e); + } catch (SQLException e) { + throw new UncheckedSQLException("Failed to initialize catalog!", e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException("Interrupted in call to initialize!", e); + } + } + + private void initializeConnection(Map<String, String> properties) throws SQLException, InterruptedException { + LOG.debug("Connecting to Jdbc database {}", properties.get(CatalogProperties.HIVE_URI)); + connections = new JdbcClientPool(properties.get(CatalogProperties.HIVE_URI), properties); + initializeCatalogTables(); + } + + private void initializeCatalogTables() throws InterruptedException, SQLException { + // need to check multiple times because some databases are using different naming standard. + // ex: H2db keeping table names as uppercase, PostgreSQL is keeping lowercase + + boolean exists = connections.run(conn -> { + boolean foundTable = false; + DatabaseMetaData dbMeta = conn.getMetaData(); + ResultSet tables = dbMeta.getTables(null, null, JdbcUtil.SQL_TABLE_NAME, null); + if (tables.next()) { + foundTable = true; + } + tables.close(); + ResultSet tablesUpper = dbMeta.getTables(null, null, JdbcUtil.SQL_TABLE_NAME.toUpperCase(), null); + if (tablesUpper.next()) { + foundTable = true; + } + tablesUpper.close(); + ResultSet tablesLower = dbMeta.getTables(null, null, JdbcUtil.SQL_TABLE_NAME.toLowerCase(), null); + if (tablesLower.next()) { + foundTable = true; + } + tablesLower.close(); + return foundTable; + }); + + // create table if not exits + if (!exists) { + connections.run(conn -> conn.prepareStatement(JdbcUtil.SQL_CREATE_CATALOG_TABLE).execute()); + LOG.debug("Created table {} to store iceberg tables!", JdbcUtil.SQL_TABLE_NAME); + } + } + + @Override + protected TableOperations newTableOps(TableIdentifier tableIdentifier) { + return new JdbcTableOperations(connections, io, catalogName, tableIdentifier); + } + + @Override + protected String defaultWarehouseLocation(TableIdentifier table) { + if (table.hasNamespace()) { + return SLASH.join(defaultNamespaceLocation(table.namespace()), table.name()); + } + return SLASH.join(defaultNamespaceLocation(table.namespace()), table.name()); Review comment: nit: space after `if` statement ---------------------------------------------------------------- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
