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
use std::io::{Read, Seek};
use arrow::io::avro::{self, read};
use polars_core::prelude::*;
use super::{finish_reader, ArrowChunk, ArrowReader, ArrowResult};
use crate::avro::convert_err;
use crate::prelude::*;
#[must_use]
pub struct AvroReader<R> {
reader: R,
rechunk: bool,
n_rows: Option<usize>,
columns: Option<Vec<String>>,
projection: Option<Vec<usize>>,
}
impl<R: Read + Seek> AvroReader<R> {
pub fn schema(&mut self) -> PolarsResult<Schema> {
let schema = self.arrow_schema()?;
Ok((schema.fields.iter()).into())
}
pub fn arrow_schema(&mut self) -> PolarsResult<ArrowSchema> {
let metadata =
avro::avro_schema::read::read_metadata(&mut self.reader).map_err(convert_err)?;
let schema = read::infer_schema(&metadata.record)?;
Ok(schema)
}
pub fn with_n_rows(mut self, num_rows: Option<usize>) -> Self {
self.n_rows = num_rows;
self
}
pub fn with_projection(mut self, projection: Option<Vec<usize>>) -> Self {
self.projection = projection;
self
}
pub fn with_columns(mut self, columns: Option<Vec<String>>) -> Self {
self.columns = columns;
self
}
}
impl<R> ArrowReader for read::Reader<R>
where
R: Read + Seek,
{
fn next_record_batch(&mut self) -> ArrowResult<Option<ArrowChunk>> {
self.next().map_or(Ok(None), |v| v.map(Some))
}
}
impl<R> SerReader<R> for AvroReader<R>
where
R: Read + Seek,
{
fn new(reader: R) -> Self {
AvroReader {
reader,
rechunk: true,
n_rows: None,
columns: None,
projection: None,
}
}
fn set_rechunk(mut self, rechunk: bool) -> Self {
self.rechunk = rechunk;
self
}
fn finish(mut self) -> PolarsResult<DataFrame> {
let rechunk = self.rechunk;
let metadata =
avro::avro_schema::read::read_metadata(&mut self.reader).map_err(convert_err)?;
let schema = read::infer_schema(&metadata.record)?;
if let Some(columns) = &self.columns {
self.projection = Some(columns_to_projection(columns, &schema)?);
}
let (projection, projected_schema) = if let Some(projection) = self.projection {
let mut prj = vec![false; schema.fields.len()];
for &index in projection.iter() {
prj[index] = true;
}
(Some(prj), apply_projection(&schema, &projection))
} else {
(None, schema.clone())
};
let avro_reader =
avro::read::Reader::new(&mut self.reader, metadata, schema.fields, projection);
finish_reader(
avro_reader,
rechunk,
self.n_rows,
None,
&projected_schema,
None,
)
}
}