Skip to main content

parquet_derive/
lib.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! This crate provides a procedural macro to derive
19//! implementations of a RecordWriter and RecordReader
20//!
21//! # Platform Support
22//!
23//! Only little-endian platforms are officially supported and tested in CI.
24//! Big-endian platforms are not tested in CI and may not work correctly.
25//! Fixes for big-endian platforms are welcome and handled on a best-effort basis,
26//! but compatibility is not guaranteed.
27
28#![doc(
29    html_logo_url = "https://raw.githubusercontent.com/apache/parquet-format/25f05e73d8cd7f5c83532ce51cb4f4de8ba5f2a2/logo/parquet-logos_1.svg",
30    html_favicon_url = "https://raw.githubusercontent.com/apache/parquet-format/25f05e73d8cd7f5c83532ce51cb4f4de8ba5f2a2/logo/parquet-logos_1.svg"
31)]
32#![cfg_attr(docsrs, feature(doc_cfg))]
33#![warn(missing_docs)]
34#![recursion_limit = "128"]
35
36#[macro_use]
37extern crate quote;
38
39use ::syn::{Data, DataStruct, DeriveInput, ext::IdentExt, parse_macro_input};
40
41mod parquet_field;
42
43/// Derive flat, simple RecordWriter implementations.
44///
45/// Works by parsing a struct tagged with `#[derive(ParquetRecordWriter)]` and emitting
46/// the correct writing code for each field of the struct. Column writers
47/// are generated in the order they are defined.
48///
49/// It is up to the programmer to keep the order of the struct
50/// fields lined up with the schema.
51///
52/// Example:
53///
54/// ```rust
55/// use parquet::file::properties::WriterProperties;
56/// use parquet::file::writer::SerializedFileWriter;
57/// use parquet::record::RecordWriter;
58/// use parquet_derive::ParquetRecordWriter;
59/// use std::fs::File;
60/// use std::sync::Arc;
61///
62/// // For reader
63/// use parquet::file::reader::{FileReader, SerializedFileReader};
64/// use parquet::record::RecordReader;
65/// use parquet_derive::ParquetRecordReader;
66///
67/// #[derive(Debug, ParquetRecordWriter, ParquetRecordReader)]
68/// struct ACompleteRecord {
69///     pub a_bool: bool,
70///     pub a_string: String,
71/// }
72///
73/// fn write_some_records() {
74///     let samples = vec![
75///         ACompleteRecord {
76///             a_bool: true,
77///             a_string: "I'm true".into(),
78///         },
79///         ACompleteRecord {
80///             a_bool: false,
81///             a_string: "I'm false".into(),
82///         },
83///     ];
84///
85///     let schema = samples.as_slice().schema().unwrap();
86///
87///     let props = Arc::new(WriterProperties::builder().build());
88///
89///     let file = File::create("example.parquet").unwrap();
90///
91///     let mut writer = SerializedFileWriter::new(file, schema, props).unwrap();
92///
93///     let mut row_group = writer.next_row_group().unwrap();
94///
95///     samples
96///         .as_slice()
97///         .write_to_row_group(&mut row_group)
98///         .unwrap();
99///
100///     row_group.close().unwrap();
101///
102///     writer.close().unwrap();
103/// }
104///
105/// fn read_some_records() -> Vec<ACompleteRecord> {
106///     let mut samples: Vec<ACompleteRecord> = Vec::new();
107///     let file = File::open("example.parquet").unwrap();
108///
109///     let reader = SerializedFileReader::new(file).unwrap();
110///     let mut row_group = reader.get_row_group(0).unwrap();
111///     samples.read_from_row_group(&mut *row_group, 2).unwrap();
112///
113///     samples
114/// }
115///
116/// pub fn main() {
117///     write_some_records();
118///
119///     let records = read_some_records();
120///
121///     std::fs::remove_file("example.parquet").unwrap();
122///
123///     assert_eq!(
124///         format!("{:?}", records),
125///         "[ACompleteRecord { a_bool: true, a_string: \"I'm true\" }, ACompleteRecord { a_bool: false, a_string: \"I'm false\" }]"
126///     );
127/// }
128/// ```
129///
130#[proc_macro_derive(ParquetRecordWriter)]
131pub fn parquet_record_writer(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
132    let input: DeriveInput = parse_macro_input!(input as DeriveInput);
133    let fields = match input.data {
134        Data::Struct(DataStruct { fields, .. }) => fields,
135        Data::Enum(_) => unimplemented!("Enum currently is not supported"),
136        Data::Union(_) => unimplemented!("Union currently is not supported"),
137    };
138
139    let field_infos: Vec<_> = fields.iter().map(parquet_field::Field::from).collect();
140
141    let writer_snippets: Vec<proc_macro2::TokenStream> =
142        field_infos.iter().map(|x| x.writer_snippet()).collect();
143
144    let derived_for = input.ident;
145    let generics = input.generics;
146
147    let field_types: Vec<proc_macro2::TokenStream> =
148        field_infos.iter().map(|x| x.parquet_type()).collect();
149
150    (quote! {
151    impl #generics ::parquet::record::RecordWriter<#derived_for #generics> for &[#derived_for #generics] {
152      fn write_to_row_group<W: ::std::io::Write + Send>(
153        &self,
154        row_group_writer: &mut ::parquet::file::writer::SerializedRowGroupWriter<'_, W>
155      ) -> ::std::result::Result<(), ::parquet::errors::ParquetError> {
156        use ::parquet::column::writer::ColumnWriter;
157
158        let mut row_group_writer = row_group_writer;
159        let records = &self; // Used by all the writer snippets to be more clear
160
161        #(
162          {
163              let mut some_column_writer = row_group_writer.next_column().unwrap();
164              if let Some(mut column_writer) = some_column_writer {
165                  #writer_snippets
166                  column_writer.close()?;
167              } else {
168                  return Err(::parquet::errors::ParquetError::General("Failed to get next column".into()))
169              }
170          }
171        );*
172
173        Ok(())
174      }
175
176      fn schema(&self) -> ::std::result::Result<::parquet::schema::types::TypePtr, ::parquet::errors::ParquetError> {
177        use ::parquet::schema::types::Type as ParquetType;
178        use ::parquet::schema::types::TypePtr;
179        use ::parquet::basic::LogicalType;
180
181        let mut fields: ::std::vec::Vec<TypePtr> = ::std::vec::Vec::new();
182        #(
183          #field_types
184        );*;
185        let group = ParquetType::group_type_builder("rust_schema")
186          .with_fields(fields)
187          .build()?;
188        Ok(group.into())
189      }
190    }
191  }).into()
192}
193
194/// Derive flat, simple RecordReader implementations.
195///
196/// Works by parsing a struct tagged with `#[derive(ParquetRecordReader)]` and emitting
197/// the correct writing code for each field of the struct. Column readers
198/// are generated by matching names in the schema to the names in the struct.
199///
200/// It is up to the programmer to ensure the names in the struct
201/// fields line up with the schema.
202///
203/// Example:
204///
205/// ```rust
206/// use parquet::record::RecordReader;
207/// use parquet::file::{serialized_reader::SerializedFileReader, reader::FileReader};
208/// use parquet_derive::{ParquetRecordReader};
209/// use std::fs::File;
210///
211/// #[derive(ParquetRecordReader)]
212/// struct ACompleteRecord {
213///     pub a_bool: bool,
214///     pub a_string: String,
215/// }
216///
217/// pub fn read_some_records() -> Vec<ACompleteRecord> {
218///   let mut samples: Vec<ACompleteRecord> = Vec::new();
219///   let file = File::open("some_file.parquet").unwrap();
220///
221///   let reader = SerializedFileReader::new(file).unwrap();
222///   let mut row_group = reader.get_row_group(0).unwrap();
223///   samples.read_from_row_group(&mut *row_group, 1).unwrap();
224///   samples
225/// }
226/// ```
227///
228#[proc_macro_derive(ParquetRecordReader)]
229pub fn parquet_record_reader(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
230    let input: DeriveInput = parse_macro_input!(input as DeriveInput);
231    let fields = match input.data {
232        Data::Struct(DataStruct { fields, .. }) => fields,
233        Data::Enum(_) => unimplemented!("Enum currently is not supported"),
234        Data::Union(_) => unimplemented!("Union currently is not supported"),
235    };
236
237    let field_infos: Vec<_> = fields.iter().map(parquet_field::Field::from).collect();
238    let field_names: Vec<_> = fields.iter().map(|f| f.ident.clone()).collect();
239    // unraw the identifiers, so raw identifiers like `r#type` are looked
240    // up by their column name `type` in the parquet file
241    let field_names_str: Vec<_> = fields
242        .iter()
243        .map(|f| {
244            f.ident
245                .as_ref()
246                .expect("Only structs with named fields are currently supported")
247                .unraw()
248                .to_string()
249        })
250        .collect();
251    let reader_snippets: Vec<proc_macro2::TokenStream> =
252        field_infos.iter().map(|x| x.reader_snippet()).collect();
253
254    let derived_for = input.ident;
255    let generics = input.generics;
256
257    (quote! {
258
259    impl #generics ::parquet::record::RecordReader<#derived_for #generics> for Vec<#derived_for #generics> {
260      fn read_from_row_group(
261        &mut self,
262        row_group_reader: &mut dyn ::parquet::file::reader::RowGroupReader,
263        num_records: usize,
264      ) -> ::std::result::Result<(), ::parquet::errors::ParquetError> {
265        use ::parquet::column::reader::ColumnReader;
266
267        let mut row_group_reader = row_group_reader;
268
269        // key: parquet file column name, value: column index
270        let mut name_to_index = std::collections::HashMap::new();
271        for (idx, col) in row_group_reader.metadata().schema_descr().columns().iter().enumerate() {
272            name_to_index.insert(col.name().to_string(), idx);
273        }
274
275        for _ in 0..num_records {
276          self.push(#derived_for {
277            #(
278              #field_names: Default::default()
279            ),*
280          })
281        }
282
283        let records = self; // Used by all the reader snippets to be more clear
284
285        #(
286          {
287              let idx: usize = match name_to_index.get(#field_names_str) {
288                Some(&col_idx) => col_idx,
289                None => {
290                  let error_msg = format!("column name '{}' is not found in parquet file!", #field_names_str);
291                  return Err(::parquet::errors::ParquetError::General(error_msg));
292                }
293              };
294              if let Ok(column_reader) = row_group_reader.get_column_reader(idx) {
295                  #reader_snippets
296              } else {
297                  return Err(::parquet::errors::ParquetError::General("Failed to get next column".into()))
298              }
299          }
300        );*
301
302        Ok(())
303      }
304    }
305  }).into()
306}