AvroSchemaUtil.java org::apache::iceberg::avro::AvroSchemaUtil org::apache::iceberg::avro /* *LicensedtotheApacheSoftwareFoundation(ASF)underone *ormorecontributorlicenseagreements.SeetheNOTICEfile *distributedwiththisworkforadditionalinformation *regardingcopyrightownership.TheASFlicensesthisfile *toyouundertheApacheLicense,Version2.0(the *"License");youmaynotusethisfileexceptincompliance *withtheLicense.YoumayobtainacopyoftheLicenseat * *http://www.apache.org/licenses/LICENSE-2.0 * *Unlessrequiredbyapplicablelaworagreedtoinwriting, *softwaredistributedundertheLicenseisdistributedonan *"ASIS"BASIS,WITHOUTWARRANTIESORCONDITIONSOFANY *KIND,eitherexpressorimplied.SeetheLicenseforthe *specificlanguagegoverningpermissionsandlimitations *undertheLicense. */ packageorg.apache.iceberg.avro; importjava.util.List; importjava.util.Map; importjava.util.Set; importjava.util.function.BiFunction; importorg.apache.avro.JsonProperties; importorg.apache.avro.LogicalType; importorg.apache.avro.LogicalTypes; importorg.apache.avro.Schema; importorg.apache.iceberg.mapping.MappedField; importorg.apache.iceberg.mapping.NameMapping; importorg.apache.iceberg.relocated.com.google.common.base.Preconditions; importorg.apache.iceberg.relocated.com.google.common.collect.ImmutableList; importorg.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; importorg.apache.iceberg.relocated.com.google.common.collect.Lists; importorg.apache.iceberg.types.Type; importorg.apache.iceberg.types.TypeUtil; importorg.apache.iceberg.types.Types; publicclassAvroSchemaUtil{ privateAvroSchemaUtil(){} //OriginalIcebergfieldnamecorrespondingtoasanitizedAvroname publicstaticfinalStringICEBERG_FIELD_NAME_PROP="iceberg-field-name"; publicstaticfinalStringFIELD_ID_PROP="field-id"; publicstaticfinalStringKEY_ID_PROP="key-id"; publicstaticfinalStringVALUE_ID_PROP="value-id"; publicstaticfinalStringELEMENT_ID_PROP="element-id"; publicstaticfinalStringADJUST_TO_UTC_PROP="adjust-to-utc"; privatestaticfinalSchemaNULL=Schema.create(Schema.Type.NULL); privatestaticfinalSchema.TypeMAP=Schema.Type.MAP; privatestaticfinalSchema.TypeARRAY=Schema.Type.ARRAY; privatestaticfinalSchema.TypeUNION=Schema.Type.UNION; privatestaticfinalSchema.TypeRECORD=Schema.Type.RECORD; publicstaticSchemaconvert(org.apache.iceberg.Schemaschema,StringtableName){ returnconvert(schema,ImmutableMap.of(schema.asStruct(),tableName)); } publicstaticSchemaconvert( org.apache.iceberg.Schemaschema,Map<Types.StructType,String>names){ returnTypeUtil.visit(schema,newTypeToSchema.WithTypeToName(names)); } publicstaticSchemaconvert(Typetype){ returnconvert(type,ImmutableMap.of()); } publicstaticSchemaconvert(Types.StructTypetype,Stringname){ returnconvert(type,ImmutableMap.of(type,name)); } publicstaticSchemaconvert(Typetype,Map<Types.StructType,String>names){ returnTypeUtil.visit(type,newTypeToSchema.WithTypeToName(names)); } publicstaticSchemaconvert( Typetype,BiFunction<Integer,Types.StructType,String>namesFunction){ returnTypeUtil.visit(type,newTypeToSchema.WithNamesFunction(namesFunction)); } publicstaticTypeconvert(Schemaschema){ returnAvroSchemaVisitor.visit(schema,newSchemaToType(schema)); } publicstaticorg.apache.iceberg.SchematoIceberg(Schemaschema){ finalList<Types.NestedField>fields=convert(schema).asNestedType().asStructType().fields(); returnneworg.apache.iceberg.Schema(fields); } staticbooleanhasIds(Schemaschema){ returnAvroCustomOrderSchemaVisitor.visit(schema,newHasIds()); } staticbooleanmissingIds(Schemaschema){ returnAvroCustomOrderSchemaVisitor.visit(schema,newMissingIds()); } publicstaticMap<Type,Schema>convertTypes(Types.StructTypetype,Stringname){ TypeToSchema.WithTypeToNameconverter= newTypeToSchema.WithTypeToName(ImmutableMap.of(type,name)); TypeUtil.visit(type,converter); returnImmutableMap.copyOf(converter.getConversionMap()); } publicstaticSchemapruneColumns(Schemaschema,Set<Integer>selectedIds){ returnnewPruneColumns(selectedIds,null).rootSchema(schema); } @Deprecated publicstaticSchemapruneColumns( Schemaschema,Set<Integer>selectedIds,NameMappingnameMapping){ returnnewPruneColumns(selectedIds,nameMapping).rootSchema(schema); } publicstaticSchemabuildAvroProjection( Schemaschema,org.apache.iceberg.Schemaexpected,Map<String,String>renames){ returnAvroCustomOrderSchemaVisitor.visit(schema,newBuildAvroProjection(expected,renames)); } publicstaticSchemaapplyNameMapping(SchemafileSchema,NameMappingnameMapping){ if(nameMapping!=null){ returnAvroSchemaVisitor.visit(fileSchema,newApplyNameMapping(nameMapping)); } returnfileSchema; } publicstaticbooleanisTimestamptz(Schemaschema){ LogicalTypelogicalType=schema.getLogicalType(); if(logicalTypeinstanceofLogicalTypes.TimestampMillis ||logicalTypeinstanceofLogicalTypes.TimestampMicros){ //timestamptzisadjustedtoUTC Objectvalue=schema.getObjectProp(ADJUST_TO_UTC_PROP); if(value==null){ //notallavrotimestamplogicaltypeswillhavetheadjust_to_utcprop,defaultto //timestampwithouttimezone returnfalse; }elseif(valueinstanceofBoolean){ return(Boolean)value; }elseif(valueinstanceofString){ returnBoolean.parseBoolean((String)value); } } returnfalse; } publicstaticbooleanisOptionSchema(Schemaschema){ if(schema.getType()==UNION&&schema.getTypes().size()==2){ if(schema.getTypes().get(0).getType()==Schema.Type.NULL){ returntrue; }elseif(schema.getTypes().get(1).getType()==Schema.Type.NULL){ returntrue; } } returnfalse; } staticSchematoOption(Schemaschema){ if(schema.getType()==UNION){ Preconditions.checkArgument( isOptionSchema(schema),"Unionschemasarenotsupported:%s",schema); returnschema; }else{ returnSchema.createUnion(NULL,schema); } } staticSchemafromOption(Schemaschema){ Preconditions.checkArgument( schema.getType()==UNION,"Expectedunionschemabutwaspassed:%s",schema); Preconditions.checkArgument( schema.getTypes().size()==2,"Expectedoptionalschema,butwaspassed:%s",schema); if(schema.getTypes().get(0).getType()==Schema.Type.NULL){ returnschema.getTypes().get(1); }else{ returnschema.getTypes().get(0); } } staticSchemafromOptions(List<Schema>options){ Preconditions.checkArgument( options.size()==2,"Expectedtwoschemas,butwaspassed:%soptions",options.size()); if(options.get(0).getType()==Schema.Type.NULL){ returnoptions.get(1); }else{ returnoptions.get(0); } } publicstaticbooleanisKeyValueSchema(Schemaschema){ returnschema.getType()==RECORD&&schema.getFields().size()==2; } staticSchemacreateMap(intkeyId,SchemakeySchema,intvalueId,SchemavalueSchema){ StringkeyValueName="k"+keyId+"_v"+valueId; Schema.FieldkeyField=newSchema.Field("key",keySchema,null,(Object)null); keyField.addProp(FIELD_ID_PROP,keyId); Schema.FieldvalueField= newSchema.Field( "value", valueSchema, null, isOptionSchema(valueSchema)?JsonProperties.NULL_VALUE:null); valueField.addProp(FIELD_ID_PROP,valueId); returnLogicalMap.get() .addToSchema( Schema.createArray( Schema.createRecord( keyValueName,null,null,false,ImmutableList.of(keyField,valueField)))); } staticSchemacreateProjectionMap( StringrecordName, intkeyId, StringkeyName, SchemakeySchema, intvalueId, StringvalueName, SchemavalueSchema){ StringkeyValueName="k"+keyId+"_v"+valueId; Schema.FieldkeyField=newSchema.Field("key",keySchema,null,(Object)null); if(!"key".equals(keyName)){ keyField.addAlias(keyName); } keyField.addProp(FIELD_ID_PROP,keyId); Schema.FieldvalueField= newSchema.Field( "value", valueSchema, null, isOptionSchema(valueSchema)?JsonProperties.NULL_VALUE:null); valueField.addProp(FIELD_ID_PROP,valueId); if(!"value".equals(valueName)){ valueField.addAlias(valueName); } SchemakeyValueRecord= Schema.createRecord( keyValueName,null,null,false,ImmutableList.of(keyField,valueField)); if(!keyValueName.equals(recordName)){ keyValueRecord.addAlias(recordName); } returnLogicalMap.get().addToSchema(Schema.createArray(keyValueRecord)); } privatestaticIntegergetId(Schemaschema,StringpropertyName){ Integerid=getId(schema,propertyName,null,null); Preconditions.checkNotNull(id,"Missingexpected'%s'property",propertyName); returnid; } privatestaticIntegergetId( Schemaschema,StringpropertyName,NameMappingnameMapping,List<String>names){ if(schema.getType()==UNION){ returngetId(fromOption(schema),propertyName,nameMapping,names); } Objectid=schema.getObjectProp(propertyName); if(id!=null){ returntoInt(id); }elseif(nameMapping!=null){ MappedFieldmappedField=nameMapping.find(names); if(mappedField!=null){ returnmappedField.id(); } } returnnull; } staticbooleanhasProperty(Schemaschema,StringpropertyName){ if(schema.getType()==UNION){ returnhasProperty(fromOption(schema),propertyName); } returnschema.getObjectProp(propertyName)!=null; } publicstaticintgetKeyId(Schemaschema){ Preconditions.checkArgument( schema.getType()==MAP,"Cannotgetmapkeyidfornon-mapschema:%s",schema); returngetId(schema,KEY_ID_PROP); } staticIntegerkeyId(SchemamapSchema){ ObjectidObj=mapSchema.getObjectProp(KEY_ID_PROP); if(idObj!=null){ returntoInt(idObj); } returnnull; } staticIntegergetKeyId( Schemaschema,NameMappingnameMapping,Iterable<String>parentFieldNames){ Preconditions.checkArgument( schema.getType()==MAP,"Cannotgetmapkeyidfornon-mapschema:%s",schema); List<String>names=Lists.newArrayList(parentFieldNames); names.add("key"); returngetId(schema,KEY_ID_PROP,nameMapping,names); } publicstaticintgetValueId(Schemaschema){ Preconditions.checkArgument( schema.getType()==MAP,"Cannotgetmapvalueidfornon-mapschema:%s",schema); returngetId(schema,VALUE_ID_PROP); } staticIntegervalueId(SchemamapSchema){ ObjectidObj=mapSchema.getObjectProp(VALUE_ID_PROP); if(idObj!=null){ returntoInt(idObj); } returnnull; } staticIntegergetValueId( Schemaschema,NameMappingnameMapping,Iterable<String>parentFieldNames){ Preconditions.checkArgument( schema.getType()==MAP,"Cannotgetmapvalueidfornon-mapschema:%s",schema); List<String>names=Lists.newArrayList(parentFieldNames); names.add("value"); returngetId(schema,VALUE_ID_PROP,nameMapping,names); } publicstaticintgetElementId(Schemaschema){ Preconditions.checkArgument( schema.getType()==ARRAY,"Cannotgetarrayelementidfornon-arrayschema:%s",schema); returngetId(schema,ELEMENT_ID_PROP); } staticIntegerelementId(SchemaarraySchema){ ObjectidObj=arraySchema.getObjectProp(ELEMENT_ID_PROP); if(idObj!=null){ returntoInt(idObj); } returnnull; } staticIntegergetElementId( Schemaschema,NameMappingnameMapping,Iterable<String>parentFieldNames){ Preconditions.checkArgument( schema.getType()==ARRAY,"Cannotgetarrayelementidfornon-arrayschema:%s",schema); List<String>names=Lists.newArrayList(parentFieldNames); names.add("element"); returngetId(schema,ELEMENT_ID_PROP,nameMapping,names); } publicstaticintgetFieldId(Schema.Fieldfield){ Integerid=getFieldId(field,null,null); Preconditions.checkNotNull(id,"Missingexpected'%s'property",FIELD_ID_PROP); returnid; } staticIntegerfieldId(Schema.Fieldfield){ returngetFieldId(field,null,null); } staticIntegergetFieldId( Schema.Fieldfield,NameMappingnameMapping,Iterable<String>parentFieldNames){ Objectid=field.getObjectProp(FIELD_ID_PROP); if(id!=null){ returntoInt(id); }elseif(nameMapping!=null){ MappedFieldmappedField=nameMapping.find(parentFieldNames,field.name()); if(mappedField!=null){ returnmappedField.id(); } } returnnull; } publicstaticbooleanhasFieldId(Schema.Fieldfield){ returnfield.getObjectProp(FIELD_ID_PROP)!=null; } privatestaticinttoInt(Objectvalue){ if(valueinstanceofNumber){ return((Number)value).intValue(); }elseif(valueinstanceofString){ returnInteger.parseInt((String)value); } thrownewUnsupportedOperationException("Cannotcoercevaluetoint:"+value); } staticSchemacopyRecord(Schemarecord,List<Schema.Field>newFields,StringnewName){ Schemacopy; if(newName!=null){ copy=Schema.createRecord(newName,record.getDoc(),null,record.isError(),newFields); //thenamespaceisdefaultedtotherecord'snamespaceifitisnull,whichcausesrenames //withoutthenamespacetofail.using""insteadofnullchangesthisbehaviortomatchthe //originalschema. copy.addAlias(record.getName(),record.getNamespace()==null?"":record.getNamespace()); }else{ copy= Schema.createRecord( record.getName(), record.getDoc(), record.getNamespace(), record.isError(), newFields); } for(Map.Entry<String,Object>prop:record.getObjectProps().entrySet()){ copy.addProp(prop.getKey(),prop.getValue()); } returncopy; } staticSchema.FieldcopyField(Schema.Fieldfield,SchemanewSchema,StringnewName){ Schema.Fieldcopy= newSchema.Field(newName,newSchema,field.doc(),field.defaultVal(),field.order()); for(Map.Entry<String,Object>prop:field.getObjectProps().entrySet()){ copy.addProp(prop.getKey(),prop.getValue()); } if(!newName.equals(field.name())){ copy.addAlias(field.name()); } returncopy; } staticSchemareplaceElement(Schemaarray,SchemaelementSchema){ Preconditions.checkArgument( array.getType()==ARRAY,"CannotinvokereplaceElementonnonarrayschema:%s",array); Schemacopy=Schema.createArray(elementSchema); for(Map.Entry<String,Object>prop:array.getObjectProps().entrySet()){ copy.addProp(prop.getKey(),prop.getValue()); } returncopy; } staticSchemareplaceValue(Schemamap,SchemavalueSchema){ Preconditions.checkArgument( map.getType()==MAP,"CannotinvokereplaceValueonnonmapschema:%s",map); Schemacopy=Schema.createMap(valueSchema); for(Map.Entry<String,Object>prop:map.getObjectProps().entrySet()){ copy.addProp(prop.getKey(),prop.getValue()); } returncopy; } publicstaticStringmakeCompatibleName(Stringname){ if(!validAvroName(name)){ returnsanitize(name); } returnname; } staticbooleanvalidAvroName(Stringname){ intlength=name.length(); Preconditions.checkArgument(length>0,"Emptyname"); charfirst=name.charAt(0); if(!(Character.isLetter(first)||first=='_')){ returnfalse; } for(inti=1;i<length;i++){ charcharacter=name.charAt(i); if(!(Character.isLetterOrDigit(character)||character=='_')){ returnfalse; } } returntrue; } staticStringsanitize(Stringname){ intlength=name.length(); StringBuildersb=newStringBuilder(name.length()); charfirst=name.charAt(0); if(!(Character.isLetter(first)||first=='_')){ sb.append(sanitize(first)); }else{ sb.append(first); } for(inti=1;i<length;i++){ charcharacter=name.charAt(i); if(!(Character.isLetterOrDigit(character)||character=='_')){ sb.append(sanitize(character)); }else{ sb.append(character); } } returnsb.toString(); } privatestaticStringsanitize(charcharacter){ if(Character.isDigit(character)){ return"_"+character; } return"_x"+Integer.toHexString(character).toUpperCase(); } }