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