World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#14662] fix(postgresql): keep an explicit column collation on a column type change (#14665)
geyanggangb654b802416f
diff --git a/catalogs/catalog-jdbc-postgresql/src/main/java/org/apache/gravitino/catalog/postgresql/operation/PostgreSqlTableOperations.java b/catalogs/catalog-jdbc-postgresql/src/main/java/org/apache/gravitino/catalog/postgresql/operation/PostgreSqlTableOperations.javaindex 213dd667fb..01e570d111 100644--- a/catalogs/catalog-jdbc-postgresql/src/main/java/org/apache/gravitino/catalog/postgresql/operation/PostgreSqlTableOperations.java+++ b/catalogs/catalog-jdbc-postgresql/src/main/java/org/apache/gravitino/catalog/postgresql/operation/PostgreSqlTableOperations.java@@ -435,7 +435,7 @@ public class PostgreSqlTableOperations extends JdbcTableOperations} else if (change instanceof TableChange.UpdateColumnType) {lazyLoadTable = getOrCreateTable(schemaName, tableName, lazyLoadTable);TableChange.UpdateColumnType updateColumnType = (TableChange.UpdateColumnType) change;- alterSql.add(updateColumnTypeFieldDefinition(updateColumnType, lazyLoadTable));+ alterSql.add(updateColumnTypeFieldDefinition(schemaName, updateColumnType, lazyLoadTable));} else if (change instanceof TableChange.UpdateColumnComment) {alterSql.add(updateColumnCommentFieldDefinition(@@ -659,7 +659,7 @@ public class PostgreSqlTableOperations extends JdbcTableOperations}private String updateColumnTypeFieldDefinition(- TableChange.UpdateColumnType updateColumnType, JdbcTable jdbcTable) {+ String schemaName, TableChange.UpdateColumnType updateColumnType, JdbcTable jdbcTable) {if (updateColumnType.fieldName().length > 1) {throw new UnsupportedOperationException(POSTGRESQL_NOT_SUPPORT_NESTED_COLUMN_MSG);}@@ -673,13 +673,24 @@ public class PostgreSqlTableOperations extends JdbcTableOperationsif (null == column) {throw new NoSuchColumnException("Column %s does not exist.", col);}+ Type newType = updateColumnType.getNewDataType();StringBuilder sqlBuilder = new StringBuilder(ALTER_TABLE + quotedIdentifier(jdbcTable.name()));sqlBuilder.append("\n").append(ALTER_COLUMN).append(quotedIdentifier(col)).append(" SET DATA TYPE ")- .append(typeConverter.fromGravitino(updateColumnType.getNewDataType()));+ .append(typeConverter.fromGravitino(newType));+ // SET DATA TYPE resets the column to the new type's default collation. When the column has an+ // explicit non-default collation and the new type is still collatable text, re-apply it so a+ // type change does not silently drop the collation. Non-text targets must not carry COLLATE;+ // PostgreSQL rejects it.+ if (isCollatableTextType(newType)) {+ String collation = explicitColumnCollation(schemaName, jdbcTable.name(), col);+ if (collation != null) {+ sqlBuilder.append(" COLLATE ").append(collation);+ }+ }if (!column.nullable()) {sqlBuilder.append(",\n")@@ -690,6 +701,57 @@ public class PostgreSqlTableOperations extends JdbcTableOperationsreturn sqlBuilder.append(";").toString();}+ private static boolean isCollatableTextType(Type type) {+ return type instanceof Types.StringType+ || type instanceof Types.VarCharType+ || type instanceof Types.FixedCharType;+ }++ /**+ * Returns the explicit collation of a column as a schema-qualified, quoted identifier (for+ * example {@code "pg_catalog"."C"}), or null when the column uses the type's default collation.+ *+ * <p>A collation is a schema object, so both its schema and name are read and quoted separately.+ * An unqualified name would fail when the collation's schema is not on the connection's search+ * path, and would silently rebind the column to a same-named collation in another schema. {@code+ * information_schema.columns.collation_name} is null for the type default, so a non-null value is+ * always an explicit collation worth preserving across a type change.+ */+ @Nullable+ private String explicitColumnCollation(String schemaName, String tableName, String columnName) {+ // No data source means SQL generation without a live connection (for example unit tests that+ // only assert the generated statement); there is nothing to look up.+ if (dataSource == null) {+ return null;+ }+ String sql =+ "SELECT collation_schema, collation_name FROM information_schema.columns "+ + "WHERE table_schema = ? AND table_name = ? AND column_name = ?";+ try (Connection connection = dataSource.getConnection();+ PreparedStatement statement = connection.prepareStatement(sql)) {+ statement.setString(1, schemaName);+ statement.setString(2, tableName);+ statement.setString(3, columnName);+ try (ResultSet rows = statement.executeQuery()) {+ if (!rows.next()) {+ return null;+ }+ String collationName = rows.getString("collation_name");+ if (collationName == null) {+ return null;+ }+ String collationSchema = rows.getString("collation_schema");+ // collation_schema is non-null whenever collation_name is, but quote defensively and fall+ // back to the bare name if it is ever absent.+ return collationSchema == null+ ? quotedIdentifier(collationName)+ : quotedIdentifier(collationSchema) + "." + quotedIdentifier(collationName);+ }+ } catch (SQLException e) {+ throw exceptionMapper.toGravitinoException(e);+ }+ }+private String renameColumnFieldDefinition(TableChange.RenameColumn renameColumn, String tableName) {if (renameColumn.fieldName().length > 1) {diff --git a/catalogs/catalog-jdbc-postgresql/src/test/java/org/apache/gravitino/catalog/postgresql/operation/TestPostgreSqlTableOperations.java b/catalogs/catalog-jdbc-postgresql/src/test/java/org/apache/gravitino/catalog/postgresql/operation/TestPostgreSqlTableOperations.javaindex d4bac133f6..45d15ab1bf 100644--- a/catalogs/catalog-jdbc-postgresql/src/test/java/org/apache/gravitino/catalog/postgresql/operation/TestPostgreSqlTableOperations.java+++ b/catalogs/catalog-jdbc-postgresql/src/test/java/org/apache/gravitino/catalog/postgresql/operation/TestPostgreSqlTableOperations.java@@ -22,6 +22,7 @@ import com.google.common.collect.Maps;import com.google.common.io.BaseEncoding;import java.sql.Connection;import java.sql.DriverManager;+import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;@@ -784,6 +785,156 @@ public class TestPostgreSqlTableOperations extends TestPostgreSql {}}+ @Test+ void testUpdateColumnTypeKeepsExplicitCollation() throws SQLException {+ String table = RandomNameUtils.genRandomName("collation_type_change");+ try (Connection connection = DATA_SOURCE.getConnection()) {+ JdbcConnectorUtils.executeUpdate(+ connection,+ "CREATE TABLE "+ + TEST_DB_NAME+ + "."+ + table+ + "(name varchar(10) COLLATE \"C\" NOT NULL)");+ try {+ Assertions.assertArrayEquals(+ new String[] {"pg_catalog", "C"}, readCollation(connection, table, "name"));++ // Widen the type; the explicit "C" collation must survive the change.+ TABLE_OPERATIONS.alterTable(+ TEST_DB_NAME,+ table,+ TableChange.updateColumnType(new String[] {"name"}, Types.VarCharType.of(50)));+ Assertions.assertArrayEquals(+ new String[] {"pg_catalog", "C"}, readCollation(connection, table, "name"));+ } finally {+ TABLE_OPERATIONS.drop(TEST_DB_NAME, table);+ }+ }+ }++ @Test+ void testUpdateColumnTypeWithoutExplicitCollationStaysDefault() throws SQLException {+ String table = RandomNameUtils.genRandomName("default_collation_type_change");+ try (Connection connection = DATA_SOURCE.getConnection()) {+ JdbcConnectorUtils.executeUpdate(+ connection, "CREATE TABLE " + TEST_DB_NAME + "." + table + "(name varchar(10))");+ try {+ // A column on the database default collation reports no explicit collation.+ Assertions.assertNull(readCollation(connection, table, "name"));++ TABLE_OPERATIONS.alterTable(+ TEST_DB_NAME,+ table,+ TableChange.updateColumnType(new String[] {"name"}, Types.VarCharType.of(50)));+ Assertions.assertNull(readCollation(connection, table, "name"));+ } finally {+ TABLE_OPERATIONS.drop(TEST_DB_NAME, table);+ }+ }+ }++ @Test+ void testUpdateColumnTypeKeepsCollationFromAnotherSchema() throws SQLException {+ String collationSchema = RandomNameUtils.genRandomName("coll_schema");+ String table = RandomNameUtils.genRandomName("cross_schema_collation");+ try (Connection connection = DATA_SOURCE.getConnection()) {+ // A collation that lives outside the table's schema, so it is not on the search path when the+ // column type is altered. An unqualified COLLATE would fail to resolve it.+ JdbcConnectorUtils.executeUpdate(connection, "CREATE SCHEMA \"" + collationSchema + "\"");+ JdbcConnectorUtils.executeUpdate(+ connection, "CREATE COLLATION \"" + collationSchema + "\".c_copy FROM \"C\"");+ JdbcConnectorUtils.executeUpdate(+ connection,+ "CREATE TABLE "+ + TEST_DB_NAME+ + "."+ + table+ + "(name varchar(10) COLLATE \""+ + collationSchema+ + "\".c_copy NOT NULL)");+ try {+ Assertions.assertArrayEquals(+ new String[] {collationSchema, "c_copy"}, readCollation(connection, table, "name"));++ TABLE_OPERATIONS.alterTable(+ TEST_DB_NAME,+ table,+ TableChange.updateColumnType(new String[] {"name"}, Types.VarCharType.of(50)));++ Assertions.assertArrayEquals(+ new String[] {collationSchema, "c_copy"}, readCollation(connection, table, "name"));+ } finally {+ TABLE_OPERATIONS.drop(TEST_DB_NAME, table);+ JdbcConnectorUtils.executeUpdate(+ connection, "DROP SCHEMA \"" + collationSchema + "\" CASCADE");+ }+ }+ }++ @Test+ void testUpdateColumnTypeKeepsCollationIdentityOnNameClash() throws SQLException {+ String collationSchema = RandomNameUtils.genRandomName("coll_schema");+ String table = RandomNameUtils.genRandomName("clash_collation");+ try (Connection connection = DATA_SOURCE.getConnection()) {+ // Two collations share the simple name "und_ci": one in another schema (used by the column)+ // and one in the table's schema. An unqualified COLLATE would silently rebind the column to+ // the table-schema collation, changing the collation identity without any error.+ JdbcConnectorUtils.executeUpdate(connection, "CREATE SCHEMA \"" + collationSchema + "\"");+ JdbcConnectorUtils.executeUpdate(+ connection, "CREATE COLLATION \"" + collationSchema + "\".clash FROM \"C\"");+ JdbcConnectorUtils.executeUpdate(+ connection, "CREATE COLLATION " + TEST_DB_NAME + ".clash FROM \"POSIX\"");+ JdbcConnectorUtils.executeUpdate(+ connection,+ "CREATE TABLE "+ + TEST_DB_NAME+ + "."+ + table+ + "(name varchar(10) COLLATE \""+ + collationSchema+ + "\".clash NOT NULL)");+ try {+ Assertions.assertArrayEquals(+ new String[] {collationSchema, "clash"}, readCollation(connection, table, "name"));++ TABLE_OPERATIONS.alterTable(+ TEST_DB_NAME,+ table,+ TableChange.updateColumnType(new String[] {"name"}, Types.VarCharType.of(50)));++ // The collation schema must still be the original one, not the table's schema.+ Assertions.assertArrayEquals(+ new String[] {collationSchema, "clash"}, readCollation(connection, table, "name"));+ } finally {+ TABLE_OPERATIONS.drop(TEST_DB_NAME, table);+ JdbcConnectorUtils.executeUpdate(connection, "DROP COLLATION " + TEST_DB_NAME + ".clash");+ JdbcConnectorUtils.executeUpdate(+ connection, "DROP SCHEMA \"" + collationSchema + "\" CASCADE");+ }+ }+ }++ private static String[] readCollation(Connection connection, String table, String column)+ throws SQLException {+ try (PreparedStatement statement =+ connection.prepareStatement(+ "SELECT collation_schema, collation_name FROM information_schema.columns "+ + "WHERE table_schema = ? AND table_name = ? AND column_name = ?")) {+ statement.setString(1, TEST_DB_NAME);+ statement.setString(2, table);+ statement.setString(3, column);+ try (ResultSet rows = statement.executeQuery()) {+ Assertions.assertTrue(rows.next());+ String name = rows.getString("collation_name");+ if (name == null) {+ return null;+ }+ return new String[] {rows.getString("collation_schema"), name};+ }+ }+ }+@Testvoid testListTablesEscapesSchemaPattern() throws SQLException {String schema = "list\\schema_%";