Skip to main content

polars_io/parquet/write/
batched_writer.rs

1use std::io::Write;
2use std::sync::Mutex;
3
4use polars_arrow::record_batch::RecordBatch;
5use polars_buffer::Buffer;
6use polars_core::prelude::*;
7use polars_core::runtime::RAYON;
8use polars_parquet::read::{ParquetError, fallible_streaming_iterator};
9use polars_parquet::write::{
10    CompressedPage, Compressor, DynIter, DynStreamingIterator, Encoding, FallibleStreamingIterator,
11    FileWriter, Page, ParquetType, RowGroupIterColumns, SchemaDescriptor, WriteOptions,
12    array_to_columns, schema_to_metadata_key,
13};
14use rayon::prelude::*;
15
16use super::{KeyValueMetadata, ParquetMetadataContext};
17
18pub struct BatchedWriter<W: Write> {
19    // A mutex so that streaming engine can get concurrent read access to
20    // compress pages.
21    //
22    // @TODO: Remove mutex when old streaming engine is removed
23    pub(super) writer: Mutex<FileWriter<W>>,
24    // @TODO: Remove when old streaming engine is removed
25    pub(super) parquet_schema: SchemaDescriptor,
26    pub(super) encodings: Buffer<Vec<Encoding>>,
27    pub(super) options: WriteOptions,
28    pub(super) parallel: bool,
29    pub(super) key_value_metadata: Option<KeyValueMetadata>,
30}
31
32impl<W: Write> BatchedWriter<W> {
33    pub fn new(
34        writer: Mutex<FileWriter<W>>,
35        encodings: Buffer<Vec<Encoding>>,
36        options: WriteOptions,
37        parallel: bool,
38        key_value_metadata: Option<KeyValueMetadata>,
39    ) -> Self {
40        Self {
41            writer,
42            parquet_schema: SchemaDescriptor::new(PlSmallStr::EMPTY, vec![]),
43            encodings,
44            options,
45            parallel,
46            key_value_metadata,
47        }
48    }
49
50    pub fn encode_and_compress<'a>(
51        &'a self,
52        df: &'a DataFrame,
53    ) -> impl Iterator<Item = PolarsResult<RowGroupIterColumns<'static, PolarsError>>> + 'a {
54        let rb_iter = df.try_iter_chunks(CompatLevel::newest(), false);
55        rb_iter.filter_map(move |batch| match batch {
56            Ok(batch) if batch.is_empty() => None,
57            Ok(batch) => Some(create_eager_serializer(
58                batch,
59                self.parquet_schema.fields(),
60                self.encodings.as_ref(),
61                self.options,
62            )),
63            Err(err) => Some(Err(err)),
64        })
65    }
66
67    /// Write a batch to the parquet writer.
68    ///
69    /// # Panics
70    /// The caller must ensure the chunks in the given [`DataFrame`] are aligned.
71    pub fn write_batch(&mut self, df: &DataFrame) -> PolarsResult<()> {
72        let row_group_iter = prepare_rg_iter(
73            df,
74            &self.parquet_schema,
75            &self.encodings,
76            self.options,
77            self.parallel,
78        );
79        // Lock before looping so that order is maintained under contention.
80        let mut writer = self.writer.lock().unwrap();
81        for (num_rows, group) in row_group_iter {
82            writer.write(num_rows as u64, group?)?;
83        }
84        Ok(())
85    }
86
87    pub fn parquet_schema(&mut self) -> &SchemaDescriptor {
88        let writer = self.writer.get_mut().unwrap();
89        writer.parquet_schema()
90    }
91
92    /// Note: `num_rows` can be passed as `u64::MAX` to infer `num_rows` from the encoded data.
93    pub fn write_row_group(
94        &mut self,
95        num_rows: u64,
96        rg: &[Vec<CompressedPage>],
97    ) -> PolarsResult<()> {
98        let writer = self.writer.get_mut().unwrap();
99        let rg = DynIter::new(rg.iter().map(|col_pages| {
100            Ok(DynStreamingIterator::new(
101                fallible_streaming_iterator::convert(col_pages.iter().map(PolarsResult::Ok)),
102            ))
103        }));
104        writer.write(num_rows, rg)?;
105        Ok(())
106    }
107
108    pub fn get_writer(&self) -> &Mutex<FileWriter<W>> {
109        &self.writer
110    }
111
112    pub fn write_row_groups(
113        &self,
114        rgs: Vec<RowGroupIterColumns<'static, PolarsError>>,
115    ) -> PolarsResult<()> {
116        // Lock before looping so that order is maintained.
117        let mut writer = self.writer.lock().unwrap();
118        for group in rgs {
119            writer.write(u64::MAX, group)?;
120        }
121        Ok(())
122    }
123
124    /// Writes the footer of the parquet file. Returns the total size of the file.
125    pub fn finish(&self) -> PolarsResult<u64> {
126        let mut writer = self.writer.lock().unwrap();
127
128        let key_value_metadata = self
129            .key_value_metadata
130            .as_ref()
131            .map(|meta| {
132                let arrow_schema = schema_to_metadata_key(writer.schema());
133                let ctx = ParquetMetadataContext {
134                    arrow_schema: arrow_schema.value.as_ref().unwrap(),
135                };
136                let mut out = meta.collect(ctx)?;
137                if !out.iter().any(|kv| kv.key == arrow_schema.key) {
138                    out.insert(0, arrow_schema);
139                }
140                PolarsResult::Ok(out)
141            })
142            .transpose()?;
143
144        let size = writer.end(key_value_metadata)?;
145        Ok(size)
146    }
147}
148
149// Note that the df should be rechunked
150fn prepare_rg_iter<'a>(
151    df: &'a DataFrame,
152    parquet_schema: &'a SchemaDescriptor,
153    encodings: &'a [Vec<Encoding>],
154    options: WriteOptions,
155    parallel: bool,
156) -> impl Iterator<
157    Item = (
158        usize,
159        PolarsResult<RowGroupIterColumns<'static, PolarsError>>,
160    ),
161> + 'a {
162    let rb_iter = df.try_iter_chunks(CompatLevel::newest(), false);
163    rb_iter.filter_map(move |batch| match batch {
164        Ok(batch) if batch.is_empty() => None,
165        Ok(batch) => {
166            let num_rows = batch.len();
167            let row_group =
168                create_serializer(batch, parquet_schema.fields(), encodings, options, parallel);
169
170            Some((num_rows, row_group))
171        },
172        Err(err) => Some((0, Err(err))),
173    })
174}
175
176fn pages_iter_to_compressor(
177    encoded_columns: Vec<DynIter<'static, PolarsResult<Page>>>,
178    options: WriteOptions,
179) -> Vec<PolarsResult<DynStreamingIterator<'static, CompressedPage, PolarsError>>> {
180    encoded_columns
181        .into_iter()
182        .map(|encoded_pages| {
183            // iterator over pages
184            let pages = DynStreamingIterator::new(
185                Compressor::new_from_vec(
186                    encoded_pages.map(|result| {
187                        result.map_err(|e| {
188                            ParquetError::FeatureNotSupported(format!("reraised in polars: {e}",))
189                        })
190                    }),
191                    options.compression,
192                    vec![],
193                )
194                .map_err(PolarsError::from),
195            );
196
197            Ok(pages)
198        })
199        .collect::<Vec<_>>()
200}
201
202fn array_to_pages_iter(
203    array: &ArrayRef,
204    type_: &ParquetType,
205    encoding: &[Encoding],
206    options: WriteOptions,
207) -> Vec<PolarsResult<DynStreamingIterator<'static, CompressedPage, PolarsError>>> {
208    let encoded_columns = array_to_columns(array, type_.clone(), options, encoding).unwrap();
209    pages_iter_to_compressor(encoded_columns, options)
210}
211
212fn create_serializer(
213    batch: RecordBatch,
214    fields: &[ParquetType],
215    encodings: &[Vec<Encoding>],
216    options: WriteOptions,
217    parallel: bool,
218) -> PolarsResult<RowGroupIterColumns<'static, PolarsError>> {
219    let func = move |((array, type_), encoding): ((&ArrayRef, &ParquetType), &Vec<Encoding>)| {
220        array_to_pages_iter(array, type_, encoding, options)
221    };
222
223    let columns = if parallel {
224        RAYON.install(|| {
225            batch
226                .columns()
227                .par_iter()
228                .zip(fields)
229                .zip(encodings)
230                .flat_map(func)
231                .collect::<Vec<_>>()
232        })
233    } else {
234        batch
235            .columns()
236            .iter()
237            .zip(fields)
238            .zip(encodings)
239            .flat_map(func)
240            .collect::<Vec<_>>()
241    };
242
243    let row_group = DynIter::new(columns.into_iter());
244
245    Ok(row_group)
246}
247
248/// This serializer encodes and compresses all eagerly in memory.
249/// Used for separating compute from IO.
250fn create_eager_serializer(
251    batch: RecordBatch,
252    fields: &[ParquetType],
253    encodings: &[Vec<Encoding>],
254    options: WriteOptions,
255) -> PolarsResult<RowGroupIterColumns<'static, PolarsError>> {
256    let func = move |((array, type_), encoding): ((&ArrayRef, &ParquetType), &Vec<Encoding>)| {
257        array_to_pages_iter(array, type_, encoding, options)
258    };
259
260    let columns = batch
261        .columns()
262        .iter()
263        .zip(fields)
264        .zip(encodings)
265        .flat_map(func)
266        .collect::<Vec<_>>();
267
268    let row_group = DynIter::new(columns.into_iter());
269
270    Ok(row_group)
271}