|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one |
| 3 | + * or more contributor license agreements. See the NOTICE file |
| 4 | + * distributed with this work for additional information |
| 5 | + * regarding copyright ownership. The ASF licenses this file |
| 6 | + * to you under the Apache License, Version 2.0 (the |
| 7 | + * "License"); you may not use this file except in compliance |
| 8 | + * with the License. You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, |
| 13 | + * software distributed under the License is distributed on an |
| 14 | + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | + * KIND, either express or implied. See the License for the |
| 16 | + * specific language governing permissions and limitations |
| 17 | + * under the License. |
| 18 | + */ |
| 19 | + |
| 20 | +package org.apache.iceberg.mr.hive; |
| 21 | + |
| 22 | +import java.io.IOException; |
| 23 | +import java.util.Collection; |
| 24 | +import java.util.Collections; |
| 25 | +import java.util.LinkedHashMap; |
| 26 | +import java.util.List; |
| 27 | +import java.util.Map; |
| 28 | +import org.apache.hadoop.hive.metastore.api.Table; |
| 29 | +import org.apache.iceberg.FileFormat; |
| 30 | +import org.apache.iceberg.FileScanTask; |
| 31 | +import org.apache.iceberg.catalog.TableIdentifier; |
| 32 | +import org.apache.iceberg.io.CloseableIterable; |
| 33 | +import org.apache.iceberg.mr.hive.test.TestTables.TestTableType; |
| 34 | +import org.apache.iceberg.mr.hive.test.utils.HiveIcebergStorageHandlerTestUtils; |
| 35 | +import org.apache.thrift.TException; |
| 36 | +import org.junit.Assert; |
| 37 | +import org.junit.Test; |
| 38 | +import org.junit.runners.Parameterized.Parameters; |
| 39 | + |
| 40 | +/** |
| 41 | + * Verifies that Iceberg tables honor the {@code CLUSTERED BY} clause by checking HMS metadata |
| 42 | + * persistence, data readability and physical file distribution across buckets. |
| 43 | + */ |
| 44 | +public class TestHiveIcebergClusteredBy extends HiveIcebergStorageHandlerWithEngineBase { |
| 45 | + |
| 46 | + private static final String TABLE_NAME = "ice_clus_data_files"; |
| 47 | + private static final TableIdentifier TABLE_ID = TableIdentifier.of("default", TABLE_NAME); |
| 48 | + private static final int NUM_BUCKETS = 3; |
| 49 | + |
| 50 | + private static final Map<Integer, Long> EXPECTED_BUCKET_RECORD_COUNTS = buildExpectedBuckets(); |
| 51 | + |
| 52 | + private static Map<Integer, Long> buildExpectedBuckets() { |
| 53 | + Map<Integer, Long> bucketCounts = new LinkedHashMap<>(); |
| 54 | + bucketCounts.put(0, 4L); // customer_id=2 |
| 55 | + bucketCounts.put(1, 3L); // customer_id=3 |
| 56 | + bucketCounts.put(2, 2L); // customer_id=1 |
| 57 | + return Collections.unmodifiableMap(bucketCounts); |
| 58 | + } |
| 59 | + |
| 60 | + @Parameters(name = "fileFormat={0}, catalog={1}, isVectorized={2}, formatVersion={3}") |
| 61 | + public static Collection<Object[]> parameters() { |
| 62 | + return HiveIcebergStorageHandlerWithEngineBase.getParameters(p -> |
| 63 | + p.fileFormat() == FileFormat.PARQUET && |
| 64 | + p.testTableType() == TestTableType.HIVE_CATALOG && |
| 65 | + p.isVectorized()); |
| 66 | + } |
| 67 | + |
| 68 | + private void setUpIcebergTable() { |
| 69 | + shell.executeStatement( |
| 70 | + "CREATE TABLE " + TABLE_NAME + |
| 71 | + " (customer_id BIGINT, first_name STRING, last_name STRING) " + |
| 72 | + "CLUSTERED BY (customer_id) INTO " + NUM_BUCKETS + " BUCKETS " + |
| 73 | + "STORED BY ICEBERG STORED AS PARQUET " + |
| 74 | + "TBLPROPERTIES ('format-version'='" + formatVersion + "')"); |
| 75 | + |
| 76 | + shell.executeStatement(testTables.getInsertQuery( |
| 77 | + HiveIcebergStorageHandlerTestUtils.OTHER_CUSTOMER_RECORDS_2, TABLE_ID, false)); |
| 78 | + } |
| 79 | + |
| 80 | + @Test |
| 81 | + public void testHmsHasBucketMetadata() throws TException, InterruptedException { |
| 82 | + setUpIcebergTable(); |
| 83 | + validateHmsBucketMetadata(TABLE_NAME); |
| 84 | + } |
| 85 | + |
| 86 | + @Test |
| 87 | + public void testTotalRowCountAfterClusteredInsert() { |
| 88 | + setUpIcebergTable(); |
| 89 | + List<Object[]> result = shell.executeStatement("SELECT COUNT(*) FROM " + TABLE_NAME); |
| 90 | + long count = ((Number) result.getFirst()[0]).longValue(); |
| 91 | + Assert.assertEquals(HiveIcebergStorageHandlerTestUtils.OTHER_CUSTOMER_RECORDS_2.size(), count); |
| 92 | + } |
| 93 | + |
| 94 | + @Test |
| 95 | + public void testIcebergDataFilesAfterClusteredInsert() throws IOException { |
| 96 | + setUpIcebergTable(); |
| 97 | + org.apache.iceberg.Table icebergTable = testTables.loadTable(TABLE_ID); |
| 98 | + Map<Integer, Long> actualBucketRecordCounts = extractBucketRecordCounts(icebergTable); |
| 99 | + Assert.assertEquals(EXPECTED_BUCKET_RECORD_COUNTS, actualBucketRecordCounts); |
| 100 | + } |
| 101 | + |
| 102 | + /** |
| 103 | + * Tests that CLUSTERED BY metadata and bucketing behavior are preserved when migrating |
| 104 | + * a native Hive table to Iceberg using ALTER TABLE CONVERT TO ICEBERG. |
| 105 | + */ |
| 106 | + @Test |
| 107 | + public void testNativeToIcebergMigrationWithClusteredBy() throws TException, InterruptedException, IOException { |
| 108 | + String migrationTableName = "migration_clustered_table"; |
| 109 | + TableIdentifier migrationTableId = TableIdentifier.of("default", migrationTableName); |
| 110 | + |
| 111 | + // Create a Native Hive table with CLUSTERED BY |
| 112 | + shell.executeStatement( |
| 113 | + "CREATE EXTERNAL TABLE " + migrationTableName + |
| 114 | + " (customer_id BIGINT, first_name STRING, last_name STRING) " + |
| 115 | + "CLUSTERED BY (customer_id) INTO " + NUM_BUCKETS + " BUCKETS " + |
| 116 | + "STORED AS ORC"); |
| 117 | + |
| 118 | + // Insert initial records into the Native Hive table |
| 119 | + List<org.apache.iceberg.data.Record> initialRecords = |
| 120 | + HiveIcebergStorageHandlerTestUtils.OTHER_CUSTOMER_RECORDS_2.subList(0, 4); |
| 121 | + shell.executeStatement(testTables.getInsertQuery(initialRecords, migrationTableId, false)); |
| 122 | + |
| 123 | + validateHmsBucketMetadata(migrationTableName); |
| 124 | + |
| 125 | + List<Object[]> initialCount = shell.executeStatement("SELECT COUNT(*) FROM " + migrationTableName); |
| 126 | + Assert.assertEquals(4L, ((Number) initialCount.getFirst()[0]).longValue()); |
| 127 | + |
| 128 | + // Convert the Native Hive table to Iceberg table |
| 129 | + shell.executeStatement("ALTER TABLE " + migrationTableName + " CONVERT TO ICEBERG"); |
| 130 | + |
| 131 | + validateHmsBucketMetadata(migrationTableName); |
| 132 | + Table hmsTable = shell.metastore().getTable("default", migrationTableName); |
| 133 | + Assert.assertEquals("org.apache.iceberg.mr.hive.HiveIcebergStorageHandler", |
| 134 | + hmsTable.getParameters().get("storage_handler")); |
| 135 | + |
| 136 | + // Insert remaining records into the Iceberg table |
| 137 | + List<org.apache.iceberg.data.Record> remainingRecords = |
| 138 | + HiveIcebergStorageHandlerTestUtils.OTHER_CUSTOMER_RECORDS_2.subList(4, 9); |
| 139 | + shell.executeStatement(testTables.getInsertQuery(remainingRecords, migrationTableId, false)); |
| 140 | + |
| 141 | + // Validate Iceberg table metadata and bucketing behavior |
| 142 | + List<Object[]> finalCount = shell.executeStatement("SELECT COUNT(*) FROM " + migrationTableName); |
| 143 | + Assert.assertEquals(HiveIcebergStorageHandlerTestUtils.OTHER_CUSTOMER_RECORDS_2.size(), |
| 144 | + ((Number) finalCount.getFirst()[0]).longValue()); |
| 145 | + |
| 146 | + org.apache.iceberg.Table icebergTable = testTables.loadTable(migrationTableId); |
| 147 | + Map<Integer, Long> bucketCounts = extractBucketRecordCounts(icebergTable); |
| 148 | + Assert.assertEquals(EXPECTED_BUCKET_RECORD_COUNTS, bucketCounts); |
| 149 | + |
| 150 | + shell.executeStatement("DROP TABLE IF EXISTS " + migrationTableName); |
| 151 | + } |
| 152 | + |
| 153 | + private void validateHmsBucketMetadata(String tableName) throws TException, InterruptedException { |
| 154 | + Table hmsTable = shell.metastore().getTable("default", tableName); |
| 155 | + Assert.assertEquals(NUM_BUCKETS, hmsTable.getSd().getNumBuckets()); |
| 156 | + Assert.assertEquals(Collections.singletonList("customer_id"), hmsTable.getSd().getBucketCols()); |
| 157 | + } |
| 158 | + |
| 159 | + /** |
| 160 | + * Extracts bucket ID from file names and counts records per bucket. |
| 161 | + * Handles both Iceberg file names ({bucketId}-{attemptId}-...) and native Hive file names ({bucketId}_0). |
| 162 | + */ |
| 163 | + private Map<Integer, Long> extractBucketRecordCounts(org.apache.iceberg.Table icebergTable) throws IOException { |
| 164 | + Map<Integer, Long> bucketRecordCounts = new LinkedHashMap<>(); |
| 165 | + try (CloseableIterable<FileScanTask> tasks = icebergTable.newScan().planFiles()) { |
| 166 | + for (FileScanTask task : tasks) { |
| 167 | + String path = task.file().location(); |
| 168 | + String filename = path.substring(path.lastIndexOf('/') + 1); |
| 169 | + |
| 170 | + int bucketId; |
| 171 | + if (!filename.contains("-")) { |
| 172 | + // Native Hive: 000000_0 → bucket 0 |
| 173 | + bucketId = Integer.parseInt(filename.split("_")[0]); |
| 174 | + } else { |
| 175 | + // Iceberg: 00000-0-... → bucket 0 |
| 176 | + bucketId = Integer.parseInt(filename.split("-")[0]); |
| 177 | + } |
| 178 | + |
| 179 | + // Sum records across multiple files in the same bucket (e.g., multiple inserts) |
| 180 | + bucketRecordCounts.merge(bucketId, task.file().recordCount(), Long::sum); |
| 181 | + } |
| 182 | + } |
| 183 | + return bucketRecordCounts; |
| 184 | + } |
| 185 | +} |
0 commit comments