rdblue commented on a change in pull request #227: ORC column map fix URL: https://github.com/apache/incubator-iceberg/pull/227#discussion_r326393122
########## File path: orc/src/main/java/org/apache/iceberg/orc/ORCSchemaUtil.java ########## @@ -0,0 +1,412 @@ +/* + * 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.iceberg.orc; + +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicInteger; +import org.apache.iceberg.Schema; +import org.apache.iceberg.types.Type; +import org.apache.iceberg.types.TypeUtil; +import org.apache.iceberg.types.Types; +import org.apache.orc.TypeDescription; + +/** + * Utilities for mapping Iceberg to ORC schemas. + */ +final class ORCSchemaUtil { + + private static final String ICEBERG_ID_ATTRIBUTE = "iceberg.id"; + private static final String ICEBERG_REQUIRED_ATTRIBUTE = "iceberg.required"; + + private static final Map<Type.TypeID, TypeDescription.Category> TYPE_MAPPING = + ImmutableMap.<Type.TypeID, TypeDescription.Category>builder() + .put(Type.TypeID.BOOLEAN, TypeDescription.Category.BOOLEAN) + .put(Type.TypeID.INTEGER, TypeDescription.Category.INT) + .put(Type.TypeID.TIME, TypeDescription.Category.INT) + .put(Type.TypeID.LONG, TypeDescription.Category.LONG) + .put(Type.TypeID.FLOAT, TypeDescription.Category.FLOAT) + .put(Type.TypeID.DOUBLE, TypeDescription.Category.DOUBLE) + .put(Type.TypeID.DATE, TypeDescription.Category.DATE) + .put(Type.TypeID.TIMESTAMP, TypeDescription.Category.TIMESTAMP) + .put(Type.TypeID.STRING, TypeDescription.Category.STRING) + .put(Type.TypeID.UUID, TypeDescription.Category.BINARY) + .put(Type.TypeID.FIXED, TypeDescription.Category.BINARY) + .put(Type.TypeID.BINARY, TypeDescription.Category.BINARY) + .put(Type.TypeID.DECIMAL, TypeDescription.Category.DECIMAL) + .build(); + + private ORCSchemaUtil() {} + + static TypeDescription toOrc(Schema schema) { + final TypeDescription root = TypeDescription.createStruct(); + final Types.StructType schemaRoot = schema.asStruct(); + for (Types.NestedField field : schemaRoot.asStructType().fields()) { + TypeDescription orcColumType = toOrc(field.fieldId(), field.type(), field.isRequired()); + root.addField(field.name(), orcColumType); + } + return root; + } + + private static TypeDescription toOrc(Integer fieldId, Type type, boolean isRequired) { + final TypeDescription orcType; + + switch (type.typeId()) { + case BOOLEAN: + orcType = TypeDescription.createBoolean(); + break; + case INTEGER: + case TIME: + orcType = TypeDescription.createInt(); + break; + case LONG: + orcType = TypeDescription.createLong(); + break; + case FLOAT: + orcType = TypeDescription.createFloat(); + break; + case DOUBLE: + orcType = TypeDescription.createDouble(); + break; + case DATE: + orcType = TypeDescription.createDate(); + break; + case TIMESTAMP: + orcType = TypeDescription.createTimestamp(); + break; + case STRING: + orcType = TypeDescription.createString(); + break; + case UUID: + case FIXED: + case BINARY: + orcType = TypeDescription.createBinary(); + break; + case DECIMAL: { + Types.DecimalType decimal = (Types.DecimalType) type; + orcType = TypeDescription.createDecimal() + .withScale(decimal.scale()) + .withPrecision(decimal.precision()); + break; + } + case STRUCT: { + orcType = TypeDescription.createStruct(); + for (Types.NestedField field : type.asStructType().fields()) { + TypeDescription childType = toOrc(field.fieldId(), field.type(), field.isRequired()); + orcType.addField(field.name(), childType); + } + break; + } + case LIST: { + Types.ListType list = (Types.ListType) type; + TypeDescription elementType = toOrc(list.elementId(), list.elementType(), + list.isElementRequired()); + orcType = TypeDescription.createList(elementType); + break; + } + case MAP: { + Types.MapType map = (Types.MapType) type; + TypeDescription keyType = toOrc(map.keyId(), map.keyType(), true); + TypeDescription valueType = toOrc(map.valueId(), map.valueType(), map.isValueRequired()); + orcType = TypeDescription.createMap(keyType, valueType); + break; + } + default: + throw new IllegalArgumentException("Unhandled type " + type.typeId()); + } + + // Set Iceberg column attributes for mapping + orcType.setAttribute(ICEBERG_ID_ATTRIBUTE, String.valueOf(fieldId)); + orcType.setAttribute(ICEBERG_REQUIRED_ATTRIBUTE, String.valueOf(isRequired)); + return orcType; + } + + /** + * Converts an Iceberg schema to a corresponding ORC schema within the context of an existing + * ORC file schema. This method also handles schema evolution from the original ORC file schema + * to the given Iceberg schema. + * + * @param schema an Iceberg schema + * @param originalOrcSchema an existing ORC file schema + * @return the resulting ORC schema + */ + static TypeDescription toOrc(Schema schema, TypeDescription originalOrcSchema) { + final Map<Integer, OrcColumn> icebergToOrc = icebergToOrcMapping("root", originalOrcSchema); + return toOrc(Integer.MIN_VALUE, schema.asStruct(), true, icebergToOrc); + } + + private static TypeDescription toOrc(Integer fieldId, Type type, boolean isRequired, + Map<Integer, OrcColumn> mapping) { + final TypeDescription orcType; + + switch (type.typeId()) { + case STRUCT: { + orcType = TypeDescription.createStruct(); + for (Types.NestedField nestedField : type.asStructType().fields()) { + String name = Optional.ofNullable(mapping.get(nestedField.fieldId())) + .map(OrcColumn::name) + .orElse(nestedField.name()); + TypeDescription childType = toOrc(nestedField.fieldId(), nestedField.type(), + nestedField.isRequired(), mapping); + orcType.addField(name, childType); + } + break; + } + case LIST: { + Types.ListType list = (Types.ListType) type; + TypeDescription elementType = toOrc(list.elementId(), list.elementType(), + list.isElementRequired(), mapping); + orcType = TypeDescription.createList(elementType); + break; + } + case MAP: { + Types.MapType map = (Types.MapType) type; + TypeDescription keyType = toOrc(map.keyId(), map.keyType(), true, mapping); + TypeDescription valueType = toOrc(map.valueId(), map.valueType(), map.isValueRequired(), + mapping); + orcType = TypeDescription.createMap(keyType, valueType); + break; + } + default: { + if (mapping.containsKey(fieldId)) { + TypeDescription originalType = mapping.get(fieldId).type(); + Optional<TypeDescription> promotedType = getPromotedType(type, originalType); + + if (promotedType.isPresent()) { + orcType = promotedType.get(); + } else { + Preconditions.checkArgument(isSameType(originalType, type), + "Can not promote %s type to %s", + originalType.getCategory(), type.typeId().name()); + orcType = originalType.clone(); + } + } else { + // This column is new, we need to convert via the usual way + orcType = toOrc(fieldId, type, isRequired); + } + } + } + + return orcType; + } + + private static Map<Integer, OrcColumn> icebergToOrcMapping(String name, TypeDescription orcType) { + Map<Integer, OrcColumn> icebergToOrc = Maps.newHashMap(); + switch (orcType.getCategory()) { + case STRUCT: + List<String> childrenNames = orcType.getFieldNames(); + List<TypeDescription> children = orcType.getChildren(); + for (int i = 0; i < children.size(); i++) { + icebergToOrc.putAll(icebergToOrcMapping(childrenNames.get(i), + children.get(i))); + } + break; + case LIST: + icebergToOrc.putAll(icebergToOrcMapping("element", orcType.getChildren().get(0))); + break; + case MAP: + icebergToOrc.putAll(icebergToOrcMapping("key", orcType.getChildren().get(0))); + icebergToOrc.putAll(icebergToOrcMapping("value", orcType.getChildren().get(1))); + break; + } + + if (orcType.getId() > 0) { + // Only add to non-root types. + icebergToOrc.put(Integer.parseInt(orcType.getAttributeValue(ICEBERG_ID_ATTRIBUTE)), + new OrcColumn(name, orcType)); + } + + return icebergToOrc; + } + + + private static Optional<TypeDescription> getPromotedType(Type icebergType, + TypeDescription originalOrcType) { + TypeDescription promotedOrcType = null; + if (Type.TypeID.LONG.equals(icebergType.typeId()) && + TypeDescription.Category.INT.equals(originalOrcType.getCategory())) { + // Promote: int to long + promotedOrcType = TypeDescription.createLong(); + } else if (Type.TypeID.DOUBLE.equals(icebergType.typeId()) && + TypeDescription.Category.FLOAT.equals(originalOrcType.getCategory())) { + // Promote: float to double + promotedOrcType = TypeDescription.createDouble(); + } else if (Type.TypeID.DECIMAL.equals(icebergType.typeId()) && + TypeDescription.Category.DECIMAL.equals(originalOrcType.getCategory())) { + // Promote: decimal(P, S) to decimal(P', S) if P' > P + Types.DecimalType newDecimal = (Types.DecimalType) icebergType; + if (newDecimal.scale() == originalOrcType.getScale() && + newDecimal.precision() > originalOrcType.getPrecision()) { + promotedOrcType = TypeDescription.createDecimal() + .withScale(newDecimal.scale()) + .withPrecision(newDecimal.precision()); + } + } + return Optional.ofNullable(promotedOrcType); + } + + private static boolean isSameType(TypeDescription orcType, Type icebergType) { + return Objects.equals(TYPE_MAPPING.get(icebergType.typeId()), orcType.getCategory()); + } + + /** + * Convert an ORC schema to an Iceberg schema. This method handles the convertion from the original + * Iceberg colum mapping IDs if present in the ORC column attributes, otherwise, ORC column IDs + * will be assigned following ORCs pre-order ID assignment. + * + * @return the Iceberg schema + */ + static Schema toIceberg(TypeDescription orcSchema) { + List<TypeDescription> children = orcSchema.getChildren(); + List<String> childrenNames = orcSchema.getFieldNames(); + Preconditions.checkState(children.size() == childrenNames.size(), + "Error in ORC file, children fields and names do not match."); + + List<Types.NestedField> icebergFields = Lists.newArrayListWithExpectedSize(children.size()); + AtomicInteger lastColumnId = new AtomicInteger(orcSchema.getMaximumId()); + for (int i = 0; i < children.size(); i++) { + icebergFields.add(convertOrcToIceberg(children.get(i), childrenNames.get(i), + lastColumnId::incrementAndGet)); + } + + return new Schema(icebergFields); + } + + private static Integer icebergID(TypeDescription orcType) { + return Optional.ofNullable(orcType.getAttributeValue(ICEBERG_ID_ATTRIBUTE)) + .map(Integer::parseInt) + .orElse(null); + } + + private static boolean isRequired(TypeDescription orcType) { + String isRequiredStr = orcType.getAttributeValue(ICEBERG_REQUIRED_ATTRIBUTE); + if (isRequiredStr != null) { + return Boolean.parseBoolean(isRequiredStr); + } + return false; + } + + private static Types.NestedField getIcebergType(int icebergID, String name, Type type, + boolean isRequired) { + return isRequired ? + Types.NestedField.required(icebergID, name, type) : + Types.NestedField.optional(icebergID, name, type); + } + + private static Types.NestedField convertOrcToIceberg(TypeDescription orcType, String name, + TypeUtil.NextID nextID) { + + final int icebergID = Optional.ofNullable(icebergID(orcType)).orElseGet(nextID::get); + final boolean isRequired = isRequired(orcType); + + switch (orcType.getCategory()) { + case BOOLEAN: + return getIcebergType(icebergID, name, Types.BooleanType.get(), isRequired); + case BYTE: + case SHORT: + case INT: + return getIcebergType(icebergID, name, Types.IntegerType.get(), isRequired); + case LONG: + return getIcebergType(icebergID, name, Types.LongType.get(), isRequired); + case FLOAT: + return getIcebergType(icebergID, name, Types.FloatType.get(), isRequired); + case DOUBLE: + return getIcebergType(icebergID, name, Types.DoubleType.get(), isRequired); + case STRING: + case CHAR: + case VARCHAR: + return getIcebergType(icebergID, name, Types.StringType.get(), isRequired); + case BINARY: + return getIcebergType(icebergID, name, Types.BinaryType.get(), isRequired); + case DATE: + return getIcebergType(icebergID, name, Types.DateType.get(), isRequired); + case TIMESTAMP: + return getIcebergType(icebergID, name, Types.TimestampType.withoutZone(), isRequired); + case DECIMAL: + return getIcebergType(icebergID, name, + Types.DecimalType.of(orcType.getPrecision(), orcType.getScale()), + isRequired); + case STRUCT: { + List<String> fieldNames = orcType.getFieldNames(); + List<TypeDescription> fieldTypes = orcType.getChildren(); + List<Types.NestedField> fields = new ArrayList<>(fieldNames.size()); + for (int c = 0; c < fieldNames.size(); ++c) { + String childName = fieldNames.get(c); + TypeDescription type = fieldTypes.get(c); + Types.NestedField field = convertOrcToIceberg(type, childName, nextID); + fields.add(field); + } + + return getIcebergType(icebergID, name, Types.StructType.of(fields), isRequired); + } + case LIST: { + TypeDescription elementType = orcType.getChildren().get(0); + Types.NestedField element = convertOrcToIceberg(elementType, "element", nextID); + + Types.ListType listTypeWithElem = isRequired(elementType) ? + Types.ListType.ofRequired(element.fieldId(), element.type()) : + Types.ListType.ofOptional(element.fieldId(), element.type()); + return isRequired ? + Types.NestedField.required(icebergID, name, listTypeWithElem) : + Types.NestedField.optional(icebergID, name, listTypeWithElem); + } + case MAP: { + TypeDescription keyType = orcType.getChildren().get(0); + Types.NestedField key = convertOrcToIceberg(keyType, "key", nextID); + TypeDescription valueType = orcType.getChildren().get(1); + Types.NestedField value = convertOrcToIceberg(valueType, "value", nextID); + + Types.MapType mapTypeWithKV = isRequired(valueType) ? + Types.MapType.ofRequired(key.fieldId(), value.fieldId(), key.type(), value.type()) : + Types.MapType.ofOptional(key.fieldId(), value.fieldId(), key.type(), value.type()); + + return getIcebergType(icebergID, name, mapTypeWithKV, isRequired); + } + default: + // We don't have an answer for union types. + throw new IllegalArgumentException("Can't handle " + orcType); + } + } + + private static class OrcColumn { Review comment: Would `OrcField` be a more accurate name since these may be nested fields? ---------------------------------------------------------------- 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. For queries about this service, please contact Infrastructure at: [email protected] With regards, Apache Git Services --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
