ArrowReader.java org::apache::iceberg::arrow::vectorized::ArrowReader org::apache::iceberg::arrow::vectorized::ArrowReader::VectorizedCombinedScanIterator org::apache::iceberg::arrow::vectorized /* *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.arrow.vectorized; importjava.io.IOException; importjava.nio.ByteBuffer; importjava.util.Collection; importjava.util.Iterator; importjava.util.List; importjava.util.Map; importjava.util.NoSuchElementException; importjava.util.Set; importjava.util.stream.Collectors; importjava.util.stream.Stream; importjava.util.stream.StreamSupport; importorg.apache.arrow.vector.NullCheckingForGet; importorg.apache.arrow.vector.VectorSchemaRoot; importorg.apache.arrow.vector.types.Types.MinorType; importorg.apache.iceberg.CombinedScanTask; importorg.apache.iceberg.FileFormat; importorg.apache.iceberg.FileScanTask; importorg.apache.iceberg.Schema; importorg.apache.iceberg.TableScan; importorg.apache.iceberg.encryption.EncryptedFiles; importorg.apache.iceberg.encryption.EncryptedInputFile; importorg.apache.iceberg.encryption.EncryptionManager; importorg.apache.iceberg.io.CloseableGroup; importorg.apache.iceberg.io.CloseableIterable; importorg.apache.iceberg.io.CloseableIterator; importorg.apache.iceberg.io.FileIO; importorg.apache.iceberg.io.InputFile; importorg.apache.iceberg.mapping.NameMappingParser; importorg.apache.iceberg.parquet.Parquet; importorg.apache.iceberg.parquet.TypeWithSchemaVisitor; importorg.apache.iceberg.relocated.com.google.common.base.Preconditions; importorg.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; importorg.apache.iceberg.relocated.com.google.common.collect.ImmutableSet; importorg.apache.iceberg.relocated.com.google.common.collect.Maps; importorg.apache.iceberg.relocated.com.google.common.collect.Sets; importorg.apache.iceberg.types.Type.TypeID; importorg.apache.iceberg.types.Types; importorg.apache.iceberg.util.ExceptionUtil; importorg.apache.iceberg.util.TableScanUtil; importorg.apache.parquet.schema.MessageType; importorg.slf4j.Logger; importorg.slf4j.LoggerFactory; publicclassArrowReaderextendsCloseableGroup{ privatestaticfinalLoggerLOG=LoggerFactory.getLogger(ArrowReader.class); privatestaticfinalSet<TypeID>SUPPORTED_TYPES= ImmutableSet.of( TypeID.BOOLEAN, TypeID.INTEGER, TypeID.LONG, TypeID.FLOAT, TypeID.DOUBLE, TypeID.STRING, TypeID.TIMESTAMP, TypeID.BINARY, TypeID.DATE, TypeID.UUID, TypeID.TIME, TypeID.DECIMAL); privatefinalSchemaschema; privatefinalFileIOio; privatefinalEncryptionManagerencryption; privatefinalintbatchSize; privatefinalbooleanreuseContainers; publicArrowReader(TableScanscan,intbatchSize,booleanreuseContainers){ this.schema=scan.schema(); this.io=scan.table().io(); this.encryption=scan.table().encryption(); this.batchSize=batchSize; //startplanningtasksinthebackground this.reuseContainers=reuseContainers; } publicCloseableIterator<ColumnarBatch>open(CloseableIterable<CombinedScanTask>tasks){ CloseableIterator<ColumnarBatch>itr= newVectorizedCombinedScanIterator( tasks,schema,null,io,encryption,true,batchSize,reuseContainers); addCloseable(itr); returnitr; } @Override publicvoidclose()throwsIOException{ super.close();//closedatafiles } privatestaticfinalclassVectorizedCombinedScanIterator implementsCloseableIterator<ColumnarBatch>{ privatefinalIterator<FileScanTask>fileItr; privatefinalMap<String,InputFile>inputFiles; privatefinalSchemaexpectedSchema; privatefinalStringnameMapping; privatefinalbooleancaseSensitive; privatefinalintbatchSize; privatefinalbooleanreuseContainers; privateCloseableIterator<ColumnarBatch>currentIterator; privateFileScanTaskcurrentTask; VectorizedCombinedScanIterator( CloseableIterable<CombinedScanTask>tasks, SchemaexpectedSchema, StringnameMapping, FileIOio, EncryptionManagerencryptionManager, booleancaseSensitive, intbatchSize, booleanreuseContainers){ List<FileScanTask>fileTasks= StreamSupport.stream(tasks.spliterator(),false) .map(CombinedScanTask::files) .flatMap(Collection::stream) .collect(Collectors.toList()); this.fileItr=fileTasks.iterator(); if(fileTasks.stream().anyMatch(TableScanUtil::hasDeletes)){ thrownewUnsupportedOperationException( "Cannotreadfilesthatrequireapplyingdeletefiles"); } if(expectedSchema.columns().isEmpty()){ thrownewUnsupportedOperationException( "Cannotreadwithoutatleastoneprojectedcolumn"); } Set<TypeID>unsupportedTypes= Sets.difference( expectedSchema.columns().stream() .map(c->c.type().typeId()) .collect(Collectors.toSet()), SUPPORTED_TYPES); if(!unsupportedTypes.isEmpty()){ thrownewUnsupportedOperationException( "Cannotreadunsupportedcolumntypes:"+unsupportedTypes); } Map<String,ByteBuffer>keyMetadata=Maps.newHashMap(); fileTasks.stream() .map(FileScanTask::file) .forEach(file->keyMetadata.put(file.path().toString(),file.keyMetadata())); Stream<EncryptedInputFile>encrypted= keyMetadata.entrySet().stream() .map( entry-> EncryptedFiles.encryptedInput( io.newInputFile(entry.getKey()),entry.getValue())); //decryptwiththebatchcalltoavoidmultipleRPCstoakeyserver,ifpossible @SuppressWarnings("StreamToIterable") Iterable<InputFile>decryptedFiles=encryptionManager.decrypt(encrypted::iterator); Map<String,InputFile>files=Maps.newHashMapWithExpectedSize(fileTasks.size()); decryptedFiles.forEach(decrypted->files.putIfAbsent(decrypted.location(),decrypted)); this.inputFiles=ImmutableMap.copyOf(files); this.currentIterator=CloseableIterator.empty(); this.expectedSchema=expectedSchema; this.nameMapping=nameMapping; this.caseSensitive=caseSensitive; this.batchSize=batchSize; this.reuseContainers=reuseContainers; } @Override publicbooleanhasNext(){ try{ while(true){ if(currentIterator.hasNext()){ returntrue; }elseif(fileItr.hasNext()){ this.currentIterator.close(); this.currentTask=fileItr.next(); this.currentIterator=open(currentTask); }else{ this.currentIterator.close(); returnfalse; } } }catch(IOException|RuntimeExceptione){ if(currentTask!=null&&!currentTask.isDataTask()){ LOG.error("Errorreadingfile:{}",getInputFile(currentTask).location(),e); } ExceptionUtil.castAndThrow(e,RuntimeException.class); returnfalse; } } @Override publicColumnarBatchnext(){ if(hasNext()){ returncurrentIterator.next(); }else{ thrownewNoSuchElementException(); } } CloseableIterator<ColumnarBatch>open(FileScanTasktask){ CloseableIterable<ColumnarBatch>iter; InputFilelocation=getInputFile(task); Preconditions.checkNotNull(location,"CouldnotfindInputFileassociatedwithFileScanTask"); if(task.file().format()==FileFormat.PARQUET){ Parquet.ReadBuilderbuilder= Parquet.read(location) .project(expectedSchema) .split(task.start(),task.length()) .createBatchedReaderFunc( fileSchema-> buildReader( expectedSchema, fileSchema,/*setArrowValidityVector*/ NullCheckingForGet.NULL_CHECKING_ENABLED)) .recordsPerBatch(batchSize) .filter(task.residual()) .caseSensitive(caseSensitive); if(reuseContainers){ builder.reuseContainers(); } if(nameMapping!=null){ builder.withNameMapping(NameMappingParser.fromJson(nameMapping)); } iter=builder.build(); }else{ thrownewUnsupportedOperationException( "Format:"+task.file().format()+"notsupportedforbatchedreads"); } returniter.iterator(); } @Override publicvoidclose()throwsIOException{ //closethecurrentiterator this.currentIterator.close(); //exhaustthetaskiterator while(fileItr.hasNext()){ fileItr.next(); } } privateInputFilegetInputFile(FileScanTasktask){ Preconditions.checkArgument(!task.isDataTask(),"Invalidtasktype"); returninputFiles.get(task.file().path().toString()); } privatestaticArrowBatchReaderbuildReader( SchemaexpectedSchema,MessageTypefileSchema,booleansetArrowValidityVector){ return(ArrowBatchReader) TypeWithSchemaVisitor.visit( expectedSchema.asStruct(), fileSchema, newVectorizedReaderBuilder( expectedSchema, fileSchema, setArrowValidityVector, ImmutableMap.of(), ArrowBatchReader::new)); } } }