World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#1737] Improvement(postgresql): Obtain PostgreSQL table information in the form of metadata using the driver (#1741)
Clearviveddc2f6b77513
diff --git a/catalogs/catalog-jdbc-common/src/main/java/com/datastrato/gravitino/catalog/jdbc/JdbcTable.java b/catalogs/catalog-jdbc-common/src/main/java/com/datastrato/gravitino/catalog/jdbc/JdbcTable.javaindex 20740f0174..a181e63a46 100644--- a/catalogs/catalog-jdbc-common/src/main/java/com/datastrato/gravitino/catalog/jdbc/JdbcTable.java+++ b/catalogs/catalog-jdbc-common/src/main/java/com/datastrato/gravitino/catalog/jdbc/JdbcTable.java@@ -7,6 +7,7 @@ package com.datastrato.gravitino.catalog.jdbc;import com.datastrato.gravitino.catalog.TableOperations;import com.datastrato.gravitino.catalog.rel.BaseTable;import com.google.common.collect.Maps;+import java.util.Map;import lombok.Getter;import lombok.ToString;@@ -44,5 +45,13 @@ public class JdbcTable extends BaseTable {jdbcTable.indexes = indexes;return jdbcTable;}++ public String comment() {+ return comment;+ }++ public Map<String, String> properties() {+ return properties;+ }}}diff --git a/catalogs/catalog-jdbc-common/src/main/java/com/datastrato/gravitino/catalog/jdbc/converter/JdbcTypeConverter.java b/catalogs/catalog-jdbc-common/src/main/java/com/datastrato/gravitino/catalog/jdbc/converter/JdbcTypeConverter.javaindex aac1ac4d7b..3fb4ab4a93 100644--- a/catalogs/catalog-jdbc-common/src/main/java/com/datastrato/gravitino/catalog/jdbc/converter/JdbcTypeConverter.java+++ b/catalogs/catalog-jdbc-common/src/main/java/com/datastrato/gravitino/catalog/jdbc/converter/JdbcTypeConverter.java@@ -5,22 +5,97 @@package com.datastrato.gravitino.catalog.jdbc.converter;import com.datastrato.gravitino.rel.types.Type;+import java.util.Objects;-public abstract class JdbcTypeConverter<FROM, TO> {+/** @param <TO> Implement the corresponding JDBC data type to be converted */+public abstract class JdbcTypeConverter<TO> {++ protected static final String DATE = "date";+ protected static final String TIME = "time";+ protected static final String TIMESTAMP = "timestamp";+ protected static final String VARCHAR = "varchar";+ protected static final String TEXT = "text";/**- * Convert from Gravitino type to JDBC type+ * Convert from JDBC type to Gravitino type*- * @param type- * @return+ * @param type The common jdbc type bean.+ * @return Gravitino type.*/- public abstract Type toGravitinoType(FROM type);+ public abstract Type toGravitinoType(JdbcTypeBean type);/**- * Convert from JDBC type to Gravitino type+ * Convert from Gravitino type to JDBC type*- * @param type- * @return+ * @param type Gravitino type.+ * @return Implement the corresponding JDBC data type to be converted.*/public abstract TO fromGravitinoType(Type type);++ public static class JdbcTypeBean {+ /** Data type name. */+ private String typeName;+ /** Column size. For example: 20 in varchar (20) and 10 in decimal (10,2). */+ private String columnSize;+ /** Scale. For example: 2 in decimal (10,2). */+ private String scale;++ public JdbcTypeBean(String typeName) {+ this.typeName = typeName;+ }++ public String getTypeName() {+ return typeName;+ }++ public void setTypeName(String typeName) {+ this.typeName = typeName;+ }++ public String getColumnSize() {+ return columnSize;+ }++ public void setColumnSize(String columnSize) {+ this.columnSize = columnSize;+ }++ public String getScale() {+ return scale;+ }++ public void setScale(String scale) {+ this.scale = scale;+ }++ @Override+ public boolean equals(Object o) {+ if (this == o) return true;+ if (o == null || getClass() != o.getClass()) return false;+ JdbcTypeBean typeBean = (JdbcTypeBean) o;+ return Objects.equals(typeName, typeBean.typeName)+ && Objects.equals(columnSize, typeBean.columnSize)+ && Objects.equals(scale, typeBean.scale);+ }++ @Override+ public int hashCode() {+ return Objects.hash(typeName, columnSize, scale);+ }++ @Override+ public String toString() {+ return "JdbcTypeBean{"+ + "typeName='"+ + typeName+ + '\''+ + ", columnSize='"+ + columnSize+ + '\''+ + ", scale='"+ + scale+ + '\''+ + '}';+ }+ }}diff --git a/catalogs/catalog-jdbc-common/src/main/java/com/datastrato/gravitino/catalog/jdbc/operation/JdbcTableOperations.java b/catalogs/catalog-jdbc-common/src/main/java/com/datastrato/gravitino/catalog/jdbc/operation/JdbcTableOperations.javaindex ebaa725c61..b346e6c8fe 100644--- a/catalogs/catalog-jdbc-common/src/main/java/com/datastrato/gravitino/catalog/jdbc/operation/JdbcTableOperations.java+++ b/catalogs/catalog-jdbc-common/src/main/java/com/datastrato/gravitino/catalog/jdbc/operation/JdbcTableOperations.java@@ -22,6 +22,7 @@ import java.sql.DatabaseMetaData;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;+import java.util.Collections;import java.util.List;import java.util.Map;import javax.sql.DataSource;@@ -31,15 +32,10 @@ import org.slf4j.LoggerFactory;/** Operations for managing tables in a JDBC data store. */public abstract class JdbcTableOperations implements TableOperation {- public static final String PRIMARY_KEY = "PRIMARY KEY";- public static final String UNIQUE_KEY = "UNIQUE KEY";public static final String COMMENT = "COMMENT";public static final String SPACE = " ";- public static final String NOT_NULL = "NOT NULL";- public static final String DEFAULT = "DEFAULT";-protected static final Logger LOG = LoggerFactory.getLogger(JdbcTableOperations.class);protected DataSource dataSource;@@ -108,35 +104,59 @@ public abstract class JdbcTableOperations implements TableOperation {@Overridepublic JdbcTable load(String databaseName, String tableName) throws NoSuchTableException {try (Connection connection = getConnection(databaseName)) {- String comment;- Map<String, String> properties;- try (ResultSet table = getTable(connection, tableName)) {- if (!table.next()) {- throw new NoSuchTableException("Table " + tableName + " does not exist.");- }- comment = table.getString("REMARKS");- properties = extractPropertiesFromResultSet(table);+ // 1.Get table information+ ResultSet table = getTable(connection, databaseName, tableName);+ if (!table.next() || !tableName.equals(table.getString("TABLE_NAME"))) {+ throw new NoSuchTableException(+ String.format("Table %s does not exist in %s.", tableName, databaseName));}- JdbcColumn[] jdbcColumns;- try (ResultSet column = getColumns(connection, tableName)) {- List<JdbcColumn> result = new ArrayList<>();- while (column.next()) {- result.add(extractJdbcColumnFromResultSet(column));- }- jdbcColumns = result.toArray(new JdbcColumn[0]);+ JdbcTable.Builder jdbcTableBuilder = getBasicJdbcTableInfo(table);++ // 2.Get column information+ List<JdbcColumn> jdbcColumns = new ArrayList<>();+ ResultSet columns = getColumns(connection, databaseName, tableName);+ while (columns.next()) {+ JdbcColumn.Builder columnBuilder = getBasicJdbcColumnInfo(columns);+ boolean autoIncrement = getAutoIncrementInfo(columns);+ columnBuilder.withAutoIncrement(autoIncrement);+ jdbcColumns.add(columnBuilder.build());}- return new JdbcTable.Builder()- .withName(tableName)- .withColumns(jdbcColumns)- .withComment(comment)- .withProperties(properties)- .withAuditInfo(AuditInfo.EMPTY)- .build();- } catch (final SQLException se) {- throw this.exceptionMapper.toGravitinoException(se);+ jdbcTableBuilder.withColumns(jdbcColumns.toArray(new JdbcColumn[0]));++ // 3.Get index information+ List<Index> indexes = getIndexes(databaseName, tableName, connection.getMetaData());+ jdbcTableBuilder.withIndexes(indexes.toArray(new Index[0]));++ // 4.Get table properties+ Map<String, String> tableProperties = getTableProperties(connection, tableName);+ jdbcTableBuilder.withProperties(tableProperties);++ // 5.Leave the information to the bottom layer to append the table+ correctJdbcTableFields(connection, tableName, jdbcTableBuilder);+ return jdbcTableBuilder.build();+ } catch (SQLException e) {+ throw exceptionMapper.toGravitinoException(e);}}+ /**+ * Get all properties values of the table, including properties outside Gravitino management. The+ * JdbcCatalogOperations#loadTable method will filter out unnecessary properties.+ *+ * @param connection jdbc connection+ * @param tableName table name+ * @return Returns all table properties values.+ * @throws SQLException+ */+ protected Map<String, String> getTableProperties(Connection connection, String tableName)+ throws SQLException {+ return Collections.emptyMap();+ }++ protected boolean getAutoIncrementInfo(ResultSet resultSet) throws SQLException {+ return resultSet.getBoolean("IS_AUTOINCREMENT");+ }+@Overridepublic void rename(String databaseName, String oldTableName, String newTableName)throws NoSuchTableException {@@ -190,27 +210,37 @@ public abstract class JdbcTableOperations implements TableOperation {return metaData.getTables(databaseName, databaseName, null, JdbcConnectorUtils.TABLE_TYPES);}- protected ResultSet getTable(Connection connection, String tableName) throws SQLException {+ protected ResultSet getTable(Connection connection, String databaseName, String tableName)+ throws SQLException {final DatabaseMetaData metaData = connection.getMetaData();- String databaseName = connection.getSchema();- return metaData.getTables(- databaseName, databaseName, tableName, JdbcConnectorUtils.TABLE_TYPES);+ return metaData.getTables(connection.getCatalog(), connection.getSchema(), tableName, null);}- protected ResultSet getColumns(Connection connection, String tableName) throws SQLException {+ protected ResultSet getColumns(Connection connection, String databaseName, String tableName)+ throws SQLException {final DatabaseMetaData metaData = connection.getMetaData();- String databaseName = connection.getSchema();- return metaData.getColumns(databaseName, databaseName, tableName, null);+ return metaData.getColumns(connection.getCatalog(), connection.getSchema(), tableName, null);}/**- * @param table The result set of the table- * @return The properties extracted from the result set+ * Correct table information from the JDBC driver, because not all information could be retrieved+ * from the JDBC driver, like the table comment in MySQL of the 5.7 version.+ *+ * @param connection jdbc connection+ * @param tableName table name+ * @param jdbcTableBuilder The builder of the table to be returned+ * @throws SQLException*/- protected abstract Map<String, String> extractPropertiesFromResultSet(ResultSet table);+ protected void correctJdbcTableFields(+ Connection connection, String tableName, JdbcTable.Builder jdbcTableBuilder)+ throws SQLException {+ // nothing to do+ }- protected abstract JdbcColumn extractJdbcColumnFromResultSet(ResultSet column)- throws SQLException;+ protected List<Index> getIndexes(String databaseName, String tableName, DatabaseMetaData metaData)+ throws SQLException {+ return Collections.emptyList();+ }protected abstract String generateCreateTableSql(String tableName,@@ -234,4 +264,25 @@ public abstract class JdbcTableOperations implements TableOperation {connection.setCatalog(catalog);return connection;}++ protected JdbcTable.Builder getBasicJdbcTableInfo(ResultSet table) throws SQLException {+ return new JdbcTable.Builder()+ .withName(table.getString("TABLE_NAME"))+ .withComment(table.getString("REMARKS"))+ .withAuditInfo(AuditInfo.EMPTY);+ }++ protected JdbcColumn.Builder getBasicJdbcColumnInfo(ResultSet column) throws SQLException {+ JdbcTypeConverter.JdbcTypeBean typeBean =+ new JdbcTypeConverter.JdbcTypeBean(column.getString("TYPE_NAME"));+ typeBean.setColumnSize(column.getString("COLUMN_SIZE"));+ typeBean.setScale(column.getString("DECIMAL_DIGITS"));+ String comment = column.getString("REMARKS");+ return new JdbcColumn.Builder()+ .withName(column.getString("COLUMN_NAME"))+ .withType(typeConverter.toGravitinoType(typeBean))+ .withComment(StringUtils.isEmpty(comment) ? null : comment)+ .withNullable(column.getBoolean("NULLABLE"))+ .withProperties(Collections.emptyList());+ }}diff --git a/catalogs/catalog-jdbc-common/src/test/java/com/datastrato/gravitino/catalog/jdbc/converter/SqliteTypeConverter.java b/catalogs/catalog-jdbc-common/src/test/java/com/datastrato/gravitino/catalog/jdbc/converter/SqliteTypeConverter.javaindex eae27be90c..e97470034d 100644--- a/catalogs/catalog-jdbc-common/src/test/java/com/datastrato/gravitino/catalog/jdbc/converter/SqliteTypeConverter.java+++ b/catalogs/catalog-jdbc-common/src/test/java/com/datastrato/gravitino/catalog/jdbc/converter/SqliteTypeConverter.java@@ -11,7 +11,7 @@ import java.util.HashMap;import java.util.Map;import org.apache.commons.lang3.StringUtils;-public class SqliteTypeConverter extends JdbcTypeConverter<String, String> {+public class SqliteTypeConverter extends JdbcTypeConverter<String> {protected static final Map<Type, String> GRAVITINO_TO_SQLITE_MAPPING = new HashMap<>();@@ -23,9 +23,9 @@ public class SqliteTypeConverter extends JdbcTypeConverter<String, String> {}@Override- public Type toGravitinoType(String type) {+ public Type toGravitinoType(JdbcTypeBean type) {return GRAVITINO_TO_SQLITE_MAPPING.entrySet().stream()- .filter(entry -> StringUtils.equalsIgnoreCase(type, entry.getValue()))+ .filter(entry -> StringUtils.equalsIgnoreCase(type.getTypeName(), entry.getValue())).map(Map.Entry::getKey).findFirst().orElse(null);diff --git a/catalogs/catalog-jdbc-common/src/test/java/com/datastrato/gravitino/catalog/jdbc/operation/SqliteTableOperations.java b/catalogs/catalog-jdbc-common/src/test/java/com/datastrato/gravitino/catalog/jdbc/operation/SqliteTableOperations.javaindex 320a736df7..44698cc127 100644--- a/catalogs/catalog-jdbc-common/src/test/java/com/datastrato/gravitino/catalog/jdbc/operation/SqliteTableOperations.java+++ b/catalogs/catalog-jdbc-common/src/test/java/com/datastrato/gravitino/catalog/jdbc/operation/SqliteTableOperations.java@@ -9,8 +9,6 @@ import com.datastrato.gravitino.rel.TableChange;import com.datastrato.gravitino.rel.expressions.transforms.Transform;import com.datastrato.gravitino.rel.indexes.Index;import java.sql.ResultSet;-import java.sql.SQLException;-import java.util.Collections;import java.util.Map;public class SqliteTableOperations extends JdbcTableOperations {@@ -77,20 +75,7 @@ public class SqliteTableOperations extends JdbcTableOperations {}@Override- protected JdbcColumn extractJdbcColumnFromResultSet(ResultSet resultSet) throws SQLException {- return new JdbcColumn.Builder()- .withName(resultSet.getString("COLUMN_NAME"))- .withComment(null)- .withType(typeConverter.toGravitinoType(resultSet.getString("TYPE_NAME")))- .withNullable(resultSet.getBoolean("NULLABLE"))- // TODO: uncomment this once we support column default values.- // .withDefaultValue(resultSet.getString("COLUMN_DEF"))- .build();- }-- @Override- protected Map<String, String> extractPropertiesFromResultSet(ResultSet table) {- // Sqlite does not support table properties.- return Collections.emptyMap();+ protected boolean getAutoIncrementInfo(ResultSet columns) {+ return false;}}diff --git a/catalogs/catalog-jdbc-mysql/src/main/java/com/datastrato/gravitino/catalog/mysql/converter/MysqlTypeConverter.java b/catalogs/catalog-jdbc-mysql/src/main/java/com/datastrato/gravitino/catalog/mysql/converter/MysqlTypeConverter.javaindex 13440f28a3..559925959e 100644--- a/catalogs/catalog-jdbc-mysql/src/main/java/com/datastrato/gravitino/catalog/mysql/converter/MysqlTypeConverter.java+++ b/catalogs/catalog-jdbc-mysql/src/main/java/com/datastrato/gravitino/catalog/mysql/converter/MysqlTypeConverter.java@@ -7,43 +7,51 @@ package com.datastrato.gravitino.catalog.mysql.converter;import com.datastrato.gravitino.catalog.jdbc.converter.JdbcTypeConverter;import com.datastrato.gravitino.rel.types.Type;import com.datastrato.gravitino.rel.types.Types;-import java.util.Objects;/** Type converter for MySQL. */-public class MysqlTypeConverter- extends JdbcTypeConverter<MysqlTypeConverter.MysqlTypeBean, String> {+public class MysqlTypeConverter extends JdbcTypeConverter<String> {++ private static final String TINYINT = "tinyint";+ private static final String SMALLINT = "smallint";+ private static final String INT = "int";+ private static final String BIGINT = "bigint";+ private static final String FLOAT = "float";+ private static final String DOUBLE = "double";+ private static final String DECIMAL = "decimal";+ private static final String CHAR = "char";+ private static final String BINARY = "binary";@Override- public Type toGravitinoType(MysqlTypeBean typeBean) {+ public Type toGravitinoType(JdbcTypeBean typeBean) {switch (typeBean.getTypeName().toLowerCase()) {- case "tinyint":+ case TINYINT:return Types.ByteType.get();- case "smallint":+ case SMALLINT:return Types.ShortType.get();- case "int":+ case INT:return Types.IntegerType.get();- case "bigint":+ case BIGINT:return Types.LongType.get();- case "float":+ case FLOAT:return Types.FloatType.get();- case "double":+ case DOUBLE:return Types.DoubleType.get();- case "date":+ case DATE:return Types.DateType.get();- case "time":+ case TIME:return Types.TimeType.get();- case "timestamp":+ case TIMESTAMP:return Types.TimestampType.withoutTimeZone();- case "decimal":+ case DECIMAL:return Types.DecimalType.of(Integer.parseInt(typeBean.getColumnSize()), Integer.parseInt(typeBean.getScale()));- case "varchar":+ case VARCHAR:return Types.VarCharType.of(Integer.parseInt(typeBean.getColumnSize()));- case "char":+ case CHAR:return Types.FixedCharType.of(Integer.parseInt(typeBean.getColumnSize()));- case "text":+ case TEXT:return Types.StringType.get();- case "binary":+ case BINARY:return Types.BinaryType.get();default:throw new IllegalArgumentException("Not a supported type: " + typeBean.getTypeName());@@ -53,19 +61,19 @@ public class MysqlTypeConverter@Overridepublic String fromGravitinoType(Type type) {if (type instanceof Types.ByteType) {- return "tinyint";+ return TINYINT;} else if (type instanceof Types.ShortType) {- return "smallint";+ return SMALLINT;} else if (type instanceof Types.IntegerType) {- return "int";+ return INT;} else if (type instanceof Types.LongType) {- return "bigint";+ return BIGINT;} else if (type instanceof Types.FloatType) {return type.simpleString();} else if (type instanceof Types.DoubleType) {return type.simpleString();} else if (type instanceof Types.StringType) {- return "text";+ return TEXT;} else if (type instanceof Types.DateType) {return type.simpleString();} else if (type instanceof Types.TimeType) {@@ -83,53 +91,4 @@ public class MysqlTypeConverter}throw new IllegalArgumentException("Not a supported type: " + type.toString());}-- public static class MysqlTypeBean {- private String typeName;- private String columnSize;- private String scale;-- public MysqlTypeBean(String typeName) {- this.typeName = typeName;- }-- public String getTypeName() {- return typeName;- }-- public void setTypeName(String typeName) {- this.typeName = typeName;- }-- public String getColumnSize() {- return columnSize;- }-- public void setColumnSize(String columnSize) {- this.columnSize = columnSize;- }-- public String getScale() {- return scale;- }-- public void setScale(String scale) {- this.scale = scale;- }-- @Override- public boolean equals(Object o) {- if (this == o) return true;- if (o == null || getClass() != o.getClass()) return false;- MysqlTypeBean typeBean = (MysqlTypeBean) o;- return Objects.equals(typeName, typeBean.typeName)- && Objects.equals(columnSize, typeBean.columnSize)- && Objects.equals(scale, typeBean.scale);- }-- @Override- public int hashCode() {- return Objects.hash(typeName, columnSize, scale);- }- }}diff --git a/catalogs/catalog-jdbc-mysql/src/main/java/com/datastrato/gravitino/catalog/mysql/operation/MysqlTableOperations.java b/catalogs/catalog-jdbc-mysql/src/main/java/com/datastrato/gravitino/catalog/mysql/operation/MysqlTableOperations.javaindex 400684ad65..ad8082be91 100644--- a/catalogs/catalog-jdbc-mysql/src/main/java/com/datastrato/gravitino/catalog/mysql/operation/MysqlTableOperations.java+++ b/catalogs/catalog-jdbc-mysql/src/main/java/com/datastrato/gravitino/catalog/mysql/operation/MysqlTableOperations.java@@ -11,11 +11,9 @@ import com.datastrato.gravitino.StringIdentifier;import com.datastrato.gravitino.catalog.jdbc.JdbcColumn;import com.datastrato.gravitino.catalog.jdbc.JdbcTable;import com.datastrato.gravitino.catalog.jdbc.operation.JdbcTableOperations;-import com.datastrato.gravitino.catalog.mysql.converter.MysqlTypeConverter;import com.datastrato.gravitino.exceptions.NoSuchColumnException;import com.datastrato.gravitino.exceptions.NoSuchSchemaException;import com.datastrato.gravitino.exceptions.NoSuchTableException;-import com.datastrato.gravitino.meta.AuditInfo;import com.datastrato.gravitino.rel.Column;import com.datastrato.gravitino.rel.TableChange;import com.datastrato.gravitino.rel.expressions.transforms.Transform;@@ -48,139 +46,6 @@ public class MysqlTableOperations extends JdbcTableOperations {public static final String BACK_QUOTE = "`";- @Override- public JdbcTable load(String databaseName, String tableName) throws NoSuchTableException {- List<JdbcColumn> jdbcColumns = new ArrayList<>();- try (Connection connection = getConnection(databaseName)) {- // 1.Get table information- DatabaseMetaData metaData = connection.getMetaData();- ResultSet table = metaData.getTables(databaseName, null, tableName, null);- if (!table.next() || !tableName.equals(table.getString("TABLE_NAME"))) {- throw new NoSuchTableException(- String.format("Table %s does not exist in %s.", tableName, databaseName));- }-- // 2.Get column information- ResultSet columns = metaData.getColumns(databaseName, null, tableName, null);- while (columns.next()) {- MysqlTypeConverter.MysqlTypeBean typeBean =- new MysqlTypeConverter.MysqlTypeBean(columns.getString("TYPE_NAME"));- typeBean.setColumnSize(columns.getString("COLUMN_SIZE"));- typeBean.setScale(columns.getString("DECIMAL_DIGITS"));-- String columnName = columns.getString("COLUMN_NAME");- String colComment = columns.getString("REMARKS");- jdbcColumns.add(- new JdbcColumn.Builder()- .withName(columnName)- .withType(typeConverter.toGravitinoType(typeBean))- .withNullable(columns.getBoolean("NULLABLE"))- .withComment(StringUtils.isEmpty(colComment) ? null : colComment)- // TODO #1531 will add default value.- // .withDefaultValue(columns.getString("COLUMN_DEF"))- .withProperties(Collections.emptyList())- .build());- }-- // 3.Load table properties- Map<String, String> tableProperties = loadTablePropertiesFromSql(connection, tableName);-- String comment = table.getString("REMARKS");- if (StringUtils.isEmpty(comment)) {- // In Mysql version 5.7, the comment field value cannot be obtained in the driver API.- LOG.warn("Not found comment in mysql driver api. Will try to get comment from sql");- comment = tableProperties.getOrDefault(COMMENT, comment);- }-- // 4.Get index information- List<Index> indexes = getIndexes(databaseName, tableName, metaData);-- return new JdbcTable.Builder()- .withName(tableName)- .withColumns(jdbcColumns.toArray(new JdbcColumn[0]))- .withComment(comment)- .withProperties(- Collections.unmodifiableMap(- new HashMap<String, String>() {- {- put(MYSQL_ENGINE_KEY, tableProperties.get(MYSQL_ENGINE_KEY));- String autoIncrement = tableProperties.get(MYSQL_AUTO_INCREMENT_OFFSET_KEY);- if (StringUtils.isNotEmpty(autoIncrement)) {- put(MYSQL_AUTO_INCREMENT_OFFSET_KEY, autoIncrement);- }- }- }))- .withIndexes(indexes.toArray(new Index[0]))- .withAuditInfo(AuditInfo.EMPTY)- .build();- } catch (SQLException e) {- throw exceptionMapper.toGravitinoException(e);- }- }-- public List<Index> getIndexes(String databaseName, String tableName, DatabaseMetaData metaData)- throws SQLException {- List<Index> indexes = new ArrayList<>();-- // Get primary key information- SetMultimap<String, String> primaryKeyGroupByName = HashMultimap.create();- ResultSet primaryKeys = metaData.getPrimaryKeys(databaseName, null, tableName);- while (primaryKeys.next()) {- String columnName = primaryKeys.getString("COLUMN_NAME");- primaryKeyGroupByName.put(primaryKeys.getString("PK_NAME"), columnName);- }- for (String key : primaryKeyGroupByName.keySet()) {- indexes.add(Indexes.primary(key, convertIndexFieldNames(primaryKeyGroupByName.get(key))));- }-- // Get unique key information- SetMultimap<String, String> indexGroupByName = HashMultimap.create();- ResultSet indexInfo = metaData.getIndexInfo(databaseName, null, tableName, false, false);- while (indexInfo.next()) {- String indexName = indexInfo.getString("INDEX_NAME");- if (!indexInfo.getBoolean("NON_UNIQUE")- && !StringUtils.equalsIgnoreCase(Indexes.DEFAULT_MYSQL_PRIMARY_KEY_NAME, indexName)) {- String columnName = indexInfo.getString("COLUMN_NAME");- indexGroupByName.put(indexName, columnName);- }- }- for (String key : indexGroupByName.keySet()) {- indexes.add(Indexes.unique(key, convertIndexFieldNames(indexGroupByName.get(key))));- }-- return indexes;- }-- private String[][] convertIndexFieldNames(Set<String> fieldNames) {- return fieldNames.stream().map(colName -> new String[] {colName}).toArray(String[][]::new);- }-- private Map<String, String> loadTablePropertiesFromSql(Connection connection, String tableName)- throws SQLException {- try (PreparedStatement statement = connection.prepareStatement("SHOW TABLE STATUS LIKE ?")) {- statement.setString(1, tableName);- try (ResultSet resultSet = statement.executeQuery()) {- if (!resultSet.next() || !tableName.equals(resultSet.getString("NAME"))) {- throw new NoSuchTableException(- String.format("Table %s does not exist in %s.", tableName, connection.getCatalog()));- }- return Collections.unmodifiableMap(- new HashMap<String, String>() {- {- // It is not possible to get all column assembly returns here, because in version- // 5.7, some columns exist in metadata but get will report an error that they do not- // exist, such as: TABLE_NAME- put(COMMENT, resultSet.getString(COMMENT));- put(MYSQL_ENGINE_KEY, resultSet.getString(MYSQL_ENGINE_KEY));- put(- MYSQL_AUTO_INCREMENT_OFFSET_KEY,- resultSet.getString(MYSQL_AUTO_INCREMENT_OFFSET_KEY));- }- });- }- }- }-@Overridepublic List<String> listTables(String databaseName) throws NoSuchSchemaException {try (Connection connection = getConnection(databaseName)) {@@ -212,12 +77,6 @@ public class MysqlTableOperations extends JdbcTableOperations {"Column " + colName + " does not exist in table " + jdbcTable.name()));}- @Override- protected Map<String, String> extractPropertiesFromResultSet(ResultSet table) {- // We have rewritten the `load` method, so there is no need to implement this method- throw new UnsupportedOperationException("Extracting table properties is not supported yet");- }-@Overrideprotected String generateCreateTableSql(String tableName,@@ -309,10 +168,85 @@ public class MysqlTableOperations extends JdbcTableOperations {}}+ protected List<Index> getIndexes(String databaseName, String tableName, DatabaseMetaData metaData)+ throws SQLException {+ List<Index> indexes = new ArrayList<>();++ // Get primary key information+ SetMultimap<String, String> primaryKeyGroupByName = HashMultimap.create();+ ResultSet primaryKeys = metaData.getPrimaryKeys(databaseName, null, tableName);+ while (primaryKeys.next()) {+ String columnName = primaryKeys.getString("COLUMN_NAME");+ primaryKeyGroupByName.put(primaryKeys.getString("PK_NAME"), columnName);+ }+ for (String key : primaryKeyGroupByName.keySet()) {+ indexes.add(Indexes.primary(key, convertIndexFieldNames(primaryKeyGroupByName.get(key))));+ }++ // Get unique key information+ SetMultimap<String, String> indexGroupByName = HashMultimap.create();+ ResultSet indexInfo = metaData.getIndexInfo(databaseName, null, tableName, false, false);+ while (indexInfo.next()) {+ String indexName = indexInfo.getString("INDEX_NAME");+ if (!indexInfo.getBoolean("NON_UNIQUE")+ && !StringUtils.equalsIgnoreCase(Indexes.DEFAULT_MYSQL_PRIMARY_KEY_NAME, indexName)) {+ String columnName = indexInfo.getString("COLUMN_NAME");+ indexGroupByName.put(indexName, columnName);+ }+ }+ for (String key : indexGroupByName.keySet()) {+ indexes.add(Indexes.unique(key, convertIndexFieldNames(indexGroupByName.get(key))));+ }++ return indexes;+ }++ private String[][] convertIndexFieldNames(Set<String> fieldNames) {+ return fieldNames.stream().map(colName -> new String[] {colName}).toArray(String[][]::new);+ }++ @Override+ protected boolean getAutoIncrementInfo(ResultSet resultSet) throws SQLException {+ return "YES".equalsIgnoreCase(resultSet.getString("IS_AUTOINCREMENT"));+ }++ @Override+ protected Map<String, String> getTableProperties(Connection connection, String tableName)+ throws SQLException {+ try (PreparedStatement statement = connection.prepareStatement("SHOW TABLE STATUS LIKE ?")) {+ statement.setString(1, tableName);+ try (ResultSet resultSet = statement.executeQuery()) {+ if (!resultSet.next() || !tableName.equals(resultSet.getString("NAME"))) {+ throw new NoSuchTableException(+ String.format("Table %s does not exist in %s.", tableName, connection.getCatalog()));+ }+ return Collections.unmodifiableMap(+ new HashMap<String, String>() {+ {+ // It is not possible to get all column assembly returns here, because in version+ // 5.7, some columns exist in metadata but get will report an error that they do not+ // exist, such as: TABLE_NAME+ put(COMMENT, resultSet.getString(COMMENT));+ put(MYSQL_ENGINE_KEY, resultSet.getString(MYSQL_ENGINE_KEY));+ String autoIncrement = resultSet.getString(MYSQL_AUTO_INCREMENT_OFFSET_KEY);+ if (StringUtils.isNotEmpty(autoIncrement)) {+ put(MYSQL_AUTO_INCREMENT_OFFSET_KEY, autoIncrement);+ }+ }+ });+ }+ }+ }+@Override- protected JdbcColumn extractJdbcColumnFromResultSet(ResultSet resultSet) {- // We have rewritten the `load` method, so there is no need to implement this method- throw new UnsupportedOperationException("Extracting table columns is not supported yet");+ protected void correctJdbcTableFields(+ Connection connection, String tableName, JdbcTable.Builder tableBuilder) throws SQLException {+ if (StringUtils.isEmpty(tableBuilder.comment())) {+ // In Mysql version 5.7, the comment field value cannot be obtained in the driver API.+ LOG.warn("Not found comment in mysql driver api. Will try to get comment from sql");+ tableBuilder.withComment(+ tableBuilder.properties().getOrDefault(COMMENT, tableBuilder.comment()));+ }}@Overridediff --git a/catalogs/catalog-jdbc-postgresql/src/main/java/com/datastrato/gravitino/catalog/postgresql/converter/PostgreSqlTypeConverter.java b/catalogs/catalog-jdbc-postgresql/src/main/java/com/datastrato/gravitino/catalog/postgresql/converter/PostgreSqlTypeConverter.javaindex 986fd9ef7e..3ed1e06128 100644--- a/catalogs/catalog-jdbc-postgresql/src/main/java/com/datastrato/gravitino/catalog/postgresql/converter/PostgreSqlTypeConverter.java+++ b/catalogs/catalog-jdbc-postgresql/src/main/java/com/datastrato/gravitino/catalog/postgresql/converter/PostgreSqlTypeConverter.java@@ -7,89 +7,99 @@ package com.datastrato.gravitino.catalog.postgresql.converter;import com.datastrato.gravitino.catalog.jdbc.converter.JdbcTypeConverter;import com.datastrato.gravitino.rel.types.Type;import com.datastrato.gravitino.rel.types.Types;-import java.util.List;-import net.sf.jsqlparser.statement.create.table.ColDataType;-public class PostgreSqlTypeConverter extends JdbcTypeConverter<ColDataType, String> {+public class PostgreSqlTypeConverter extends JdbcTypeConverter<String> {++ private static final String BOOL = "bool";+ private static final String INT_2 = "int2";+ private static final String INT_4 = "int4";+ private static final String INT_8 = "int8";+ private static final String FLOAT_4 = "float4";+ private static final String FLOAT_8 = "float8";++ private static final String TIMESTAMP_TZ = "timestamptz";+ private static final String NUMERIC = "numeric";+ private static final String BPCHAR = "bpchar";+ private static final String BYTEA = "bytea";+@Override- public Type toGravitinoType(ColDataType type) {- List<String> arguments = type.getArgumentsStringList();+ public Type toGravitinoType(JdbcTypeBean typeBean) {// TODO #947 Complex types are not considered for support in this issue, which will bring more// testing needs- switch (type.getDataType().toLowerCase()) {- case "boolean":+ switch (typeBean.getTypeName().toLowerCase()) {+ case BOOL:return Types.BooleanType.get();- case "smallint":+ case INT_2:return Types.ShortType.get();- case "integer":+ case INT_4:return Types.IntegerType.get();- case "bigint":+ case INT_8:return Types.LongType.get();- case "real":+ case FLOAT_4:return Types.FloatType.get();- case "double precision":+ case FLOAT_8:return Types.DoubleType.get();- case "date":+ case DATE:return Types.DateType.get();- case "time without time zone":+ case TIME:return Types.TimeType.get();- case "timestamp without time zone":+ case TIMESTAMP:return Types.TimestampType.withoutTimeZone();- case "timestamp with time zone":+ case TIMESTAMP_TZ:return Types.TimestampType.withTimeZone();- case "numeric":+ case NUMERIC:return Types.DecimalType.of(- Integer.parseInt(arguments.get(0)), Integer.parseInt(arguments.get(1)));- case "character varying":- return Types.VarCharType.of(Integer.parseInt(arguments.get(0)));- case "char":- case "character":- return Types.FixedCharType.of(Integer.parseInt(arguments.get(0)));- case "text":+ Integer.parseInt(typeBean.getColumnSize()), Integer.parseInt(typeBean.getScale()));+ case VARCHAR:+ return Types.VarCharType.of(Integer.parseInt(typeBean.getColumnSize()));+ case BPCHAR:+ return Types.FixedCharType.of(Integer.parseInt(typeBean.getColumnSize()));+ case TEXT:return Types.StringType.get();- case "bytea":+ case BYTEA:return Types.BinaryType.get();default:- throw new IllegalArgumentException("Not a supported type: " + type);+ throw new IllegalArgumentException("Not a supported type: " + typeBean);}}@Overridepublic String fromGravitinoType(Type type) {if (type instanceof Types.BooleanType) {- return "boolean";+ return BOOL;} else if (type instanceof Types.ShortType) {- return "smallint";+ return INT_2;} else if (type instanceof Types.IntegerType) {- return "integer";+ return INT_4;} else if (type instanceof Types.LongType) {- return "bigint";+ return INT_8;} else if (type instanceof Types.FloatType) {- return "real";+ return FLOAT_4;} else if (type instanceof Types.DoubleType) {- return "double precision";+ return FLOAT_8;} else if (type instanceof Types.StringType) {- return "text";+ return TEXT;} else if (type instanceof Types.DateType) {return type.simpleString();} else if (type instanceof Types.TimeType) {- return "time without time zone";+ return type.simpleString();} else if (type instanceof Types.TimestampType && !((Types.TimestampType) type).hasTimeZone()) {- return "timestamp without time zone";+ return TIMESTAMP;} else if (type instanceof Types.TimestampType && ((Types.TimestampType) type).hasTimeZone()) {- return "timestamp with time zone";+ return TIMESTAMP_TZ;} else if (type instanceof Types.DecimalType) {- return "numeric("+ return NUMERIC+ + "("+ ((Types.DecimalType) type).precision()+ ","+ ((Types.DecimalType) type).scale()+ ")";} else if (type instanceof Types.VarCharType) {- return "character varying(" + ((Types.VarCharType) type).length() + ")";+ return VARCHAR + "(" + ((Types.VarCharType) type).length() + ")";} else if (type instanceof Types.FixedCharType) {- return type.simpleString();+ return BPCHAR + "(" + ((Types.FixedCharType) type).length() + ")";} else if (type instanceof Types.BinaryType) {- return "bytea";+ return BYTEA;}throw new IllegalArgumentException(String.format("Couldn't convert PostgreSQL type %s to Gravitino type", type.toString()));diff --git a/catalogs/catalog-jdbc-postgresql/src/main/java/com/datastrato/gravitino/catalog/postgresql/operation/PostgreSqlTableOperations.java b/catalogs/catalog-jdbc-postgresql/src/main/java/com/datastrato/gravitino/catalog/postgresql/operation/PostgreSqlTableOperations.javaindex fff44aa301..03a0b7767f 100644--- a/catalogs/catalog-jdbc-postgresql/src/main/java/com/datastrato/gravitino/catalog/postgresql/operation/PostgreSqlTableOperations.java+++ b/catalogs/catalog-jdbc-postgresql/src/main/java/com/datastrato/gravitino/catalog/postgresql/operation/PostgreSqlTableOperations.java@@ -12,26 +12,20 @@ import com.datastrato.gravitino.catalog.jdbc.converter.JdbcExceptionConverter;import com.datastrato.gravitino.catalog.jdbc.converter.JdbcTypeConverter;import com.datastrato.gravitino.catalog.jdbc.operation.JdbcTableOperations;import com.datastrato.gravitino.exceptions.NoSuchColumnException;-import com.datastrato.gravitino.exceptions.NoSuchTableException;-import com.datastrato.gravitino.meta.AuditInfo;import com.datastrato.gravitino.rel.TableChange;import com.datastrato.gravitino.rel.expressions.transforms.Transform;import com.datastrato.gravitino.rel.indexes.Index;import com.datastrato.gravitino.rel.types.Types;import com.google.common.base.Preconditions;import java.sql.Connection;-import java.sql.PreparedStatement;+import java.sql.DatabaseMetaData;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.Arrays;-import java.util.Collections;-import java.util.HashMap;import java.util.List;import java.util.Map;-import java.util.function.BiConsumer;import javax.sql.DataSource;-import net.sf.jsqlparser.statement.create.table.ColDataType;import org.apache.commons.collections4.CollectionUtils;import org.apache.commons.collections4.MapUtils;import org.apache.commons.lang3.ArrayUtils;@@ -43,30 +37,6 @@ public class PostgreSqlTableOperations extends JdbcTableOperations {public static final String PG_QUOTE = "\"";- private static final String SHOW_COLUMN_COMMENT_SQL =- "SELECT \n"- + " a.attname as col_name,\n"- + " col_description(a.attrelid, a.attnum) as comment\n"- + "FROM \n"- + " pg_class AS c\n"- + "JOIN \n"- + " pg_attribute AS a ON a.attrelid = c.oid\n"- + "JOIN\n"- + " pg_namespace AS n ON n.oid = c.relnamespace\n"- + "WHERE \n"- + " a.attnum > 0 \n"- + " AND c.relname = ? AND n.nspname = ?";-- private static final String SHOW_COLUMN_INFO_SQL =- "select * FROM information_schema.columns WHERE table_name = ? AND table_schema = ? order by ordinal_position";-- private static final String SHOW_TABLE_COMMENT_SQL =- "SELECT tb.table_name, d.description\n"- + "FROM information_schema.tables tb\n"- + " JOIN pg_class c ON c.relname = tb.table_name\n"- + " LEFT JOIN pg_description d ON d.objoid = c.oid AND d.objsubid = '0'\n"- + "WHERE tb.table_name = ? AND table_schema = ?;";-private String database;@Override@@ -82,144 +52,6 @@ public class PostgreSqlTableOperations extends JdbcTableOperations {"The `jdbc-database` configuration item is mandatory in PostgreSQL.");}- @Override- public JdbcTable load(String schema, String tableName) throws NoSuchTableException {- try (Connection connection = getConnection(schema)) {- // The first step is to obtain the comment information of the column.- Map<String, String> columnCommentMap = selectColumnComment(schema, tableName, connection);-- // The second step is to obtain the column information of the table.- List<JdbcColumn> jdbcColumns =- selectColumnInfoAndExecute(- schema,- tableName,- connection,- (builder, s) -> builder.withComment(columnCommentMap.get(s)));-- // The third step is to obtain the comment information of the table.- String comment = selectTableComment(schema, tableName, connection);- return new JdbcTable.Builder()- .withName(tableName)- .withColumns(jdbcColumns.toArray(new JdbcColumn[0]))- .withComment(comment)- .withAuditInfo(AuditInfo.EMPTY)- .withProperties(Collections.emptyMap())- .build();- } catch (SQLException e) {- throw this.exceptionMapper.toGravitinoException(e);- }- }-- private List<JdbcColumn> selectColumnInfoAndExecute(- String schemaName,- String tableName,- Connection connection,- BiConsumer<JdbcColumn.Builder, String> builderConsumer)- throws SQLException {- List<JdbcColumn> jdbcColumns = new ArrayList<>();- try (PreparedStatement preparedStatement = connection.prepareStatement(SHOW_COLUMN_INFO_SQL)) {- preparedStatement.setString(1, tableName);- preparedStatement.setString(2, schemaName);- try (ResultSet resultSet = preparedStatement.executeQuery()) {- while (resultSet.next()) {- ColDataType colDataType = new ColDataType();- colDataType.setDataType(resultSet.getString("data_type"));- colDataType.setArgumentsStringList(getArgList(resultSet));- String columnName = resultSet.getString("column_name");- JdbcColumn.Builder builder =- new JdbcColumn.Builder()- .withName(columnName)- // TODO: uncomment this once we support column default values.- // .withDefaultValue(extractDefaultValue(resultSet.getString("column_default")))- .withNullable("YES".equalsIgnoreCase(resultSet.getString("is_nullable")))- .withType(typeConverter.toGravitinoType(colDataType))- .withAutoIncrement("YES".equalsIgnoreCase(resultSet.getString("is_identity")));- builderConsumer.accept(builder, columnName);- jdbcColumns.add(builder.build());- }- }- }- if (jdbcColumns.isEmpty()) {- throw new NoSuchTableException("Table " + tableName + " does not exist.");- }- return jdbcColumns;- }-- private static List<String> getArgList(ResultSet resultSet) throws SQLException {- List<String> result = new ArrayList<>();- String characterMaximumLength = resultSet.getString("character_maximum_length");- if (StringUtils.isNotEmpty(characterMaximumLength)) {- result.add(characterMaximumLength);- }- String numericPrecision = resultSet.getString("numeric_precision");- if (StringUtils.isNotEmpty(numericPrecision)) {- result.add(numericPrecision);- }- String numericScale = resultSet.getString("numeric_scale");- if (StringUtils.isNotEmpty(numericScale)) {- result.add(numericScale);- }- String datetimePrecision = resultSet.getString("datetime_precision");- if (StringUtils.isNotEmpty(datetimePrecision)) {- result.add(datetimePrecision);- }- return result;- }-- private String selectTableComment(String schema, String tableName, Connection connection)- throws SQLException {- try (PreparedStatement preparedStatement =- connection.prepareStatement(SHOW_TABLE_COMMENT_SQL)) {- preparedStatement.setString(1, tableName);- preparedStatement.setString(2, schema);- try (ResultSet resultSet = preparedStatement.executeQuery()) {- if (resultSet.next()) {- return resultSet.getString("description");- }- }- }- return null;- }-- /**- * @return Returns the column names and comments of the table- * @throws SQLException- */- private Map<String, String> selectColumnComment(- String schema, String tableName, Connection connection) throws SQLException {- Map<String, String> columnCommentMap = new HashMap<>();-- try (PreparedStatement preparedStatement =- connection.prepareStatement(SHOW_COLUMN_COMMENT_SQL)) {- preparedStatement.setString(1, tableName);- preparedStatement.setString(2, schema);- try (ResultSet resultSet = preparedStatement.executeQuery()) {- while (resultSet.next()) {- String comment = resultSet.getString("comment");- if (null != comment) {- String columnName = resultSet.getString("col_name");- columnCommentMap.put(columnName, comment);- }- }- }- }- return columnCommentMap;- }-- private static String extractDefaultValue(String columnDefault) {- if (columnDefault == null) {- return null;- }-- // Remove single quotes and '::'- int i = columnDefault.indexOf("::");- if (-1 != i) {- columnDefault = columnDefault.substring(0, i);- }- String replace = columnDefault.replace("'", "");- return "NULL".equalsIgnoreCase(replace) ? null : replace;- }-@Overrideprotected String generateCreateTableSql(String tableName,@@ -552,22 +384,24 @@ public class PostgreSqlTableOperations extends JdbcTableOperations {}@Override- protected Map<String, String> extractPropertiesFromResultSet(ResultSet table) {- // We have rewritten the `load` method, so there is no need to implement this method- throw new UnsupportedOperationException("Extracting table columns is not supported yet");+ protected Connection getConnection(String schema) throws SQLException {+ Connection connection = dataSource.getConnection();+ connection.setCatalog(database);+ connection.setSchema(schema);+ return connection;}@Override- protected JdbcColumn extractJdbcColumnFromResultSet(ResultSet column) {- // We have rewritten the `load` method, so there is no need to implement this method- throw new UnsupportedOperationException("Extracting table columns is not supported yet");+ protected ResultSet getTable(Connection connection, String schema, String tableName)+ throws SQLException {+ DatabaseMetaData metaData = connection.getMetaData();+ return metaData.getTables(database, schema, tableName, null);}@Override- protected Connection getConnection(String schema) throws SQLException {- Connection connection = dataSource.getConnection();- connection.setCatalog(database);- connection.setSchema(schema);- return connection;+ protected ResultSet getColumns(Connection connection, String schema, String tableName)+ throws SQLException {+ DatabaseMetaData metaData = connection.getMetaData();+ return metaData.getColumns(database, schema, tableName, null);}}