This is an automated email from the ASF dual-hosted git repository.

wgtmac pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow.git


The following commit(s) were added to refs/heads/main by this push:
     new d391e17a52f GH-54921: [C++][Python][ORC] Add batch iteration over 
selected stripes (#54926)
d391e17a52f is described below

commit d391e17a52f47d03f1ad082ff243377e3e51554f
Author: Thunderkeg <[email protected]>
AuthorDate: Tue Nov 24 22:41:18 2026 +0800

    GH-54921: [C++][Python][ORC] Add batch iteration over selected stripes 
(#54926)
    
    ### Rationale for this change
    
    `ORCFile.read_stripe()` materializes an entire stripe as one record batch. 
Dataset already scans ORC in batches; this adds native batching with explicit 
stripe selection to `ORCFile`, supporting incremental consumption and early 
termination.
    
    Closes #54921.
    
    ### What changes are included in this PR?
    
    - Add `ORCFile.iter_batches(batch_size=65536, stripes=None, columns=None)` 
with column projection.
    - Add a single stateless C++ `GetStripeReader` API with explicit optional 
column selection that decodes directly into batches without changing the 
reader's Seek position.
    - Handle zero-column row counts and iterator lifetimes, bound batch 
allocation using file or stripe row counts, and add documentation and 
regression tests.
    
    ### Are these changes tested?
    
    Validated locally on macOS arm64 with matching Release C++/Python builds, 
Python 3.13.7 and ORC 2.2.1.
    
    ```bash
    cpp/build/dev/release/arrow-orc-adapter-test
    ```
    
    44 passed; one existing timezone-database test restricted to ORC < 2.0 was 
skipped.
    
    From `python/`:
    
    ```bash
    python -m pytest -q -ra --enable-orc --enable-dataset --enable-pandas 
pyarrow/tests/test_orc.py pyarrow/tests/test_dataset.py::test_orc_format 
pyarrow/tests/test_dataset.py::test_orc_scan_options 
pyarrow/tests/test_dataset.py::test_orc_writer_not_implemented_for_dataset
    ```
    
    134 passed with NumPy 2.5.4. In an isolated environment without NumPy, the 
`iter_batches` and mixed-column-selection tests had 113 passes; the marked 
NumPy integer-input test was skipped. Coverage includes five codecs, stripe 
order and duplicates, batch limits, nested/zero-column projections, invalid 
arguments, interleaved iterators and read failures. Both environments cover 
owner lifetime, early close and resource release for whole-file and 
selected-stripe iteration.
    
    The C++ memory regression uses four int64 columns and batches of 256 rows. 
For single stripes of 262144 and 1048576 rows, it checks that streaming Arrow 
allocation peaks stay below one quarter of whole-stripe peaks. A local malloc 
probe on a three-row file with a batch size of 8000000 observed no malloc calls 
of 1 MB or more for whole-file, selected-stripe and zero-column iteration. 
NONE/ZLIB range tests verify that consuming the first batch and closing early 
does not read unselected  [...]
    
    Changed-file format/lint checks and `git diff --check` passed.
    
    ### Are there any user-facing changes?
    
    Yes. The new API yields `RecordBatch` objects. `stripes=None` reads all 
stripes; explicit sequences preserve order and duplicates, and empty sequences 
yield no batches. `columns=[]` preserves row counts. Closing the iterator 
releases its reader without closing the input; returned batches remain valid.
    
    `batch_size` limits output rows, not total process memory. ORC buffers and 
dictionaries require additional memory, and small batches can reduce 
throughput. Reading the same stripes does not inherently reduce I/O.
    
    ### Was AI used for this PR?
    
    **PR code and description written by:**
    
    - [x] Human
    - [x] AI
    
    **Reviewed before submission by:**
    
    - [x] Human
    - [x] AI
    - [ ] Not reviewed
    
    The human contributor directed the design and reviewed the proposal and PR 
text. OpenAI Codex assisted with code, tests, documentation and static review.
    
    * GitHub Issue: #54921
    
    Authored-by: jiangxt2 <[email protected]>
    Signed-off-by: Gang Wu <[email protected]>
---
 cpp/src/arrow/adapters/orc/adapter.cc      |  32 ++++
 cpp/src/arrow/adapters/orc/adapter.h       |  14 ++
 cpp/src/arrow/adapters/orc/adapter_test.cc | 198 +++++++++++++++++++
 docs/source/python/orc.rst                 |  30 +++
 python/pyarrow/_orc.pxd                    |   8 +-
 python/pyarrow/_orc.pyx                    |  46 +++++
 python/pyarrow/orc.py                      |  53 ++++++
 python/pyarrow/tests/test_orc.py           | 294 +++++++++++++++++++++++++++++
 8 files changed, 674 insertions(+), 1 deletion(-)

diff --git a/cpp/src/arrow/adapters/orc/adapter.cc 
b/cpp/src/arrow/adapters/orc/adapter.cc
index 51cca497485..8ee73ececdd 100644
--- a/cpp/src/arrow/adapters/orc/adapter.cc
+++ b/cpp/src/arrow/adapters/orc/adapter.cc
@@ -156,6 +156,12 @@ class OrcStripeReader : public RecordBatchReader {
       return Status::OK();
     }
 
+    if (schema_->num_fields() == 0) {
+      *out = RecordBatch::Make(schema_, batch->numElements,
+                               std::vector<std::shared_ptr<Array>>{});
+      return Status::OK();
+    }
+
     ARROW_ASSIGN_OR_RAISE(builder,
                           RecordBatchBuilder::Make(schema_, pool_, 
batch->numElements));
     // The top-level type must be a struct to read into an arrow table
@@ -501,6 +507,26 @@ class ORCFileReader::Impl {
     return Status::OK();
   }
 
+  Result<std::shared_ptr<RecordBatchReader>> GetStripeReader(
+      int64_t stripe, int64_t batch_size,
+      const std::optional<std::vector<std::string>>& include_names) {
+    if (batch_size <= 0) {
+      return Status::Invalid("batch_size must be greater than zero");
+    }
+    auto opts = DefaultRowReaderOptions();
+    if (include_names.has_value()) {
+      RETURN_NOT_OK(SelectNames(&opts, *include_names));
+    }
+    RETURN_NOT_OK(SelectStripe(&opts, stripe));
+    batch_size = std::max<int64_t>(
+        1, std::min(batch_size, 
stripes_[static_cast<size_t>(stripe)].num_rows));
+    std::unique_ptr<liborc::RowReader> row_reader;
+    ORC_CATCH_NOT_OK(row_reader = reader_->createRowReader(opts));
+    ARROW_ASSIGN_OR_RAISE(auto schema, 
GetArrowSchema(row_reader->getSelectedType()));
+    return std::make_shared<OrcStripeReader>(std::move(row_reader), 
std::move(schema),
+                                             batch_size, pool_);
+  }
+
   Result<std::shared_ptr<RecordBatchReader>> NextStripeReader(
       int64_t batch_size, const std::vector<int>& include_indices) {
     if (current_row_ >= NumberOfRows()) {
@@ -615,6 +641,12 @@ Result<std::shared_ptr<RecordBatch>> 
ORCFileReader::ReadStripe(
 
 Status ORCFileReader::Seek(int64_t row_number) { return 
impl_->Seek(row_number); }
 
+Result<std::shared_ptr<RecordBatchReader>> ORCFileReader::GetStripeReader(
+    int64_t stripe, int64_t batch_size,
+    const std::optional<std::vector<std::string>>& include_names) {
+  return impl_->GetStripeReader(stripe, batch_size, include_names);
+}
+
 Result<std::shared_ptr<RecordBatchReader>> ORCFileReader::NextStripeReader(
     int64_t batch_size) {
   return impl_->NextStripeReader(batch_size);
diff --git a/cpp/src/arrow/adapters/orc/adapter.h 
b/cpp/src/arrow/adapters/orc/adapter.h
index 4ffff81f355..842f42add5e 100644
--- a/cpp/src/arrow/adapters/orc/adapter.h
+++ b/cpp/src/arrow/adapters/orc/adapter.h
@@ -19,6 +19,7 @@
 
 #include <cstdint>
 #include <memory>
+#include <optional>
 #include <vector>
 
 #include "arrow/adapters/orc/options.h"
@@ -135,6 +136,19 @@ class ARROW_EXPORT ORCFileReader {
   /// \param[in] row_number the rows number to seek
   Status Seek(int64_t row_number);
 
+  /// \brief Read selected fields of a designated stripe incrementally.
+  ///
+  /// This does not change the Seek position. Field order follows the file 
schema.
+  /// \param[in] stripe the stripe index
+  /// \param[in] batch_size the maximum number of rows per batch, which must 
be positive
+  /// \param[in] include_names the selected field names, including nested 
field paths.
+  /// std::nullopt reads all fields; an empty vector produces zero-column 
batches
+  /// with the stripe's row count.
+  /// \return an independent reader for the selected fields in the stripe
+  Result<std::shared_ptr<RecordBatchReader>> GetStripeReader(
+      int64_t stripe, int64_t batch_size,
+      const std::optional<std::vector<std::string>>& include_names = 
std::nullopt);
+
   /// \brief Get a stripe level record batch iterator.
   ///
   /// Each record batch will have up to `batch_size` rows.
diff --git a/cpp/src/arrow/adapters/orc/adapter_test.cc 
b/cpp/src/arrow/adapters/orc/adapter_test.cc
index a6f4686402f..72141e4895e 100644
--- a/cpp/src/arrow/adapters/orc/adapter_test.cc
+++ b/cpp/src/arrow/adapters/orc/adapter_test.cc
@@ -18,6 +18,7 @@
 #include <gmock/gmock-matchers.h>
 #include <gtest/gtest.h>
 
+#include <optional>
 #include <orc/OrcFile.hh>
 #include <string>
 
@@ -30,6 +31,8 @@
 #include "arrow/compute/cast.h"
 #include "arrow/io/interfaces.h"
 #include "arrow/io/memory.h"
+#include "arrow/io/test_common.h"
+#include "arrow/memory_pool.h"
 #include "arrow/status.h"
 #include "arrow/table.h"
 #include "arrow/testing/gtest_util.h"
@@ -43,6 +46,7 @@ namespace liborc = orc;
 
 namespace arrow {
 
+using internal::checked_cast;
 using internal::checked_pointer_cast;
 
 constexpr size_t kDefaultSmallMemStreamSize = 16384 * 5;  // 80KB
@@ -456,6 +460,200 @@ TEST(TestAdapterRead, 
ReadIntAndStringFileMultipleStripes) {
   EXPECT_EQ(num_rows / reader_batch_size, batches);
 }
 
+int64_t StripeBatchValue(int64_t row, int column) {
+  return static_cast<int64_t>(
+      (static_cast<uint64_t>(row + 1) * (0x123456789abcdefULL + column)) &
+      0x7fffffffffffffffULL);
+}
+
+std::shared_ptr<Buffer> MakeStripeBatchFile(
+    int64_t rows_per_stripe, int stripes,
+    liborc::CompressionKind compression = liborc::CompressionKind_NONE) {
+  MemoryOutputStream stream(64 * 1024 * 1024);
+  auto type = liborc::Type::buildTypeFromString(
+      "struct<col0:bigint,col1:bigint,col2:bigint,col3:bigint>");
+  liborc::WriterOptions options;
+  options.setCompression(compression);
+  options.setRowIndexStride(0);
+  options.setStripeSize(stripes == 1 ? 256 * 1024 * 1024 : 1);
+  auto writer = liborc::createWriter(*type, &stream, options);
+  auto batch = writer->createRowBatch(16384);
+  auto& root = checked_cast<liborc::StructVectorBatch&>(*batch);
+  const int64_t total = rows_per_stripe * stripes;
+  for (int64_t offset = 0; offset < total; offset += 16384) {
+    root.numElements = std::min<int64_t>(16384, total - offset);
+    for (int col = 0; col < 4; ++col) {
+      auto& values = checked_cast<liborc::LongVectorBatch&>(*root.fields[col]);
+      values.numElements = root.numElements;
+      for (uint64_t row = 0; row < root.numElements; ++row) {
+        values.data[row] = StripeBatchValue(offset + row, col);
+      }
+    }
+    writer->add(root);
+  }
+  writer->close();
+  return Buffer::FromString(std::string(stream.getData(), stream.getLength()));
+}
+
+TEST(TestAdapterRead, StripeBatchSelectionAndState) {
+  auto file = std::make_shared<io::BufferReader>(MakeStripeBatchFile(16384, 
4));
+  ASSERT_OK_AND_ASSIGN(auto reader,
+                       adapters::orc::ORCFileReader::Open(file, 
default_memory_pool()));
+  ASSERT_EQ(4, reader->NumberOfStripes());
+  ASSERT_OK(reader->Seek(16384 + 7));
+  ASSERT_OK_AND_ASSIGN(auto first, reader->GetStripeReader(2, 1000, 
std::nullopt));
+  ASSERT_OK_AND_ASSIGN(auto second, reader->GetStripeReader(0, 1));
+  std::shared_ptr<RecordBatch> batch;
+  ASSERT_OK(second->ReadNext(&batch));
+  ASSERT_EQ(StripeBatchValue(0, 0),
+            checked_cast<const Int64Array&>(*batch->column(0)).Value(0));
+  ASSERT_OK_AND_ASSIGN(auto ignored, reader->ReadStripe(3));
+  int64_t rows = 0;
+  while (true) {
+    ASSERT_OK(first->ReadNext(&batch));
+    if (!batch) break;
+    ASSERT_OK(batch->ValidateFull());
+    ASSERT_LE(batch->num_rows(), 1000);
+    for (int64_t row = 0; row < batch->num_rows(); ++row) {
+      ASSERT_EQ(StripeBatchValue(2 * 16384 + rows + row, 0),
+                checked_cast<const Int64Array&>(*batch->column(0)).Value(row));
+    }
+    rows += batch->num_rows();
+  }
+  ASSERT_EQ(16384, rows);
+  ASSERT_OK_AND_ASSIGN(auto cursor_reader, reader->NextStripeReader(3));
+  ASSERT_OK(cursor_reader->ReadNext(&batch));
+  ASSERT_EQ(StripeBatchValue(16384 + 7, 0),
+            checked_cast<const Int64Array&>(*batch->column(0)).Value(0));
+  reader.reset();
+  ASSERT_OK(second->ReadNext(&batch));
+  ASSERT_EQ(StripeBatchValue(1, 0),
+            checked_cast<const Int64Array&>(*batch->column(0)).Value(0));
+}
+
+TEST(TestAdapterRead, StripeBatchProjectionAndArguments) {
+  auto file = std::make_shared<io::BufferReader>(MakeStripeBatchFile(16384, 
3));
+  ASSERT_OK_AND_ASSIGN(auto reader,
+                       adapters::orc::ORCFileReader::Open(file, 
default_memory_pool()));
+  ASSERT_RAISES(Invalid, reader->GetStripeReader(-1, 10));
+  ASSERT_RAISES(Invalid, reader->GetStripeReader(3, 10));
+  ASSERT_RAISES(Invalid, reader->GetStripeReader(0, 0));
+  ASSERT_RAISES(Invalid, reader->GetStripeReader(0, -1));
+  ASSERT_RAISES(IOError,
+                reader->GetStripeReader(0, 10, 
std::vector<std::string>{"missing"}));
+  ASSERT_OK_AND_ASSIGN(auto projected,
+                       reader->GetStripeReader(
+                           1, 10000, std::vector<std::string>{"col2", "col0", 
"col0"}));
+  ASSERT_EQ(projected->schema()->field_names(),
+            (std::vector<std::string>{"col0", "col2"}));
+  std::shared_ptr<RecordBatch> batch;
+  ASSERT_OK(projected->ReadNext(&batch));
+  ASSERT_EQ(10000, batch->num_rows());
+  ASSERT_EQ(StripeBatchValue(16384, 2),
+            checked_cast<const Int64Array&>(*batch->column(1)).Value(0));
+  ASSERT_OK_AND_ASSIGN(auto large_batch, reader->GetStripeReader(0, 65536));
+  ASSERT_OK(large_batch->ReadNext(&batch));
+  ASSERT_EQ(16384, batch->num_rows());
+  ASSERT_EQ(StripeBatchValue(0, 0),
+            checked_cast<const Int64Array&>(*batch->column(0)).Value(0));
+  ASSERT_OK(large_batch->ReadNext(&batch));
+  ASSERT_EQ(nullptr, batch);
+  ASSERT_OK_AND_ASSIGN(auto zero,
+                       reader->GetStripeReader(2, 1000, 
std::vector<std::string>{}));
+  int64_t rows = 0;
+  while (true) {
+    ASSERT_OK(zero->ReadNext(&batch));
+    if (!batch) break;
+    ASSERT_OK(batch->ValidateFull());
+    ASSERT_EQ(0, batch->num_columns());
+    ASSERT_GT(batch->num_rows(), 0);
+    ASSERT_LE(batch->num_rows(), 1000);
+    rows += batch->num_rows();
+  }
+  ASSERT_EQ(16384, rows);
+  ProxyMemoryPool zero_pool(default_memory_pool());
+  ASSERT_OK_AND_ASSIGN(auto zero_reader,
+                       adapters::orc::ORCFileReader::Open(file, &zero_pool));
+  ASSERT_OK_AND_ASSIGN(auto zero_batches,
+                       zero_reader->GetStripeReader(0, 1000, 
std::vector<std::string>{}));
+  ASSERT_OK(zero_batches->ReadNext(&batch));
+  ASSERT_EQ(1000, batch->num_rows());
+  ASSERT_EQ(0, zero_pool.max_memory());  // No full-column decode followed by 
projection.
+}
+
+TEST(TestAdapterRead, StripeBatchReadsOnlySelectedRange) {
+  for (auto codec : {liborc::CompressionKind_NONE, 
liborc::CompressionKind_ZLIB}) {
+    auto file = std::make_shared<io::BufferReader>(MakeStripeBatchFile(16384, 
4, codec));
+    std::shared_ptr<io::TrackedRandomAccessFile> tracked =
+        io::TrackedRandomAccessFile::Make(file.get());
+    ASSERT_OK_AND_ASSIGN(
+        auto reader, adapters::orc::ORCFileReader::Open(tracked, 
default_memory_pool()));
+    ASSERT_EQ(4, reader->NumberOfStripes());
+    for (int stripe : {2, 0}) {
+      tracked->ResetStats();
+      ASSERT_OK_AND_ASSIGN(auto batches, reader->GetStripeReader(stripe, 17));
+      std::shared_ptr<RecordBatch> batch;
+      ASSERT_OK(batches->ReadNext(&batch));
+      ASSERT_EQ(17, batch->num_rows());
+      ASSERT_GT(tracked->bytes_read(), 0);
+      auto reads = tracked->num_reads();
+      batches.reset();  // Early stop must not read the rest or another stripe.
+      ASSERT_EQ(reads, tracked->num_reads());
+      for (const auto& range : tracked->get_read_ranges()) {
+        for (int other = 0; other < reader->NumberOfStripes(); ++other) {
+          if (other == stripe) continue;
+          auto unselected = reader->GetStripeInformation(other);
+          ASSERT_TRUE(range.offset + range.length <= unselected.offset ||
+                      range.offset >= unselected.offset + unselected.length);
+        }
+      }
+    }
+  }
+}
+
+TEST(TestAdapterRead, StripeBatchMemoryBounded) {
+  constexpr int64_t batch_size = 256;
+  int64_t small_peak = 0;
+  for (int64_t rows : {262144, 1048576}) {
+    auto buffer = MakeStripeBatchFile(rows, 1);
+    int64_t full_peak;
+    {
+      ProxyMemoryPool pool(default_memory_pool());
+      auto file = std::make_shared<io::BufferReader>(buffer);
+      ASSERT_OK_AND_ASSIGN(auto reader, 
adapters::orc::ORCFileReader::Open(file, &pool));
+      ASSERT_EQ(1, reader->NumberOfStripes());
+      ASSERT_EQ(rows, reader->GetStripeInformation(0).num_rows);
+      ASSERT_OK_AND_ASSIGN(auto batch, reader->ReadStripe(0));
+      ASSERT_EQ(rows, batch->num_rows());
+      full_peak = pool.max_memory();
+    }
+    ProxyMemoryPool pool(default_memory_pool());
+    auto file = std::make_shared<io::BufferReader>(buffer);
+    ASSERT_OK_AND_ASSIGN(auto reader, adapters::orc::ORCFileReader::Open(file, 
&pool));
+    ASSERT_EQ(0, pool.bytes_allocated());
+    ASSERT_OK_AND_ASSIGN(auto batches, reader->GetStripeReader(0, batch_size));
+    ASSERT_EQ(0, pool.bytes_allocated());  // No whole-stripe Arrow allocation.
+    int64_t count = 0;
+    int64_t first_peak = 0;
+    while (true) {
+      std::shared_ptr<RecordBatch> batch;
+      ASSERT_OK(batches->ReadNext(&batch));
+      if (!batch) break;
+      ASSERT_LE(batch->num_rows(), batch_size);
+      if (count == 0) first_peak = pool.max_memory();
+      ASSERT_EQ(StripeBatchValue(count, 0),
+                checked_cast<const Int64Array&>(*batch->column(0)).Value(0));
+      count += batch->num_rows();
+    }
+    ASSERT_EQ(rows, count);
+    ASSERT_EQ(0, pool.bytes_allocated());
+    ASSERT_LT(first_peak, full_peak / 4);
+    ASSERT_LT(pool.max_memory(), full_peak / 4);
+    if (small_peak == 0) small_peak = pool.max_memory();
+    ASSERT_LE(pool.max_memory(), 2 * small_peak);
+  }
+}
+
 TEST(TestAdapterRead, ReadCharAndVarcharType) {
   MemoryOutputStream mem_stream(kDefaultMemStreamSize);
   auto orc_type = 
liborc::Type::buildTypeFromString("struct<c1:char(6),c2:varchar(6)>");
diff --git a/docs/source/python/orc.rst b/docs/source/python/orc.rst
index 8f3ae75e101..cd7c6d38155 100644
--- a/docs/source/python/orc.rst
+++ b/docs/source/python/orc.rst
@@ -167,6 +167,36 @@ concatenate them into a single table. You can read 
individual stripes with
    two: ["foo","bar","baz"]
    three: [true,false,true]
 
+To consume a file in batches without first materializing an entire stripe as
+Arrow data, use :meth:`~pyarrow.orc.ORCFile.iter_batches`:
+
+.. code-block:: python
+
+   >>> batches = orc_file.iter_batches(batch_size=2, stripes=[0], 
columns=['one'])
+   >>> [batch.num_rows for batch in batches]
+   [2, 1]
+
+Omitting ``stripes`` reads the entire file in physical order. An explicit
+sequence reads stripes in the supplied order, including repetitions; an empty
+sequence reads nothing. Column selection uses the same syntax as 
``read_stripe``:
+column names (including nested paths) or top-level integer indices. Mixing 
names and
+indices is not supported. ``columns=[]`` returns zero-column batches with the
+correct row counts.
+
+Reading begins when the iterator is consumed. When stopping early, call
+``close()`` to release its reader:
+
+.. code-block:: python
+
+   >>> batches = orc_file.iter_batches(batch_size=2)
+   >>> try:
+   ...     first_batch = next(batches)
+   ... finally:
+   ...     batches.close()
+
+Closing the iterator does not close a file object supplied by the caller.
+``batch_size`` bounds the number of output rows, not total process memory.
+
 We can write an ORC file using ``ORCWriter``:
 
 .. code-block:: python
diff --git a/python/pyarrow/_orc.pxd b/python/pyarrow/_orc.pxd
index aecbba317ae..582463ea0f7 100644
--- a/python/pyarrow/_orc.pxd
+++ b/python/pyarrow/_orc.pxd
@@ -25,7 +25,7 @@ from pyarrow.includes.common cimport *
 from pyarrow.includes.libarrow cimport (CArray, CSchema, CStatus,
                                         CResult, CTable, CMemoryPool,
                                         CKeyValueMetadata,
-                                        CRecordBatch,
+                                        CRecordBatch, CRecordBatchReader,
                                         CTable, CCompressionType,
                                         CRandomAccessFile, COutputStream,
                                         TimeUnit)
@@ -103,6 +103,12 @@ cdef extern from "arrow/adapters/orc/adapter.h" \
         CResult[shared_ptr[CRecordBatch]] ReadStripe(
             int64_t stripe, std_vector[c_string])
 
+        CResult[shared_ptr[CRecordBatchReader]] GetStripeReader(
+            int64_t stripe, int64_t batch_size,
+            const optional[std_vector[c_string]]&)
+        CResult[shared_ptr[CRecordBatchReader]] GetRecordBatchReader(
+            int64_t batch_size, const std_vector[c_string]&)
+
         CResult[shared_ptr[CTable]] Read()
         CResult[shared_ptr[CTable]] Read(std_vector[c_string])
 
diff --git a/python/pyarrow/_orc.pyx b/python/pyarrow/_orc.pyx
index 1dd6848122c..f5579a63dba 100644
--- a/python/pyarrow/_orc.pyx
+++ b/python/pyarrow/_orc.pyx
@@ -364,6 +364,52 @@ cdef class ORCReader(_Weakrefable):
 
         return pyarrow_wrap_batch(sp_record_batch)
 
+    def iter_batches(self, int64_t batch_size, stripes=None, columns=None):
+        cdef:
+            shared_ptr[CRecordBatchReader] batch_reader
+            shared_ptr[CRecordBatch] batch
+            std_vector[c_string] names
+            optional[std_vector[c_string]] selected_names
+            int64_t stripe
+
+        if columns is not None:
+            names = [tobytes(name) for name in columns]
+            selected_names = optional[std_vector[c_string]](names)
+
+        # None selects a whole-file reader. Zero-column projection needs
+        # individual stripe readers to preserve row counts.
+        if stripes is None and (columns is None or len(columns) != 0):
+            stripe_indices = [None]
+        elif stripes is None:
+            stripe_indices = range(self.nstripes())
+        else:
+            stripe_indices = stripes
+
+        try:
+            for index in stripe_indices:
+                if index is None:
+                    batch_size = max(1, min(batch_size, self.nrows()))
+                    with nogil:
+                        batch_reader = GetResultValue(
+                            self.reader.get().GetRecordBatchReader(batch_size, 
names))
+                else:
+                    stripe = index
+                    with nogil:
+                        batch_reader = GetResultValue(
+                            self.reader.get().GetStripeReader(
+                                stripe, batch_size, selected_names))
+                while True:
+                    with nogil:
+                        check_status(batch_reader.get().ReadNext(&batch))
+                    if batch.get() == NULL:
+                        break
+                    yield pyarrow_wrap_batch(batch)
+                    batch.reset()
+                batch_reader.reset()
+        finally:
+            batch.reset()
+            batch_reader.reset()
+
     def read(self, columns=None):
         cdef:
             shared_ptr[CTable] sp_table
diff --git a/python/pyarrow/orc.py b/python/pyarrow/orc.py
index aad47432cf0..91be5218f54 100644
--- a/python/pyarrow/orc.py
+++ b/python/pyarrow/orc.py
@@ -17,6 +17,7 @@
 
 
 from numbers import Integral
+import operator
 
 import pyarrow._orc as _orc
 from pyarrow.fs import _resolve_filesystem_and_path
@@ -129,6 +130,11 @@ class ORCFile:
         if columns is None:
             return None
 
+        columns = list(columns)
+        if any(isinstance(col, Integral) for col in columns) and any(
+                not isinstance(col, Integral) for col in columns):
+            raise TypeError("columns cannot mix names and integer indices")
+
         schema = self.schema
         names = []
         for col in columns:
@@ -165,6 +171,53 @@ class ORCFile:
         columns = self._select_names(columns)
         return self.reader.read_stripe(n, columns=columns)
 
+    def iter_batches(self, batch_size=65536, stripes=None, columns=None):
+        """Read streaming batches from the file or selected stripes.
+
+        Parameters
+        ----------
+        batch_size : int, default 65536
+            Maximum number of rows per batch. Must be positive.
+        stripes : sequence of int, optional
+            Zero-based stripe indices, read in the supplied order. Repeated
+            indices repeat the corresponding rows. None reads the entire file;
+            an empty sequence produces no batches.
+        columns : list, optional
+            Column names, nested field paths, or top-level integer indices,
+            using the same selection syntax as read_stripe. Names and integer
+            indices cannot be mixed.
+            Output follows the file's column order. None
+            reads all columns; an empty list reads no columns but preserves
+            the number of rows.
+
+        Yields
+        ------
+        pyarrow.RecordBatch
+            A batch containing at most batch_size rows. Stripe boundaries may
+            produce smaller batches.
+
+        Notes
+        -----
+        Reading starts when the iterator is consumed. Call its close() method
+        to release the reader when stopping early. This does not close a source
+        supplied by the caller. Returned batches remain valid after closing.
+
+        Batches are decoded incrementally, without first constructing an Arrow
+        batch for the entire stripe. batch_size limits rows, not bytes or total
+        process memory: ORC dictionaries and decompression buffers may still
+        depend on the stripe size.
+        """
+        batch_size = operator.index(batch_size)
+        if batch_size <= 0:
+            raise ValueError("batch_size must be greater than zero")
+        if stripes is not None:
+            stripes = tuple(operator.index(stripe) for stripe in stripes)
+            for stripe in stripes:
+                if not 0 <= stripe < self.nstripes:
+                    raise ValueError(f"Out of bounds stripe: {stripe}")
+        columns = self._select_names(columns)
+        return self.reader.iter_batches(batch_size, stripes, columns)
+
     def read(self, columns=None):
         """Read the whole file.
 
diff --git a/python/pyarrow/tests/test_orc.py b/python/pyarrow/tests/test_orc.py
index b5b38006e5a..8542c63b1ab 100644
--- a/python/pyarrow/tests/test_orc.py
+++ b/python/pyarrow/tests/test_orc.py
@@ -17,10 +17,14 @@
 
 import decimal
 import datetime
+import gc
+import io
 from pathlib import Path
+import random
 import shutil
 import subprocess
 import sys
+import weakref
 
 import pytest
 
@@ -126,6 +130,14 @@ def check_example_file(orc_path, expected_df, 
need_fix=False):
         json_pos += len(batch)
     assert json_pos == orc_file.nrows
 
+    # Exercise both the full-file and selected-stripe native batch paths on
+    # examples covering the existing reader's supported ORC types.
+    for stripes in (None, list(range(orc_file.nstripes))):
+        batches = list(orc_file.iter_batches(batch_size=127, stripes=stripes))
+        assert all(0 < batch.num_rows <= 127 for batch in batches)
+        actual = pa.Table.from_batches(batches, schema=table.schema)
+        assert actual.equals(table)
+
 
 @pytest.mark.pandas
 @pytest.mark.parametrize('filename', [
@@ -666,3 +678,285 @@ def test_orc_writer_with_null_arrays(tempdir):
     table = pa.table({"int64": a, "utf8": b})
     with pytest.raises(pa.ArrowNotImplementedError):
         orc.write_table(table, path)
+
+
[email protected](scope="module", params=[
+    'uncompressed', 'zlib', 'snappy', 'lz4', 'zstd'])
+def batch_file(request):
+    from pyarrow import orc
+
+    rows = 4 * 16384
+    rng = random.Random(42)
+    values = [rng.getrandbits(62) for _ in range(rows)]
+    table = pa.table({'value': values,
+                      'other': [value // 3 for value in values]})
+    sink = pa.BufferOutputStream()
+    orc.write_table(table, sink, stripe_size=1, batch_size=16384,
+                    compression=request.param)
+    data = sink.getvalue()
+    reader = orc.ORCFile(data)
+    assert reader.nstripes == 4
+    assert all(reader.read_stripe(i).num_rows == 16384 for i in range(4))
+    return data, table
+
+
[email protected]('batch_size', [1000, 16384, 65536])
[email protected]('stripes', [None, [2, 0, 2]])
+def test_iter_batches_selection(batch_file, batch_size, stripes):
+    from pyarrow import orc
+
+    data, table = batch_file
+    reader = orc.ORCFile(data)
+    batches = list(reader.iter_batches(batch_size, stripes=stripes))
+    assert all(0 < batch.num_rows <= batch_size for batch in batches)
+    if stripes is None:
+        expected = table
+    else:
+        expected = pa.Table.from_batches(
+            [reader.read_stripe(i) for i in stripes], schema=table.schema)
+    actual = pa.Table.from_batches(batches, schema=table.schema)
+    assert actual.equals(expected)
+    for batch in batches:
+        batch.validate(full=True)
+
+
[email protected]('stripes', [None, [2, 0]])
[email protected]('columns', [[], [1], ['other', 'value'],
+                                     ['other', 'other']])
+def test_iter_batches_projection(batch_file, stripes, columns):
+    from pyarrow import orc
+
+    data, _ = batch_file
+    reader = orc.ORCFile(data)
+    batches = list(reader.iter_batches(1000, stripes, columns))
+    expected_rows = reader.nrows if stripes is None else 2 * 16384
+    assert sum(batch.num_rows for batch in batches) == expected_rows
+    assert all(0 < batch.num_rows <= 1000 for batch in batches)
+    names = reader._select_names(columns)
+    if columns == []:
+        assert all(batch.num_columns == 0 for batch in batches)
+    else:
+        expected = pa.Table.from_batches([
+            reader.read_stripe(i, columns=names)
+            for i in (range(reader.nstripes) if stripes is None else stripes)])
+        assert pa.Table.from_batches(batches).equals(expected)
+
+
+def test_iter_batches_nested_and_nulls():
+    from pyarrow import orc
+
+    table = pa.table({
+        'struct': [{'middle': {'inner': 1}, 'other': 2}, None,
+                   {'middle': {'inner': None}, 'other': 4}],
+        'list-struct': [[{'inner1': 1, 'inner2': 2}], None, []],
+        'map': pa.array([[('a', 1)], None, []], pa.map_(pa.string(), 
pa.int32())),
+        'text': ['hello', None, 'world'],
+        'binary': [b'abc', None, b'def'],
+    })
+    sink = pa.BufferOutputStream()
+    orc.write_table(table, sink)
+    reader = orc.ORCFile(sink.getvalue())
+    for columns in (None, ['struct.middle.inner'], ['list-struct.inner1'],
+                    ['map'], [0, 2]):
+        expected = reader.read(columns=columns)
+        for stripes in (None, [0]):
+            batches = list(reader.iter_batches(1, stripes, columns))
+            assert [batch.num_rows for batch in batches] == [1, 1, 1]
+            assert pa.Table.from_batches(batches).equals(expected)
+    assert sum(b.num_rows for b in reader.iter_batches()) == 3
+
+
[email protected]('batch_file', ['uncompressed'], indirect=True)
[email protected]('batch_size,error', [
+    (0, ValueError), (-1, ValueError), (1.5, TypeError), ('2', TypeError),
+    (None, TypeError), (2**63, OverflowError), (-2**63 - 1, ValueError)])
+def test_iter_batches_invalid_batch_size(batch_file, batch_size, error):
+    from pyarrow import orc
+
+    reader = orc.ORCFile(batch_file[0])
+    with pytest.raises(error):
+        reader.iter_batches(batch_size)
+
+
[email protected]('batch_file', ['uncompressed'], indirect=True)
[email protected]('stripes,error', [
+    ([-1], ValueError), ([4], ValueError), ([0, 4], ValueError),
+    ([1.2], TypeError), (['0'], TypeError), ([None], TypeError),
+    ([2**63], ValueError), ([-2**63 - 1], ValueError)])
+def test_iter_batches_invalid_stripes(batch_file, stripes, error):
+    from pyarrow import orc
+
+    source = BatchTrackingFile(batch_file[0].to_pybytes())
+    reader = orc.ORCFile(source)
+    source.reads.clear()
+    with pytest.raises(error):
+        reader.iter_batches(stripes=stripes)
+    assert source.reads == []
+
+
[email protected]('batch_file', ['uncompressed'], indirect=True)
[email protected]('method', ['read', 'read_stripe', 'iter_batches'])
[email protected]('columns', [[0, 'other'], ['value', 1]])
+def test_mixed_column_selection(batch_file, method, columns):
+    from pyarrow import orc
+
+    reader = orc.ORCFile(batch_file[0])
+    read = getattr(reader, method)
+    args = (0,) if method == 'read_stripe' else ()
+    with pytest.raises(TypeError, match='cannot mix names and integer 
indices'):
+        read(*args, columns=columns)
+
+
+def test_iter_batches_snapshot_and_state(batch_file):
+    from pyarrow import orc
+
+    reader = orc.ORCFile(batch_file[0])
+    stripes = [2, 0]
+    columns = ['value']
+    first = reader.iter_batches(1000, stripes, columns)
+    stripes[:] = [1]
+    columns[:] = ['other']
+    second = reader.iter_batches(7, [1])
+    retained = next(first)
+    assert retained.equals(reader.read_stripe(2, ['value']).slice(0, 1000))
+    assert next(second).equals(reader.read_stripe(1).slice(0, 7))
+    reader.read()
+    assert next(first).equals(reader.read_stripe(2, ['value']).slice(1000, 
1000))
+    first.close()
+    second.close()
+    assert retained.equals(reader.read_stripe(2, ['value']).slice(0, 1000))
+    with pytest.raises(ValueError):
+        reader.iter_batches(columns=[2])
+    with pytest.raises(IOError):
+        next(reader.iter_batches(columns=['missing']))
+    assert list(reader.iter_batches(stripes=[], columns=['missing'])) == []
+
+
[email protected]
+def test_iter_batches_numpy_integer_arguments():
+    from pyarrow import orc
+    import numpy as np
+
+    table = pa.table({'value': [0, 1, 2, 3]})
+    sink = pa.BufferOutputStream()
+    orc.write_table(table, sink)
+    reader = orc.ORCFile(sink.getvalue())
+    batches = list(reader.iter_batches(np.int64(2), [np.int64(0)]))
+    assert [batch.num_rows for batch in batches] == [2, 2]
+    assert pa.Table.from_batches(batches).equals(table)
+
+
+class BatchTrackingFile(io.BytesIO):
+    def __init__(self, data):
+        super().__init__(data)
+        self.reads = []
+        self.fail = False
+
+    def read(self, size=-1):
+        if self.fail:
+            raise OSError('injected ORC read failure')
+        offset = self.tell()
+        data = super().read(size)
+        self.reads.append((offset, len(data)))
+        return data
+
+    def readinto(self, buffer):
+        data = self.read(len(buffer))
+        buffer[:len(data)] = data
+        return len(data)
+
+
[email protected]('stripes', [None, [2, 0]], ids=['all', 'selected'])
+def test_iter_batches_lazy_close_and_owner(batch_file, monkeypatch, stripes):
+    from pyarrow import orc
+
+    source = BatchTrackingFile(batch_file[0].to_pybytes())
+    file = orc.ORCFile(source)
+    source.reads.clear()
+    reader_ref = weakref.ref(file.reader)
+    source_ref = weakref.ref(source)
+
+    unstarted = file.iter_batches(32, stripes)
+    unstarted.close()
+    assert list(unstarted) == []
+    assert source.reads == []
+    assert not source.closed
+    del unstarted
+
+    def fail_whole_stripe(*args, **kwargs):
+        pytest.fail('iter_batches must not call read_stripe')
+
+    monkeypatch.setattr(orc.ORCFile, 'read_stripe', fail_whole_stripe)
+    iterator = file.iter_batches(32, stripes)
+    assert source.reads == []
+    del file
+    gc.collect()
+    assert reader_ref() is not None
+    retained = next(iterator)
+    start = 0 if stripes is None else stripes[0] * 16384
+    expected = batch_file[1].slice(start, 32)
+    assert pa.Table.from_batches([retained]).equals(expected)
+    assert source.reads
+    reads = list(source.reads)
+    iterator.close()
+    assert source.reads == reads
+    assert not source.closed
+    assert list(iterator) == []
+    del iterator, source
+    gc.collect()
+    assert reader_ref() is None
+    assert source_ref() is None
+    assert pa.Table.from_batches([retained]).equals(expected)
+
+
+def test_iter_batches_errors_after_output(batch_file):
+    from pyarrow import orc
+
+    source = BatchTrackingFile(batch_file[0].to_pybytes())
+    reader = orc.ORCFile(source)
+    iterator = reader.iter_batches(16384, [0, 2])
+    first = next(iterator)
+    assert first.num_rows == 16384
+    source.fail = True
+    with pytest.raises((OSError, pa.ArrowException), match='injected ORC read 
failure'):
+        next(iterator)
+    assert list(iterator) == []
+    assert pa.Table.from_batches([first]).equals(batch_file[1].slice(0, 16384))
+    source.fail = False
+    iterator = reader.iter_batches(16384, [0, 2])
+    assert next(iterator).num_rows == 16384
+    source.close()
+    with pytest.raises((OSError, pa.ArrowException)):
+        next(iterator)
+
+
+def test_iter_batches_sources_and_empty(tmp_path, datadir):
+    from pyarrow import orc
+
+    path = tmp_path / 'batches.orc'
+    table = pa.table({'a': [1, None, 3]})
+    orc.write_table(table, path)
+    with path.open('rb') as file, pa.OSFile(str(path)) as native:
+        for source in (path, str(path), file, native,
+                       pa.BufferReader(path.read_bytes())):
+            batches = list(orc.ORCFile(source).iter_batches(2, [0]))
+            assert pa.Table.from_batches(batches).equals(table)
+    reader = orc.ORCFile(path)
+    for stripes in (None, [0]):
+        batches = list(reader.iter_batches(65536, stripes))
+        assert [batch.num_rows for batch in batches] == [3]
+        assert pa.Table.from_batches(batches).equals(table)
+        empty_columns = list(reader.iter_batches(65536, stripes, []))
+        assert [batch.num_rows for batch in empty_columns] == [3]
+        assert empty_columns[0].num_columns == 0
+    empty = orc.ORCFile(datadir / 'TestOrcFile.emptyFile.orc')
+    assert list(empty.iter_batches()) == []
+    assert list(empty.iter_batches(columns=[])) == []
+    assert list(empty.iter_batches(stripes=[])) == []
+    with pytest.raises(IOError):
+        next(empty.iter_batches(columns=['missing']))
+    assert list(empty.iter_batches(stripes=[], columns=['missing'])) == []
+    with pytest.raises(ValueError):
+        empty.iter_batches(stripes=[0])
+    with pytest.raises((OSError, pa.ArrowException)):
+        orc.ORCFile(pa.BufferReader(b'ORC broken file')).iter_batches()

Reply via email to