forked from apache/arrow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathipc.pxi
More file actions
1255 lines (998 loc) · 35.5 KB
/
Copy pathipc.pxi
File metadata and controls
1255 lines (998 loc) · 35.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# 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.
from collections import namedtuple
import warnings
cpdef enum MetadataVersion:
V1 = <char> CMetadataVersion_V1
V2 = <char> CMetadataVersion_V2
V3 = <char> CMetadataVersion_V3
V4 = <char> CMetadataVersion_V4
V5 = <char> CMetadataVersion_V5
cdef object _wrap_metadata_version(CMetadataVersion version):
return MetadataVersion(<char> version)
cdef CMetadataVersion _unwrap_metadata_version(
MetadataVersion version) except *:
if version == MetadataVersion.V1:
return CMetadataVersion_V1
elif version == MetadataVersion.V2:
return CMetadataVersion_V2
elif version == MetadataVersion.V3:
return CMetadataVersion_V3
elif version == MetadataVersion.V4:
return CMetadataVersion_V4
elif version == MetadataVersion.V5:
return CMetadataVersion_V5
raise ValueError("Not a metadata version: " + repr(version))
_WriteStats = namedtuple(
'WriteStats',
('num_messages', 'num_record_batches', 'num_dictionary_batches',
'num_dictionary_deltas', 'num_replaced_dictionaries'))
class WriteStats(_WriteStats):
"""IPC write statistics
Parameters
----------
num_messages : int
Number of messages.
num_record_batches : int
Number of record batches.
num_dictionary_batches : int
Number of dictionary batches.
num_dictionary_deltas : int
Delta of dictionaries.
num_replaced_dictionaries : int
Number of replaced dictionaries.
"""
__slots__ = ()
@staticmethod
cdef _wrap_write_stats(CIpcWriteStats c):
return WriteStats(c.num_messages, c.num_record_batches,
c.num_dictionary_batches, c.num_dictionary_deltas,
c.num_replaced_dictionaries)
_ReadStats = namedtuple(
'ReadStats',
('num_messages', 'num_record_batches', 'num_dictionary_batches',
'num_dictionary_deltas', 'num_replaced_dictionaries'))
class ReadStats(_ReadStats):
"""IPC read statistics
Parameters
----------
num_messages : int
Number of messages.
num_record_batches : int
Number of record batches.
num_dictionary_batches : int
Number of dictionary batches.
num_dictionary_deltas : int
Delta of dictionaries.
num_replaced_dictionaries : int
Number of replaced dictionaries.
"""
__slots__ = ()
@staticmethod
cdef _wrap_read_stats(CIpcReadStats c):
return ReadStats(c.num_messages, c.num_record_batches,
c.num_dictionary_batches, c.num_dictionary_deltas,
c.num_replaced_dictionaries)
cdef class IpcReadOptions(_Weakrefable):
"""
Serialization options for reading IPC format.
Parameters
----------
ensure_native_endian : bool, default True
Whether to convert incoming data to platform-native endianness.
use_threads : bool
Whether to use the global CPU thread pool to parallelize any
computational tasks like decompression
included_fields : list
If empty (the default), return all deserialized fields.
If non-empty, the values are the indices of fields to read on
the top-level schema
"""
__slots__ = ()
# cdef block is in lib.pxd
def __init__(self, *, bint ensure_native_endian=True,
bint use_threads=True, list included_fields=None):
self.c_options = CIpcReadOptions.Defaults()
self.ensure_native_endian = ensure_native_endian
self.use_threads = use_threads
if included_fields is not None:
self.included_fields = included_fields
@property
def ensure_native_endian(self):
return self.c_options.ensure_native_endian
@ensure_native_endian.setter
def ensure_native_endian(self, bint value):
self.c_options.ensure_native_endian = value
@property
def use_threads(self):
return self.c_options.use_threads
@use_threads.setter
def use_threads(self, bint value):
self.c_options.use_threads = value
@property
def included_fields(self):
return self.c_options.included_fields
@included_fields.setter
def included_fields(self, list value not None):
self.c_options.included_fields = value
cdef class IpcWriteOptions(_Weakrefable):
"""
Serialization options for the IPC format.
Parameters
----------
metadata_version : MetadataVersion, default MetadataVersion.V5
The metadata version to write. V5 is the current and latest,
V4 is the pre-1.0 metadata version (with incompatible Union layout).
allow_64bit : bool, default False
If true, allow field lengths that don't fit in a signed 32-bit int.
use_legacy_format : bool, default False
Whether to use the pre-Arrow 0.15 IPC format.
compression : str, Codec, or None
compression codec to use for record batch buffers.
If None then batch buffers will be uncompressed.
Must be "lz4", "zstd" or None.
To specify a compression_level use `pyarrow.Codec`
use_threads : bool
Whether to use the global CPU thread pool to parallelize any
computational tasks like compression.
emit_dictionary_deltas : bool
Whether to emit dictionary deltas. Default is false for maximum
stream compatibility.
unify_dictionaries : bool
If true then calls to write_table will attempt to unify dictionaries
across all batches in the table. This can help avoid the need for
replacement dictionaries (which the file format does not support)
but requires computing the unified dictionary and then remapping
the indices arrays.
This parameter is ignored when writing to the IPC stream format as
the IPC stream format can support replacement dictionaries.
"""
__slots__ = ()
# cdef block is in lib.pxd
def __init__(self, *, metadata_version=MetadataVersion.V5,
bint allow_64bit=False, use_legacy_format=False,
compression=None, bint use_threads=True,
bint emit_dictionary_deltas=False,
bint unify_dictionaries=False):
self.c_options = CIpcWriteOptions.Defaults()
self.allow_64bit = allow_64bit
self.use_legacy_format = use_legacy_format
self.metadata_version = metadata_version
if compression is not None:
self.compression = compression
self.use_threads = use_threads
self.emit_dictionary_deltas = emit_dictionary_deltas
self.unify_dictionaries = unify_dictionaries
@property
def allow_64bit(self):
return self.c_options.allow_64bit
@allow_64bit.setter
def allow_64bit(self, bint value):
self.c_options.allow_64bit = value
@property
def use_legacy_format(self):
return self.c_options.write_legacy_ipc_format
@use_legacy_format.setter
def use_legacy_format(self, bint value):
self.c_options.write_legacy_ipc_format = value
@property
def metadata_version(self):
return _wrap_metadata_version(self.c_options.metadata_version)
@metadata_version.setter
def metadata_version(self, value):
self.c_options.metadata_version = _unwrap_metadata_version(value)
@property
def compression(self):
if self.c_options.codec == nullptr:
return None
else:
return frombytes(self.c_options.codec.get().name())
@compression.setter
def compression(self, value):
if value is None:
self.c_options.codec.reset()
elif isinstance(value, str):
codec_type = _ensure_compression(value)
if codec_type != CCompressionType_ZSTD and codec_type != CCompressionType_LZ4_FRAME:
raise ValueError("Compression type must be lz4, zstd or None")
self.c_options.codec = shared_ptr[CCodec](GetResultValue(
CCodec.Create(codec_type)).release())
elif isinstance(value, Codec):
if value.name != "lz4" and value.name != "zstd":
raise ValueError("Compression type must be lz4, zstd or None")
self.c_options.codec = (<Codec>value).wrapped
else:
raise TypeError(
"Property `compression` must be None, str, or pyarrow.Codec")
@property
def use_threads(self):
return self.c_options.use_threads
@use_threads.setter
def use_threads(self, bint value):
self.c_options.use_threads = value
@property
def emit_dictionary_deltas(self):
return self.c_options.emit_dictionary_deltas
@emit_dictionary_deltas.setter
def emit_dictionary_deltas(self, bint value):
self.c_options.emit_dictionary_deltas = value
@property
def unify_dictionaries(self):
return self.c_options.unify_dictionaries
@unify_dictionaries.setter
def unify_dictionaries(self, bint value):
self.c_options.unify_dictionaries = value
cdef class Message(_Weakrefable):
"""
Container for an Arrow IPC message with metadata and optional body
"""
def __cinit__(self):
pass
def __init__(self):
raise TypeError("Do not call {}'s constructor directly, use "
"`pyarrow.ipc.read_message` function instead."
.format(self.__class__.__name__))
@property
def type(self):
return frombytes(FormatMessageType(self.message.get().type()))
@property
def metadata(self):
return pyarrow_wrap_buffer(self.message.get().metadata())
@property
def metadata_version(self):
return _wrap_metadata_version(self.message.get().metadata_version())
@property
def body(self):
cdef shared_ptr[CBuffer] body = self.message.get().body()
if body.get() == NULL:
return None
else:
return pyarrow_wrap_buffer(body)
def equals(self, Message other):
"""
Returns True if the message contents (metadata and body) are identical
Parameters
----------
other : Message
Returns
-------
are_equal : bool
"""
cdef c_bool result
with nogil:
result = self.message.get().Equals(deref(other.message.get()))
return result
def serialize_to(self, NativeFile sink, alignment=8, memory_pool=None):
"""
Write message to generic OutputStream
Parameters
----------
sink : NativeFile
alignment : int, default 8
Byte alignment for metadata and body
memory_pool : MemoryPool, default None
Uses default memory pool if not specified
"""
cdef:
int64_t output_length = 0
COutputStream* out
CIpcWriteOptions options
options.alignment = alignment
out = sink.get_output_stream().get()
with nogil:
check_status(self.message.get()
.SerializeTo(out, options, &output_length))
def serialize(self, alignment=8, memory_pool=None):
"""
Write message as encapsulated IPC message
Parameters
----------
alignment : int, default 8
Byte alignment for metadata and body
memory_pool : MemoryPool, default None
Uses default memory pool if not specified
Returns
-------
serialized : Buffer
"""
stream = BufferOutputStream(memory_pool)
self.serialize_to(stream, alignment=alignment, memory_pool=memory_pool)
return stream.getvalue()
def __repr__(self):
if self.message == nullptr:
return """pyarrow.Message(uninitialized)"""
metadata_len = self.metadata.size
body = self.body
body_len = 0 if body is None else body.size
return """pyarrow.Message
type: {0}
metadata length: {1}
body length: {2}""".format(self.type, metadata_len, body_len)
cdef class MessageReader(_Weakrefable):
"""
Interface for reading Message objects from some source (like an
InputStream)
"""
cdef:
unique_ptr[CMessageReader] reader
def __cinit__(self):
pass
def __init__(self):
raise TypeError("Do not call {}'s constructor directly, use "
"`pyarrow.ipc.MessageReader.open_stream` function "
"instead.".format(self.__class__.__name__))
@staticmethod
def open_stream(source):
"""
Open stream from source, if you want to use memory map use
MemoryMappedFile as source.
Parameters
----------
source : bytes/buffer-like, pyarrow.NativeFile, or file-like Python object
A readable source, like an InputStream
"""
cdef:
MessageReader result = MessageReader.__new__(MessageReader)
shared_ptr[CInputStream] in_stream
unique_ptr[CMessageReader] reader
_get_input_stream(source, &in_stream)
with nogil:
reader = CMessageReader.Open(in_stream)
result.reader.reset(reader.release())
return result
def __iter__(self):
while True:
yield self.read_next_message()
def read_next_message(self):
"""
Read next Message from the stream.
Raises
------
StopIteration
At end of stream
"""
cdef Message result = Message.__new__(Message)
with nogil:
result.message = move(GetResultValue(self.reader.get()
.ReadNextMessage()))
if result.message.get() == NULL:
raise StopIteration
return result
# ----------------------------------------------------------------------
# File and stream readers and writers
cdef class _CRecordBatchWriter(_Weakrefable):
"""The base RecordBatchWriter wrapper.
Provides common implementations of convenience methods. Should not
be instantiated directly by user code.
"""
# cdef block is in lib.pxd
def write(self, table_or_batch):
"""
Write RecordBatch or Table to stream.
Parameters
----------
table_or_batch : {RecordBatch, Table}
"""
if isinstance(table_or_batch, RecordBatch):
self.write_batch(table_or_batch)
elif isinstance(table_or_batch, Table):
self.write_table(table_or_batch)
else:
raise ValueError(type(table_or_batch))
def write_batch(self, RecordBatch batch, custom_metadata=None):
"""
Write RecordBatch to stream.
Parameters
----------
batch : RecordBatch
custom_metadata : mapping or KeyValueMetadata
Keys and values must be string-like / coercible to bytes
"""
metadata = ensure_metadata(custom_metadata, allow_none=True)
c_meta = pyarrow_unwrap_metadata(metadata)
with nogil:
check_status(self.writer.get()
.WriteRecordBatch(deref(batch.batch), c_meta))
def write_table(self, Table table, max_chunksize=None):
"""
Write Table to stream in (contiguous) RecordBatch objects.
Parameters
----------
table : Table
max_chunksize : int, default None
Maximum size for RecordBatch chunks. Individual chunks may be
smaller depending on the chunk layout of individual columns.
"""
cdef:
# max_chunksize must be > 0 to have any impact
int64_t c_max_chunksize = -1
if max_chunksize is not None:
c_max_chunksize = max_chunksize
with nogil:
check_status(self.writer.get().WriteTable(table.table[0],
c_max_chunksize))
def close(self):
"""
Close stream and write end-of-stream 0 marker.
"""
with nogil:
check_status(self.writer.get().Close())
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
@property
def stats(self):
"""
Current IPC write statistics.
"""
if not self.writer:
raise ValueError("Operation on closed writer")
return _wrap_write_stats(self.writer.get().stats())
cdef class _RecordBatchStreamWriter(_CRecordBatchWriter):
cdef:
CIpcWriteOptions options
bint closed
def __cinit__(self):
pass
def __dealloc__(self):
pass
@property
def _use_legacy_format(self):
# For testing (see test_ipc.py)
return self.options.write_legacy_ipc_format
@property
def _metadata_version(self):
# For testing (see test_ipc.py)
return _wrap_metadata_version(self.options.metadata_version)
def _open(self, sink, Schema schema not None,
IpcWriteOptions options=IpcWriteOptions()):
cdef:
shared_ptr[COutputStream] c_sink
self.options = options.c_options
get_writer(sink, &c_sink)
with nogil:
self.writer = GetResultValue(
MakeStreamWriter(c_sink, schema.sp_schema,
self.options))
cdef _get_input_stream(object source, shared_ptr[CInputStream]* out):
try:
source = as_buffer(source)
except TypeError:
# Non-buffer-like
pass
get_input_stream(source, True, out)
class _ReadPandasMixin:
def read_pandas(self, **options):
"""
Read contents of stream to a pandas.DataFrame.
Read all record batches as a pyarrow.Table then convert it to a
pandas.DataFrame using Table.to_pandas.
Parameters
----------
**options
Arguments to forward to :meth:`Table.to_pandas`.
Returns
-------
df : pandas.DataFrame
"""
table = self.read_all()
return table.to_pandas(**options)
cdef class RecordBatchReader(_Weakrefable):
"""Base class for reading stream of record batches.
Record batch readers function as iterators of record batches that also
provide the schema (without the need to get any batches).
Warnings
--------
Do not call this class's constructor directly, use one of the
``RecordBatchReader.from_*`` functions instead.
Notes
-----
To import and export using the Arrow C stream interface, use the
``_import_from_c`` and ``_export_from_c`` methods. However, keep in mind this
interface is intended for expert users.
Examples
--------
>>> import pyarrow as pa
>>> schema = pa.schema([('x', pa.int64())])
>>> def iter_record_batches():
... for i in range(2):
... yield pa.RecordBatch.from_arrays([pa.array([1, 2, 3])], schema=schema)
>>> reader = pa.RecordBatchReader.from_batches(schema, iter_record_batches())
>>> print(reader.schema)
x: int64
>>> for batch in reader:
... print(batch)
pyarrow.RecordBatch
x: int64
pyarrow.RecordBatch
x: int64
"""
# cdef block is in lib.pxd
def __iter__(self):
while True:
try:
yield self.read_next_batch()
except StopIteration:
return
@property
def schema(self):
"""
Shared schema of the record batches in the stream.
Returns
-------
Schema
"""
cdef shared_ptr[CSchema] c_schema
with nogil:
c_schema = self.reader.get().schema()
return pyarrow_wrap_schema(c_schema)
def read_next_batch(self):
"""
Read next RecordBatch from the stream.
Raises
------
StopIteration:
At end of stream.
Returns
-------
RecordBatch
"""
cdef shared_ptr[CRecordBatch] batch
with nogil:
check_status(self.reader.get().ReadNext(&batch))
if batch.get() == NULL:
raise StopIteration
return pyarrow_wrap_batch(batch)
def read_next_batch_with_custom_metadata(self):
"""
Read next RecordBatch from the stream along with its custom metadata.
Raises
------
StopIteration:
At end of stream.
Returns
-------
batch : RecordBatch
custom_metadata : KeyValueMetadata
"""
cdef:
CRecordBatchWithMetadata batch_with_metadata
with nogil:
batch_with_metadata = GetResultValue(self.reader.get().ReadNext())
if batch_with_metadata.batch.get() == NULL:
raise StopIteration
return _wrap_record_batch_with_metadata(batch_with_metadata)
def iter_batches_with_custom_metadata(self):
"""
Iterate over record batches from the stream along with their custom
metadata.
Yields
------
RecordBatchWithMetadata
"""
while True:
try:
yield self.read_next_batch_with_custom_metadata()
except StopIteration:
return
def read_all(self):
"""
Read all record batches as a pyarrow.Table.
Returns
-------
Table
"""
cdef shared_ptr[CTable] table
with nogil:
check_status(self.reader.get().ToTable().Value(&table))
return pyarrow_wrap_table(table)
read_pandas = _ReadPandasMixin.read_pandas
def close(self):
"""
Release any resources associated with the reader.
"""
with nogil:
check_status(self.reader.get().Close())
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
def _export_to_c(self, out_ptr):
"""
Export to a C ArrowArrayStream struct, given its pointer.
Parameters
----------
out_ptr: int
The raw pointer to a C ArrowArrayStream struct.
Be careful: if you don't pass the ArrowArrayStream struct to a
consumer, array memory will leak. This is a low-level function
intended for expert users.
"""
cdef:
void* c_ptr = _as_c_pointer(out_ptr)
with nogil:
check_status(ExportRecordBatchReader(
self.reader, <ArrowArrayStream*> c_ptr))
@staticmethod
def _import_from_c(in_ptr):
"""
Import RecordBatchReader from a C ArrowArrayStream struct,
given its pointer.
Parameters
----------
in_ptr: int
The raw pointer to a C ArrowArrayStream struct.
This is a low-level function intended for expert users.
"""
cdef:
void* c_ptr = _as_c_pointer(in_ptr)
shared_ptr[CRecordBatchReader] c_reader
RecordBatchReader self
with nogil:
c_reader = GetResultValue(ImportRecordBatchReader(
<ArrowArrayStream*> c_ptr))
self = RecordBatchReader.__new__(RecordBatchReader)
self.reader = c_reader
return self
@staticmethod
def from_batches(Schema schema not None, batches):
"""
Create RecordBatchReader from an iterable of batches.
Parameters
----------
schema : Schema
The shared schema of the record batches
batches : Iterable[RecordBatch]
The batches that this reader will return.
Returns
-------
reader : RecordBatchReader
"""
cdef:
shared_ptr[CSchema] c_schema
shared_ptr[CRecordBatchReader] c_reader
RecordBatchReader self
c_schema = pyarrow_unwrap_schema(schema)
c_reader = GetResultValue(CPyRecordBatchReader.Make(
c_schema, batches))
self = RecordBatchReader.__new__(RecordBatchReader)
self.reader = c_reader
return self
cdef class _RecordBatchStreamReader(RecordBatchReader):
cdef:
shared_ptr[CInputStream] in_stream
CIpcReadOptions options
CRecordBatchStreamReader* stream_reader
def __cinit__(self):
pass
def _open(self, source, IpcReadOptions options=IpcReadOptions(),
MemoryPool memory_pool=None):
self.options = options.c_options
self.options.memory_pool = maybe_unbox_memory_pool(memory_pool)
_get_input_stream(source, &self.in_stream)
with nogil:
self.reader = GetResultValue(CRecordBatchStreamReader.Open(
self.in_stream, self.options))
self.stream_reader = <CRecordBatchStreamReader*> self.reader.get()
@property
def stats(self):
"""
Current IPC read statistics.
"""
if not self.reader:
raise ValueError("Operation on closed reader")
return _wrap_read_stats(self.stream_reader.stats())
cdef class _RecordBatchFileWriter(_RecordBatchStreamWriter):
def _open(self, sink, Schema schema not None,
IpcWriteOptions options=IpcWriteOptions()):
cdef:
shared_ptr[COutputStream] c_sink
self.options = options.c_options
get_writer(sink, &c_sink)
with nogil:
self.writer = GetResultValue(
MakeFileWriter(c_sink, schema.sp_schema, self.options))
_RecordBatchWithMetadata = namedtuple(
'RecordBatchWithMetadata',
('batch', 'custom_metadata'))
class RecordBatchWithMetadata(_RecordBatchWithMetadata):
"""RecordBatch with its custom metadata
Parameters
----------
batch : RecordBatch
custom_metadata : KeyValueMetadata
"""
__slots__ = ()
@staticmethod
cdef _wrap_record_batch_with_metadata(CRecordBatchWithMetadata c):
return RecordBatchWithMetadata(pyarrow_wrap_batch(c.batch),
pyarrow_wrap_metadata(c.custom_metadata))
cdef class _RecordBatchFileReader(_Weakrefable):
cdef:
shared_ptr[CRecordBatchFileReader] reader
shared_ptr[CRandomAccessFile] file
CIpcReadOptions options
cdef readonly:
Schema schema
def __cinit__(self):
pass
def _open(self, source, footer_offset=None,
IpcReadOptions options=IpcReadOptions(),
MemoryPool memory_pool=None):
self.options = options.c_options
self.options.memory_pool = maybe_unbox_memory_pool(memory_pool)
try:
source = as_buffer(source)
except TypeError:
pass
get_reader(source, False, &self.file)
cdef int64_t offset = 0
if footer_offset is not None:
offset = footer_offset
with nogil:
if offset != 0:
self.reader = GetResultValue(
CRecordBatchFileReader.Open2(self.file.get(), offset,
self.options))
else:
self.reader = GetResultValue(
CRecordBatchFileReader.Open(self.file.get(),
self.options))
self.schema = pyarrow_wrap_schema(self.reader.get().schema())
@property
def num_record_batches(self):
"""
The number of record batches in the IPC file.
"""
return self.reader.get().num_record_batches()
def get_batch(self, int i):
"""
Read the record batch with the given index.
Parameters
----------
i : int
The index of the record batch in the IPC file.
Returns
-------
batch : RecordBatch
"""
cdef shared_ptr[CRecordBatch] batch
if i < 0 or i >= self.num_record_batches:
raise ValueError('Batch number {0} out of range'.format(i))
with nogil:
batch = GetResultValue(self.reader.get().ReadRecordBatch(i))
return pyarrow_wrap_batch(batch)
# TODO(wesm): ARROW-503: Function was renamed. Remove after a period of
# time has passed
get_record_batch = get_batch
def get_batch_with_custom_metadata(self, int i):
"""
Read the record batch with the given index along with
its custom metadata
Parameters
----------
i : int
The index of the record batch in the IPC file.
Returns
-------
batch : RecordBatch
custom_metadata : KeyValueMetadata
"""
cdef:
CRecordBatchWithMetadata batch_with_metadata
if i < 0 or i >= self.num_record_batches: