bookdata/arrow/
writer.rs

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
use std::borrow::Cow;
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::marker::PhantomData;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use anyhow::{anyhow, Result};
use arrow::record_batch::RecordBatch;
use log::*;
use parquet::arrow::ArrowWriter;
use parquet::basic::{Compression, ZstdLevel as PQZstdLevel};
use parquet::file::properties::{WriterProperties, WriterPropertiesBuilder, WriterVersion};
use parquet::file::writer::SerializedFileWriter;
use parquet::record::RecordWriter;
use parquet::schema::types::TypePtr;
use polars::io::parquet::{BatchedWriter, ZstdLevel};
use polars::prelude::{ArrowSchema, DataFrame, ParquetCompression, ParquetWriter};
use polars_arrow::array::Array as PArray;
use polars_arrow::chunk::Chunk as PChunk;
use polars_parquet::write::{
    transverse, CompressionOptions, Encoding, FileWriter, RowGroupIterator, Version, WriteOptions,
};

use crate::arrow::nonnull_schema;
use crate::io::object::{ObjectWriter, ThreadObjectWriter, UnchunkWriter};
use crate::io::DataSink;
use crate::util::logging::item_progress;

const BATCH_SIZE: usize = 1024 * 1024;
const ZSTD_LEVEL: i32 = 3;

/// Open a Parquet writer using BookData defaults.
fn open_plpq_writer<P: AsRef<Path>>(path: P, schema: ArrowSchema) -> Result<FileWriter<File>> {
    let compression = CompressionOptions::Zstd(None);
    let options = WriteOptions {
        write_statistics: true,
        version: Version::V2,
        compression,
        data_pagesize_limit: None,
    };

    info!("creating Parquet file {:?}", path.as_ref());
    let file = OpenOptions::new()
        .create(true)
        .truncate(true)
        .write(true)
        .open(path)?;
    let writer = FileWriter::try_new(file, schema, options)?;

    Ok(writer)
}

/// Open a Polars data frame Parquet writer using BookData defaults.
pub fn open_polars_writer<P: AsRef<Path>>(path: P) -> Result<ParquetWriter<File>> {
    info!("creating Parquet file {:?}", path.as_ref());
    let file = OpenOptions::new()
        .create(true)
        .truncate(true)
        .write(true)
        .open(path)?;
    let writer = ParquetWriter::new(file)
        .with_compression(ParquetCompression::Zstd(Some(ZstdLevel::try_new(
            ZSTD_LEVEL,
        )?)))
        .with_row_group_size(Some(BATCH_SIZE));

    Ok(writer)
}

pub fn parquet_writer_defaults() -> WriterPropertiesBuilder {
    WriterProperties::builder()
        .set_compression(Compression::ZSTD(
            PQZstdLevel::try_new(ZSTD_LEVEL).expect("invalid zstd level"),
        ))
        .set_writer_version(WriterVersion::PARQUET_2_0)
        .set_dictionary_enabled(false)
}

/// Open an Arrow Parquet writer using BookData defaults.
pub fn open_parquet_writer<P: AsRef<Path>>(
    path: P,
    schema: TypePtr,
) -> Result<SerializedFileWriter<File>> {
    info!("creating Parquet file {:?}", path.as_ref());
    let file = OpenOptions::new()
        .create(true)
        .truncate(true)
        .write(true)
        .open(path)?;
    let props = parquet_writer_defaults().build();
    let writer = SerializedFileWriter::new(file, schema, Arc::new(props))?;

    Ok(writer)
}

/// Save a data frame to a Parquet file.
pub fn save_df_parquet<P: AsRef<Path>>(df: DataFrame, path: P) -> Result<()> {
    let path = path.as_ref();
    debug!("writing file {}", path.display());
    debug!("{}: schema {:?}", path.display(), df.schema());
    let mut df = df;
    let writer = open_polars_writer(path)?;
    let size = writer
        .with_row_group_size(Some(BATCH_SIZE))
        .finish(&mut df)?;
    debug!("{}: wrote {}", path.display(), friendly::bytes(size));
    Ok(())
}

/// Save a data frame to a Prquet file without nulls in the schema.
pub fn save_df_parquet_nonnull<P: AsRef<Path>>(df: DataFrame, path: P) -> Result<()> {
    let path = path.as_ref();
    debug!("writing file {}", path.display());
    debug!("{}: initial schema {:?}", path.display(), df.schema());
    let schema = nonnull_schema(&df);
    debug!("{}: nonnull schema {:?}", path.display(), schema);
    let mut writer = open_plpq_writer(path, schema)?;
    let pb = item_progress(df.n_chunks(), "writing chunks");
    for chunk in df.iter_chunks(false) {
        writer.write_object(chunk)?;
        pb.tick();
    }
    let size = writer.end(None)?;
    debug!(
        "{}: wrote {} chunks in {}",
        path.display(),
        df.n_chunks(),
        friendly::bytes(size)
    );
    Ok(())
}

