polars_io/parquet/write/
writer.rs1use std::io::Write;
2use std::sync::Mutex;
3
4use polars_buffer::Buffer;
5use polars_core::frame::chunk_df_for_writing;
6use polars_core::prelude::*;
7use polars_parquet::arrow::geo::{GEO_KEY, validate_geo_schema};
8use polars_parquet::write::{
9 CompressionOptions, Encoding, FileWriter, StatisticsOptions, Version, WriteOptions,
10 get_dtype_encoding, to_parquet_schema,
11};
12
13use super::batched_writer::BatchedWriter;
14use super::options::ParquetCompression;
15use super::{KeyValueMetadata, ParquetWriteOptions};
16use crate::parquet::encryption::ParquetEncryption;
17use crate::shared::schema_to_arrow_checked;
18
19impl ParquetWriteOptions {
20 pub fn to_writer<F>(&self, f: F) -> ParquetWriter<F>
21 where
22 F: Write,
23 {
24 ParquetWriter::new(f)
25 .with_compression(self.compression)
26 .with_statistics(self.statistics)
27 .with_row_group_size(self.row_group_size)
28 .with_data_page_size(self.data_page_size)
29 .with_key_value_metadata(self.key_value_metadata.clone())
30 .with_encryption(self.encryption.clone())
31 }
32}
33
34#[must_use]
36pub struct ParquetWriter<W> {
37 writer: W,
38 compression: CompressionOptions,
40 statistics: StatisticsOptions,
42 row_group_size: Option<usize>,
44 data_page_size: Option<usize>,
46 parallel: bool,
48 key_value_metadata: Option<KeyValueMetadata>,
50 context_info: Option<PlHashMap<String, String>>,
52 encryption: Option<ParquetEncryption>,
54}
55
56impl<W> ParquetWriter<W>
57where
58 W: Write,
59{
60 pub fn new(writer: W) -> Self
62 where
63 W: Write,
64 {
65 ParquetWriter {
66 writer,
67 compression: ParquetCompression::default().into(),
68 statistics: StatisticsOptions::default(),
69 row_group_size: None,
70 data_page_size: None,
71 parallel: true,
72 key_value_metadata: None,
73 context_info: None,
74 encryption: None,
75 }
76 }
77
78 pub fn with_compression(mut self, compression: ParquetCompression) -> Self {
83 self.compression = compression.into();
84 self
85 }
86
87 pub fn with_statistics(mut self, statistics: StatisticsOptions) -> Self {
89 self.statistics = statistics;
90 self
91 }
92
93 pub fn with_row_group_size(mut self, size: Option<usize>) -> Self {
96 self.row_group_size = size;
97 self
98 }
99
100 pub fn with_data_page_size(mut self, limit: Option<usize>) -> Self {
102 self.data_page_size = limit;
103 self
104 }
105
106 pub fn set_parallel(mut self, parallel: bool) -> Self {
108 self.parallel = parallel;
109 self
110 }
111
112 pub fn with_key_value_metadata(mut self, key_value_metadata: Option<KeyValueMetadata>) -> Self {
114 self.key_value_metadata = key_value_metadata;
115 self
116 }
117
118 pub fn with_context_info(mut self, context_info: Option<PlHashMap<String, String>>) -> Self {
120 self.context_info = context_info;
121 self
122 }
123
124 pub fn with_encryption(mut self, encryption: Option<ParquetEncryption>) -> Self {
126 self.encryption = encryption;
127 self
128 }
129
130 pub fn batched(self, schema: &Schema) -> PolarsResult<BatchedWriter<W>> {
131 let schema = schema_to_arrow_checked(schema, CompatLevel::newest(), "parquet")?;
132 if !self
135 .key_value_metadata
136 .as_ref()
137 .is_some_and(|kv| kv.may_contain(GEO_KEY))
138 {
139 validate_geo_schema(&schema)?;
140 }
141 let parquet_schema = to_parquet_schema(&schema)?;
142 let encodings = get_encodings(&schema);
143 let options = self.materialize_options();
144 let encryption_properties = self
145 .encryption
146 .as_ref()
147 .map(ParquetEncryption::file_properties)
148 .transpose()?;
149 let writer = Mutex::new(FileWriter::try_new(
150 self.writer,
151 schema,
152 options,
153 encryption_properties,
154 )?);
155
156 Ok(BatchedWriter {
157 writer,
158 parquet_schema,
159 encodings,
160 options,
161 parallel: self.parallel,
162 key_value_metadata: self.key_value_metadata,
163 })
164 }
165
166 fn materialize_options(&self) -> WriteOptions {
167 WriteOptions {
168 statistics: self.statistics,
169 compression: self.compression,
170 version: Version::V1,
171 data_page_size: self.data_page_size,
172 }
173 }
174
175 pub fn finish(self, df: &mut DataFrame) -> PolarsResult<u64> {
178 let chunked_df = chunk_df_for_writing(df, self.row_group_size.unwrap_or(512 * 512))?;
179 let mut batched = self.batched(chunked_df.schema())?;
180 batched.write_batch(&chunked_df)?;
181 batched.finish()
182 }
183}
184
185pub fn get_encodings(schema: &ArrowSchema) -> Buffer<Vec<Encoding>> {
186 schema
187 .iter_values()
188 .map(|f| get_dtype_encoding(&f.dtype))
189 .collect()
190}