This is an automated email from the ASF dual-hosted git repository.
dengzh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/hive.git
The following commit(s) were added to refs/heads/master by this push:
new efa1bf74dc8 HIVE-27487: NPE in Hive JDBC storage handler (#4475)
(Zhihua Deng, reviewed by Akshat Mathur, Naveen Gangam)
efa1bf74dc8 is described below
commit efa1bf74dc83596a6022f79b2f4b16f3fc3afcf0
Author: dengzh <[email protected]>
AuthorDate: Tue Aug 8 20:39:18 2023 +0800
HIVE-27487: NPE in Hive JDBC storage handler (#4475) (Zhihua Deng, reviewed
by Akshat Mathur, Naveen Gangam)
---
.../apache/hive/storage/jdbc/JdbcRecordReader.java | 8 +-
.../org/apache/hive/storage/jdbc/JdbcSerDe.java | 11 +-
.../hive/storage/jdbc/dao/DatabaseAccessor.java | 2 +-
.../jdbc/dao/GenericJdbcDatabaseAccessor.java | 167 +++++++++++++--------
.../storage/jdbc/dao/HiveDatabaseAccessor.java | 16 ++
.../hive/storage/jdbc/dao/JdbcRecordIterator.java | 41 +++--
6 files changed, 153 insertions(+), 92 deletions(-)
diff --git
a/jdbc-handler/src/main/java/org/apache/hive/storage/jdbc/JdbcRecordReader.java
b/jdbc-handler/src/main/java/org/apache/hive/storage/jdbc/JdbcRecordReader.java
index 4884405b8d5..9a94612f13e 100644
---
a/jdbc-handler/src/main/java/org/apache/hive/storage/jdbc/JdbcRecordReader.java
+++
b/jdbc-handler/src/main/java/org/apache/hive/storage/jdbc/JdbcRecordReader.java
@@ -110,9 +110,13 @@ public class JdbcRecordReader implements
RecordReader<LongWritable, MapWritable>
if (iterator != null) {
iterator.close();
}
- if (dbAccessor != null) {
- dbAccessor = null;
+
+ try (DatabaseAccessor accessor = dbAccessor) {
+ } catch (Exception e) {
+ LOGGER.debug("Caught exception while trying to close DatabaseAccessor: "
+ + e.getMessage(), e);
}
+ dbAccessor = null;
}
diff --git
a/jdbc-handler/src/main/java/org/apache/hive/storage/jdbc/JdbcSerDe.java
b/jdbc-handler/src/main/java/org/apache/hive/storage/jdbc/JdbcSerDe.java
index b1c9d47d923..4c75bffcffa 100644
--- a/jdbc-handler/src/main/java/org/apache/hive/storage/jdbc/JdbcSerDe.java
+++ b/jdbc-handler/src/main/java/org/apache/hive/storage/jdbc/JdbcSerDe.java
@@ -72,10 +72,12 @@ public class JdbcSerDe extends AbstractSerDe {
throws SerDeException {
log.trace("Initializing the JdbcSerDe");
super.initialize(configuration, tableProperties, partitionProperties);
+ DatabaseAccessor dbAccessor = null;
try {
if
(properties.containsKey(JdbcStorageConfig.DATABASE_TYPE.getPropertyName())) {
Configuration tableConfig =
JdbcStorageConfigManager.convertPropertiesToConfiguration(properties);
- DatabaseAccessor dbAccessor =
DatabaseAccessorFactory.getAccessor(tableConfig);
+
+ dbAccessor = DatabaseAccessorFactory.getAccessor(tableConfig);
// Extract column names and types from properties
List<TypeInfo> hiveColumnTypesList;
if (properties.containsKey(Constants.JDBC_TABLE) &&
properties.containsKey(Constants.JDBC_QUERY)) {
@@ -131,7 +133,12 @@ public class JdbcSerDe extends AbstractSerDe {
row = new ArrayList<>(hiveColumnNames.length);
}
} catch (Exception e) {
- throw new SerDeException("Caught exception while initializing the
SqlSerDe", e);
+ throw new SerDeException("Caught exception while initializing the
SqlSerDe: " + e.getMessage(), e);
+ } finally {
+ try (AutoCloseable closeable = dbAccessor) {
+ } catch (Exception e) {
+ // ignore this
+ }
}
if (log.isDebugEnabled()) {
diff --git
a/jdbc-handler/src/main/java/org/apache/hive/storage/jdbc/dao/DatabaseAccessor.java
b/jdbc-handler/src/main/java/org/apache/hive/storage/jdbc/dao/DatabaseAccessor.java
index 11fcfed1939..454a787d962 100644
---
a/jdbc-handler/src/main/java/org/apache/hive/storage/jdbc/dao/DatabaseAccessor.java
+++
b/jdbc-handler/src/main/java/org/apache/hive/storage/jdbc/dao/DatabaseAccessor.java
@@ -26,7 +26,7 @@ import
org.apache.hive.storage.jdbc.exception.HiveJdbcDatabaseAccessException;
import java.io.IOException;
import java.util.List;
-public interface DatabaseAccessor {
+public interface DatabaseAccessor extends AutoCloseable {
List<String> getColumnNames(Configuration conf) throws
HiveJdbcDatabaseAccessException;
diff --git
a/jdbc-handler/src/main/java/org/apache/hive/storage/jdbc/dao/GenericJdbcDatabaseAccessor.java
b/jdbc-handler/src/main/java/org/apache/hive/storage/jdbc/dao/GenericJdbcDatabaseAccessor.java
index 39dd3eefacd..e016fe33d48 100644
---
a/jdbc-handler/src/main/java/org/apache/hive/storage/jdbc/dao/GenericJdbcDatabaseAccessor.java
+++
b/jdbc-handler/src/main/java/org/apache/hive/storage/jdbc/dao/GenericJdbcDatabaseAccessor.java
@@ -20,8 +20,6 @@ import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.conf.Constants;
-import org.apache.hadoop.hive.ql.exec.Utilities;
-import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.serde.serdeConstants;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory;
@@ -38,7 +36,6 @@ import
org.apache.hive.storage.jdbc.exception.HiveJdbcDatabaseAccessException;
import javax.sql.DataSource;
import java.io.IOException;
-import java.net.URISyntaxException;
import java.sql.Connection;
import java.sql.JDBCType;
import java.sql.PreparedStatement;
@@ -64,9 +61,55 @@ public class GenericJdbcDatabaseAccessor implements
DatabaseAccessor {
protected static final String DBCP_CONFIG_PREFIX =
Constants.JDBC_CONFIG_PREFIX + ".dbcp";
protected static final int DEFAULT_FETCH_SIZE = 1000;
protected static final Logger LOGGER =
LoggerFactory.getLogger(GenericJdbcDatabaseAccessor.class);
- protected DataSource dbcpDataSource = null;
+ private DataSource dbcpDataSource = null;
static final Pattern fromPattern = Pattern.compile("(.*?\\sfrom\\s)(.*+)",
Pattern.CASE_INSENSITIVE|Pattern.DOTALL);
+ private static ColumnMetadataAccessor<TypeInfo> typeInfoTranslator = (meta,
col) -> {
+ JDBCType type = JDBCType.valueOf(meta.getColumnType(col));
+ int prec = meta.getPrecision(col);
+ int scal = meta.getScale(col);
+ switch (type) {
+ case BIT:
+ case BOOLEAN:
+ return TypeInfoFactory.booleanTypeInfo;
+ case TINYINT:
+ return TypeInfoFactory.byteTypeInfo;
+ case SMALLINT:
+ return TypeInfoFactory.shortTypeInfo;
+ case INTEGER:
+ return TypeInfoFactory.intTypeInfo;
+ case BIGINT:
+ return TypeInfoFactory.longTypeInfo;
+ case CHAR:
+ return TypeInfoFactory.getCharTypeInfo(prec);
+ case VARCHAR:
+ case NVARCHAR:
+ case LONGNVARCHAR:
+ case LONGVARCHAR:
+ return TypeInfoFactory.getVarcharTypeInfo(Math.min(prec, 65535));
+ case DOUBLE:
+ return TypeInfoFactory.doubleTypeInfo;
+ case REAL:
+ case FLOAT:
+ return TypeInfoFactory.floatTypeInfo;
+ case DATE:
+ return TypeInfoFactory.dateTypeInfo;
+ case TIMESTAMP:
+ case TIMESTAMP_WITH_TIMEZONE:
+ return TypeInfoFactory.timestampTypeInfo;
+ case DECIMAL:
+ case NUMERIC:
+ return TypeInfoFactory.getDecimalTypeInfo(Math.min(prec, 38), scal);
+ case ARRAY:
+ // Best effort with the info that we have at the moment
+ return TypeInfoFactory.getListTypeInfo(TypeInfoFactory.unknownTypeInfo);
+ case STRUCT:
+ // Best effort with the info that we have at the moment
+ return TypeInfoFactory.getStructTypeInfo(Collections.emptyList(),
Collections.emptyList());
+ default:
+ return TypeInfoFactory.unknownTypeInfo;
+ }
+ };
public GenericJdbcDatabaseAccessor() {
}
@@ -90,17 +133,10 @@ public class GenericJdbcDatabaseAccessor implements
DatabaseAccessor {
ps = conn.prepareStatement(metadataQuery);
rs = ps.executeQuery();
- ResultSetMetaData metadata = rs.getMetaData();
- int numColumns = metadata.getColumnCount();
- List<T> columnMeta = new ArrayList<>(numColumns);
- for (int i = 0; i < numColumns; i++) {
- columnMeta.add(colAccessor.get(metadata, i + 1));
- }
-
- return columnMeta;
+ return getColumnMetadata(rs, colAccessor);
}
catch (Exception e) {
- throw new HiveJdbcDatabaseAccessException("", e);
+ throw new HiveJdbcDatabaseAccessException("Caught exception while trying
to get columns: " + e.getMessage(), e);
}
finally {
cleanupResources(conn, ps, rs);
@@ -108,6 +144,18 @@ public class GenericJdbcDatabaseAccessor implements
DatabaseAccessor {
}
+ private <T> List<T> getColumnMetadata(ResultSet rs,
ColumnMetadataAccessor<T> colAccessor)
+ throws Exception {
+ assert rs != null;
+ ResultSetMetaData metadata = rs.getMetaData();
+ int numColumns = metadata.getColumnCount();
+ List<T> columnMeta = new ArrayList<>(numColumns);
+ for (int i = 0; i < numColumns; i++) {
+ columnMeta.add(colAccessor.get(metadata, i + 1));
+ }
+ return columnMeta;
+ }
+
@Override
public List<String> getColumnNames(Configuration conf) throws
HiveJdbcDatabaseAccessException {
return getColumnMetadata(conf, ResultSetMetaData::getColumnName);
@@ -115,52 +163,15 @@ public class GenericJdbcDatabaseAccessor implements
DatabaseAccessor {
@Override
public List<TypeInfo> getColumnTypes(Configuration conf) throws
HiveJdbcDatabaseAccessException {
- return getColumnMetadata(conf, (meta, col) -> {
- JDBCType type = JDBCType.valueOf(meta.getColumnType(col));
- int prec = meta.getPrecision(col);
- int scal = meta.getScale(col);
- switch (type) {
- case BIT:
- case BOOLEAN:
- return TypeInfoFactory.booleanTypeInfo;
- case TINYINT:
- return TypeInfoFactory.byteTypeInfo;
- case SMALLINT:
- return TypeInfoFactory.shortTypeInfo;
- case INTEGER:
- return TypeInfoFactory.intTypeInfo;
- case BIGINT:
- return TypeInfoFactory.longTypeInfo;
- case CHAR:
- return TypeInfoFactory.getCharTypeInfo(prec);
- case VARCHAR:
- case NVARCHAR:
- case LONGNVARCHAR:
- case LONGVARCHAR:
- return TypeInfoFactory.getVarcharTypeInfo(Math.min(prec, 65535));
- case DOUBLE:
- return TypeInfoFactory.doubleTypeInfo;
- case REAL:
- case FLOAT:
- return TypeInfoFactory.floatTypeInfo;
- case DATE:
- return TypeInfoFactory.dateTypeInfo;
- case TIMESTAMP:
- case TIMESTAMP_WITH_TIMEZONE:
- return TypeInfoFactory.timestampTypeInfo;
- case DECIMAL:
- case NUMERIC:
- return TypeInfoFactory.getDecimalTypeInfo(Math.min(prec, 38), scal);
- case ARRAY:
- // Best effort with the info that we have at the moment
- return
TypeInfoFactory.getListTypeInfo(TypeInfoFactory.unknownTypeInfo);
- case STRUCT:
- // Best effort with the info that we have at the moment
- return TypeInfoFactory.getStructTypeInfo(Collections.emptyList(),
Collections.emptyList());
- default:
- return TypeInfoFactory.unknownTypeInfo;
- }
- });
+ return getColumnMetadata(conf, typeInfoTranslator);
+ }
+
+ protected List<String> getColNamesFromRS(ResultSet rs) throws Exception {
+ return getColumnMetadata(rs, ResultSetMetaData::getColumnName);
+ }
+
+ protected List<TypeInfo> getColTypesFromRS(ResultSet rs) throws Exception {
+ return getColumnMetadata(rs, typeInfoTranslator);
}
protected String getMetaDataQuery(String sql) {
@@ -197,7 +208,7 @@ public class GenericJdbcDatabaseAccessor implements
DatabaseAccessor {
throw he;
}
catch (Exception e) {
- LOGGER.error("Caught exception while trying to get the number of
records", e);
+ LOGGER.error("Caught exception while trying to get the number of
records: " + e.getMessage(), e);
throw new HiveJdbcDatabaseAccessException(e);
}
finally {
@@ -235,12 +246,12 @@ public class GenericJdbcDatabaseAccessor implements
DatabaseAccessor {
ps.setFetchSize(getFetchSize(conf));
rs = ps.executeQuery();
- return new JdbcRecordIterator(conn, ps, rs, conf);
+ return new JdbcRecordIterator(this, conn, ps, rs, conf);
}
catch (Exception e) {
LOGGER.error("Caught exception while trying to execute query", e);
cleanupResources(conn, ps, rs);
- throw new HiveJdbcDatabaseAccessException("Caught exception while trying
to execute query:" + e.getMessage(), e);
+ throw new HiveJdbcDatabaseAccessException("Caught exception while trying
to execute query: " + e.getMessage(), e);
}
}
@@ -261,7 +272,16 @@ public class GenericJdbcDatabaseAccessor implements
DatabaseAccessor {
conn = dbcpDataSource.getConnection();
ps = conn.prepareStatement(constructQuery(tableName, columnNames));
return new org.apache.hadoop.mapreduce.lib.db.DBOutputFormat()
- .new DBRecordWriter(conn, ps);
+ .new DBRecordWriter(conn, ps) {
+ @Override
+ public void close(TaskAttemptContext context) throws IOException {
+ try {
+ super.close(context);
+ } finally {
+ GenericJdbcDatabaseAccessor.this.close();
+ }
+ }
+ };
} catch (Exception e) {
cleanupResources(conn, ps, null);
throw new IOException(e.getMessage());
@@ -514,7 +534,7 @@ public class GenericJdbcDatabaseAccessor implements
DatabaseAccessor {
throw he;
}
catch (Exception e) {
- LOGGER.error("Caught exception while trying to get MIN/MAX of " +
partitionColumn, e);
+ LOGGER.error("Caught exception while trying to get MIN/MAX of " +
partitionColumn + ": " + e.getMessage(), e);
throw new HiveJdbcDatabaseAccessException(e);
}
finally {
@@ -550,4 +570,23 @@ public class GenericJdbcDatabaseAccessor implements
DatabaseAccessor {
private interface ColumnMetadataAccessor<T> {
T get(ResultSetMetaData metadata, Integer column) throws SQLException;
}
+
+ @Override
+ public void close() {
+ if (dbcpDataSource instanceof AutoCloseable) {
+ try (AutoCloseable closeable = (AutoCloseable) dbcpDataSource) {
+ } catch (Exception e) {
+ LOGGER.warn("Caught exception while trying to close the DataSource: "
+ + e.getMessage(), e);
+ }
+ dbcpDataSource = null;
+ }
+ }
+
+ @Override
+ protected void finalize() throws Throwable {
+ super.finalize();
+ close();
+ }
+
}
diff --git
a/jdbc-handler/src/main/java/org/apache/hive/storage/jdbc/dao/HiveDatabaseAccessor.java
b/jdbc-handler/src/main/java/org/apache/hive/storage/jdbc/dao/HiveDatabaseAccessor.java
index af60f593e83..adb126c03b9 100644
---
a/jdbc-handler/src/main/java/org/apache/hive/storage/jdbc/dao/HiveDatabaseAccessor.java
+++
b/jdbc-handler/src/main/java/org/apache/hive/storage/jdbc/dao/HiveDatabaseAccessor.java
@@ -17,6 +17,7 @@
*/
package org.apache.hive.storage.jdbc.dao;
+import java.sql.ResultSet;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.hadoop.conf.Configuration;
@@ -56,4 +57,19 @@ public class HiveDatabaseAccessor extends
GenericJdbcDatabaseAccessor {
}
return sql + " LIMIT " + limit;
}
+
+ @Override
+ protected List<String> getColNamesFromRS(ResultSet rs) throws Exception {
+ List<String> columnNames = super.getColNamesFromRS(rs);
+ return columnNames.stream()
+ .map(c -> {
+ int lastIndex = c.lastIndexOf(".");
+ return lastIndex == -1 ? c : c.substring(lastIndex + 1); })
+ .collect(Collectors.toList());
+ }
+
+ @Override
+ protected String getMetaDataQuery(String sql) {
+ return addLimitToQuery(sql, 0);
+ }
}
diff --git
a/jdbc-handler/src/main/java/org/apache/hive/storage/jdbc/dao/JdbcRecordIterator.java
b/jdbc-handler/src/main/java/org/apache/hive/storage/jdbc/dao/JdbcRecordIterator.java
index 6ba5a091b59..8cc4a72b42a 100644
---
a/jdbc-handler/src/main/java/org/apache/hive/storage/jdbc/dao/JdbcRecordIterator.java
+++
b/jdbc-handler/src/main/java/org/apache/hive/storage/jdbc/dao/JdbcRecordIterator.java
@@ -18,7 +18,6 @@ import com.google.common.base.Preconditions;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.conf.Constants;
import org.apache.hadoop.hive.serde.serdeConstants;
-import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector;
import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils;
@@ -29,15 +28,15 @@ import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
-import java.sql.ResultSetMetaData;
import java.sql.SQLDataException;
import java.sql.SQLException;
import java.sql.Types;
-import java.util.ArrayList;
+import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.stream.Collectors;
/**
* An iterator that allows iterating through a SQL resultset. Includes methods
to clear up resources.
@@ -49,10 +48,13 @@ public class JdbcRecordIterator implements
Iterator<Map<String, Object>> {
private Connection conn;
private PreparedStatement ps;
private ResultSet rs;
+ private GenericJdbcDatabaseAccessor accessor;
private String[] hiveColumnNames;
List<TypeInfo> hiveColumnTypesList;
- public JdbcRecordIterator(Connection conn, PreparedStatement ps, ResultSet
rs, Configuration conf) throws HiveJdbcDatabaseAccessException {
+ public JdbcRecordIterator(GenericJdbcDatabaseAccessor accessor, Connection
conn,
+ PreparedStatement ps, ResultSet rs, Configuration conf) throws
HiveJdbcDatabaseAccessException {
+ this.accessor = accessor;
this.conn = conn;
this.ps = ps;
this.rs = rs;
@@ -61,29 +63,29 @@ public class JdbcRecordIterator implements
Iterator<Map<String, Object>> {
if (conf.get(Constants.JDBC_TABLE) != null &&
conf.get(Constants.JDBC_QUERY) != null) {
fieldNamesProperty =
Preconditions.checkNotNull(conf.get(Constants.JDBC_QUERY_FIELD_NAMES));
fieldTypesProperty =
Preconditions.checkNotNull(conf.get(Constants.JDBC_QUERY_FIELD_TYPES));
+ hiveColumnNames = fieldNamesProperty.trim().split(",");
+ hiveColumnTypesList =
TypeInfoUtils.getTypeInfosFromTypeString(fieldTypesProperty);
} else {
try {
if (conf.get(Constants.JDBC_QUERY) == null) {
- ResultSetMetaData metadata = rs.getMetaData();
- int numColumns = metadata.getColumnCount();
- List<String> columnNames = new ArrayList<String>(numColumns);
- for (int i = 0; i < numColumns; i++) {
- columnNames.add(metadata.getColumnName(i + 1));
- }
- fieldNamesProperty = String.join(",",columnNames);
+ hiveColumnNames = accessor.getColNamesFromRS(rs).toArray(new
String[0]);
+ hiveColumnTypesList = accessor.getColTypesFromRS(rs);
+ fieldNamesProperty =
Arrays.stream(hiveColumnNames).collect(Collectors.joining(","));
+ fieldTypesProperty = hiveColumnTypesList.stream().map(typeInfo ->
typeInfo.getTypeName())
+ .collect(Collectors.joining(","));
} else {
fieldNamesProperty =
Preconditions.checkNotNull(conf.get(serdeConstants.LIST_COLUMNS));
+ fieldTypesProperty =
Preconditions.checkNotNull(conf.get(serdeConstants.LIST_COLUMN_TYPES));
+ hiveColumnNames = fieldNamesProperty.trim().split(",");
+ hiveColumnTypesList =
TypeInfoUtils.getTypeInfosFromTypeString(fieldTypesProperty);
}
}
catch (Exception e) {
LOGGER.error("Error while trying to get column names.", e);
throw new HiveJdbcDatabaseAccessException("Error while trying to get
column names: " + e.getMessage(), e);
}
- fieldTypesProperty =
Preconditions.checkNotNull(conf.get(serdeConstants.LIST_COLUMN_TYPES));
}
- LOGGER.debug("Iterator ColumnNames = {}", fieldNamesProperty);
- hiveColumnNames = fieldNamesProperty.trim().split(",");
- hiveColumnTypesList =
TypeInfoUtils.getTypeInfosFromTypeString(fieldTypesProperty);
+ LOGGER.debug("Iterator column names: {}, column types: {}",
fieldNamesProperty, fieldTypesProperty);
}
@@ -188,14 +190,7 @@ public class JdbcRecordIterator implements
Iterator<Map<String, Object>> {
* Release all DB resources
*/
public void close() {
- try {
- rs.close();
- ps.close();
- conn.close();
- }
- catch (Exception e) {
- LOGGER.warn("Caught exception while trying to close database objects",
e);
- }
+ accessor.cleanupResources(conn, ps, rs);
}
}