/// Parquet table writer.
///
/// A table writer is an [ObjectWriter] for structs implementing [TableRow], that writes
/// them out to a Parquet file.
pub struct TableWriter<R>
where
    R: Send + Sync + 'static,
    for<'a> &'a [R]: RecordWriter<R>,
{
    _phantom: PhantomData<R>,
    writer: Option<UnchunkWriter<R, ThreadObjectWriter<'static, Vec<R>>>>,
    out_path: Option<PathBuf>,
    row_count: usize,
}

impl<R> TableWriter<R>
where
    R: Send + Sync + 'static,
    for<'a> &'a [R]: RecordWriter<R>,
{
    /// Open a table writer for a path.
    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
        let path = path.as_ref();

        // extract struct schema
        let empty: [R; 0] = [];
        let schema = (&empty as &[R]).schema()?;
        debug!("{}: opening for schema {:?}", path.display(), schema);

        let writer = open_parquet_writer(path, schema)?;
        let writer = ThreadObjectWriter::wrap(writer)
            .with_name(format!("write:{}", path.display()))
            .with_capacity(4)
            .spawn();
        let writer = UnchunkWriter::with_size(writer, BATCH_SIZE);
        let out_path = Some(path.to_path_buf());
        Ok(TableWriter {
            _phantom: PhantomData,
            writer: Some(writer),
            out_path,
            row_count: 0,
        })
    }
}

impl<R> TableWriter<R>
where
    R: Send + Sync + 'static,
    for<'a> &'a [R]: RecordWriter<R>,
{
    fn display_path(&self) -> Cow<'static, str> {
        if let Some(p) = &self.out_path {
            format!("{}", p.display()).into()
        } else {
            "<unknown>".into()
        }
    }
}

impl<R> DataSink for TableWriter<R>
where
    R: Send + Sync + 'static,
    for<'a> &'a [R]: RecordWriter<R>,
{
    fn output_files(&self) -> Vec<PathBuf> {
        match &self.out_path {
            None => Vec::new(),
            Some(p) => vec![p.clone()],
        }
    }
}

impl<R> ObjectWriter<R> for TableWriter<R>
where
    R: Send + Sync + 'static,
    for<'a> &'a [R]: RecordWriter<R>,
{
    fn write_object(&mut self, row: R) -> Result<()> {
        let w = self
            .writer
            .as_mut()
            .ok_or_else(|| anyhow!("writer is closed"))?;

        w.write_object(row)?;
        self.row_count += 1;
        Ok(())
    }

    fn finish(mut self) -> Result<usize> {
        if let Some(writer) = self.writer.take() {
            info!("closing Parquet writer for {}", self.display_path());
            writer.finish()?;
        } else {
            warn!("{}: writer already closed", self.display_path());
        }
        Ok(self.row_count)
    }
}

impl<R> Drop for TableWriter<R>
where
    R: Send + Sync + 'static,
    for<'a> &'a [R]: RecordWriter<R>,
{
    fn drop(&mut self) {
        // make sure we closed the writer
        if self.writer.is_some() {
            error!("{}: Parquet table writer not closed", self.display_path());
        }
    }
}

/// Implementation of object writer for Polars Arrow writers
impl<W> ObjectWriter<PChunk<Box<dyn PArray + 'static>>> for FileWriter<W>
where
    W: Write,
{
    fn write_object(&mut self, chunk: PChunk<Box<dyn PArray + 'static>>) -> Result<()> {
        let schema = self.schema();
        let encodings: Vec<_> = schema
            .fields
            .iter()
            .map(|f| transverse(&f.data_type, |_| Encoding::Plain))
            .collect();
        let options = self.options();
        let chunks = vec![Ok(chunk)];
        let groups = RowGroupIterator::try_new(chunks.into_iter(), &schema, options, encodings)?;
        for group in groups {
            self.write(group?)?;
        }
        Ok(())
    }

    fn finish(mut self) -> Result<usize> {
        self.end(None)?;
        Ok(0)
    }
}

impl<W> ObjectWriter<RecordBatch> for ArrowWriter<W>
where
    W: Write + Send,
{
    fn write_object(&mut self, batch: RecordBatch) -> Result<()> {
        self.write(&batch)?;
        Ok(())
    }

    fn finish(self) -> Result<usize> {
        let meta = self.close()?;
        Ok(meta.num_rows as usize)
    }
}

impl<W, R> ObjectWriter<Vec<R>> for SerializedFileWriter<W>
where
    W: Write + Send,
    for<'a> &'a [R]: RecordWriter<R>,
{
    fn write_object(&mut self, object: Vec<R>) -> Result<()> {
        let slice = object.as_slice();
        let mut group = self.next_row_group()?;
        slice.write_to_row_group(&mut group)?;
        group.close()?;
        Ok(())
    }

    fn finish(self) -> Result<usize> {
        self.close()?;
        Ok(0)
    }
}

/// Implementation of object writer for Polars Parquet batched writer
impl<W> ObjectWriter<DataFrame> for BatchedWriter<W>
where
    W: Write,
{
    fn write_object(&mut self, df: DataFrame) -> Result<()> {
        self.write_batch(&df)?;
        Ok(())
    }

    fn finish(mut self) -> Result<usize> {
        let size = BatchedWriter::finish(&mut self)?;
        Ok(size as usize)
    }
}