liunaijie commented on code in PR #6842: URL: https://github.com/apache/seatunnel/pull/6842#discussion_r1624053278
########## seatunnel-connectors-v2/connector-hive/src/main/java/org/apache/seatunnel/connectors/seatunnel/hive/catalog/HiveJDBCCatalog.java: ########## @@ -0,0 +1,451 @@ +/* + * 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.seatunnel.connectors.seatunnel.hive.catalog; + +import org.apache.seatunnel.api.configuration.ReadonlyConfig; +import org.apache.seatunnel.api.sink.SaveModePlaceHolder; +import org.apache.seatunnel.api.table.catalog.Catalog; +import org.apache.seatunnel.api.table.catalog.CatalogTable; +import org.apache.seatunnel.api.table.catalog.Column; +import org.apache.seatunnel.api.table.catalog.PhysicalColumn; +import org.apache.seatunnel.api.table.catalog.TableIdentifier; +import org.apache.seatunnel.api.table.catalog.TablePath; +import org.apache.seatunnel.api.table.catalog.TableSchema; +import org.apache.seatunnel.api.table.catalog.exception.CatalogException; +import org.apache.seatunnel.api.table.catalog.exception.DatabaseAlreadyExistException; +import org.apache.seatunnel.api.table.catalog.exception.DatabaseNotExistException; +import org.apache.seatunnel.api.table.catalog.exception.TableAlreadyExistException; +import org.apache.seatunnel.api.table.catalog.exception.TableNotExistException; +import org.apache.seatunnel.connectors.seatunnel.hive.sink.HiveSinkOptions; + +import org.apache.commons.lang3.StringUtils; + +import lombok.extern.slf4j.Slf4j; +import shade.org.apache.commons.lang3.StringEscapeUtils; + +import java.io.Serializable; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; + +@Slf4j +public class HiveJDBCCatalog implements Catalog, Serializable { + + private final String catalogName = "Hive"; + private final ReadonlyConfig config; + private final boolean supportMsck; + + private Connection connection; + + public HiveJDBCCatalog(ReadonlyConfig config) { + try { + Class.forName("org.apache.hive.jdbc.HiveDriver"); + } catch (ClassNotFoundException e) { + throw new CatalogException(e); + } + this.config = config; + supportMsck = config.get(HiveSinkOptions.SUPPORT_MSCK_REPAIR); + } + + public HiveTable getTableInformation(TablePath tablePath, boolean throwExceptionIfNotExist) { + if (!tableExists(tablePath)) { + if (throwExceptionIfNotExist) { + throw new TableNotExistException(catalogName, tablePath); + } else { + return null; + } + } + String describeFormattedTableQuery = "describe formatted " + tablePath.getFullName(); + try (PreparedStatement ps = connection.prepareStatement(describeFormattedTableQuery)) { + ResultSet rs = ps.executeQuery(); + return generateHiveTableFromQueryResult(rs, tablePath); + } catch (SQLException e) { + throw new CatalogException( + String.format("get table information [%s] failed", tablePath.getFullName()), e); + } + } + + public void addPartitions( + String dbName, String tableName, List<String> partitions, String baseLocation) + throws SQLException { + if (partitions.isEmpty()) { + return; + } + StringBuilder stringBuilder = new StringBuilder(); + if (supportMsck) { + stringBuilder.append("MSCK REPAIR TABLE "); + stringBuilder.append(dbName); + stringBuilder.append("."); + stringBuilder.append(tableName); + } else { + stringBuilder.append("ALTER TABLE "); + stringBuilder.append(dbName); + stringBuilder.append("."); + stringBuilder.append(tableName); + stringBuilder.append(" ADD IF NOT EXISTS "); + for (String partition : partitions) { + stringBuilder.append(generatePartitionSyntax(partition)); + stringBuilder.append(" LOCATION "); + stringBuilder.append("'"); + stringBuilder.append(baseLocation); + stringBuilder.append("/"); + stringBuilder.append(partition); + stringBuilder.append("'"); + } + } + String execSql = stringBuilder.toString(); + try (Statement statement = connection.createStatement()) { + statement.execute(execSql); + } + } + + public void dropPartitions(String dbName, String tableName, List<String> partitions) + throws SQLException { + if (partitions.isEmpty()) { + return; + } + StringBuilder stringBuilder = new StringBuilder(); + if (supportMsck) { + stringBuilder.append("MSCK REPAIR TABLE "); + stringBuilder.append(dbName); + stringBuilder.append("."); + stringBuilder.append(tableName); + } else { + stringBuilder.append("ALTER TABLE "); + stringBuilder.append(dbName); + stringBuilder.append("."); + stringBuilder.append(tableName); + stringBuilder.append(" DROP IF EXISTS "); + for (String partition : partitions) { + stringBuilder.append(generatePartitionSyntax(partition)); + } + } + String execSql = stringBuilder.toString(); + try (Statement statement = connection.createStatement()) { + statement.execute(execSql); + } + } + + private String generatePartitionSyntax(String partition) { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append(" PARTITION "); + stringBuilder.append("("); + String[] partitions = partition.split("/"); + for (String nameAndValue : partitions) { + int index = nameAndValue.indexOf("="); + stringBuilder.append(nameAndValue, 0, index); + stringBuilder.append(" = '"); + stringBuilder.append(nameAndValue.substring(index + 1)); + stringBuilder.append("',"); + } + stringBuilder.deleteCharAt(stringBuilder.length() - 1); + stringBuilder.append(") "); + return stringBuilder.toString(); + } + + @Override + public void open() throws CatalogException { + try { + String jdbcUrl = config.get(HiveSinkOptions.HIVE_JDBC_URL); + connection = DriverManager.getConnection(jdbcUrl); + } catch (SQLException e) { + throw new CatalogException(e); + } + } + + @Override + public void close() throws CatalogException { + try { + connection.close(); + } catch (SQLException e) { + throw new CatalogException(e); + } + } + + @Override + public String name() { + return catalogName; + } + + @Override + public String getDefaultDatabase() throws CatalogException { + return "default"; + } + + @Override + public boolean databaseExists(String databaseName) throws CatalogException { + return listDatabases().contains(databaseName); + } + + @Override + public List<String> listDatabases() throws CatalogException { + List<String> databases = new ArrayList<>(); + try (PreparedStatement ps = connection.prepareStatement("SHOW DATABASES")) { + ResultSet rs = ps.executeQuery(); + while (rs.next()) { + String database = rs.getString(1); + databases.add(database); + } + } catch (SQLException e) { + throw new CatalogException("list databases failed", e); + } + Collections.sort(databases); + return databases; + } + + @Override + public List<String> listTables(String databaseName) + throws CatalogException, DatabaseNotExistException { + if (!databaseExists(databaseName)) { + throw new DatabaseNotExistException(catalogName, databaseName); + } + List<String> tables = new ArrayList<>(); + String TABLES_QUERY_WITH_DATABASE_QUERY = "SHOW TABLES IN " + databaseName; + try (PreparedStatement ps = connection.prepareStatement(TABLES_QUERY_WITH_DATABASE_QUERY)) { + ResultSet rs = ps.executeQuery(); + while (rs.next()) { + String table = rs.getString(1); + tables.add(table); + } + } catch (SQLException e) { + throw new CatalogException( + String.format("list tables of database [%s] failed", databaseName), e); + } + Collections.sort(tables); + return tables; + } + + @Override + public boolean tableExists(TablePath tablePath) throws CatalogException { + return listTables(tablePath.getDatabaseName()).contains(tablePath.getTableName()); + } + + @Override + public CatalogTable getTable(TablePath tablePath) + throws CatalogException, TableNotExistException { + return getTableInformation(tablePath, true).getCatalogTable(); + } + + @Override + public void createTable(TablePath tablePath, CatalogTable table, boolean ignoreIfExists) + throws TableAlreadyExistException, DatabaseNotExistException, CatalogException { + if (!databaseExists(tablePath.getDatabaseName())) { + throw new DatabaseNotExistException(catalogName, tablePath.getDatabaseName()); + } + if (tableExists(tablePath) && ignoreIfExists) { + return; + } + String template = config.get(HiveSinkOptions.SAVE_MODE_CREATE_TEMPLATE); + Optional<List<String>> partitionKeyOptional = + config.getOptional(HiveSinkOptions.SAVE_MODE_PARTITION_KEYS); + List<Column> columns = table.getTableSchema().getColumns(); + if (partitionKeyOptional.isPresent()) { + List<String> partitionKeys = partitionKeyOptional.get(); + columns = + columns.stream() + .filter(c -> !partitionKeys.contains(c.getName())) + .collect(Collectors.toList()); + } + String columnDef = + columns.stream() + .map(HiveTypeConvertor::columnToHiveType) + .collect(Collectors.joining(",\n")); + + String ddl = + template.replaceAll( + SaveModePlaceHolder.DATABASE.getReplacePlaceHolder(), + tablePath.getDatabaseName()) + .replaceAll( + SaveModePlaceHolder.TABLE_NAME.getReplacePlaceHolder(), + tablePath.getTableName()) + .replace(SaveModePlaceHolder.ROWTYPE_FIELDS.getPlaceHolder(), columnDef); + log.info("EXECUTE DDL SQL is \n {} \n", ddl); + try (Statement statement = connection.createStatement()) { + statement.execute(ddl); + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + @Override + public void dropTable(TablePath tablePath, boolean ignoreIfNotExists) + throws TableNotExistException, CatalogException { + String query = getDropTableQuery(tablePath, ignoreIfNotExists); + try (Statement stmt = connection.createStatement()) { + stmt.execute(query); + } catch (SQLException e) { + throw new CatalogException(e); + } + } + + @Override + public void createDatabase(TablePath tablePath, boolean ignoreIfExists) + throws DatabaseAlreadyExistException, CatalogException { + String query = getCreateDatabaseQuery(tablePath.getDatabaseName(), ignoreIfExists); + try (Statement stmt = connection.createStatement()) { + stmt.execute(query); + } catch (SQLException e) { + throw new CatalogException( + String.format("create database [%s] failed", tablePath.getDatabaseName()), e); + } + } + + @Override + public void dropDatabase(TablePath tablePath, boolean ignoreIfNotExists) + throws DatabaseNotExistException, CatalogException { + String query = getDropDatabaseQuery(tablePath.getDatabaseName(), ignoreIfNotExists); + try (Statement stmt = connection.createStatement()) { + stmt.execute(query); + } catch (SQLException e) { + throw new CatalogException( + String.format("drop database [%s] failed", tablePath.getDatabaseName()), e); + } + } + + @Override + public void truncateTable(TablePath tablePath, boolean ignoreIfNotExists) + throws TableNotExistException, CatalogException { + throw new UnsupportedOperationException("Does not support truncate table!"); + } + + @Override + public boolean isExistsData(TablePath tablePath) { + String tableName = tablePath.getFullName(); + String sql = String.format("select * from %s limit 1;", tableName); Review Comment: no, this method is to check whether this table has data. if use `show create table`, can't check has data or not. can only check table exist -- 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. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
