Skip to main content

parquet_derive/
parquet_field.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
18use syn::ext::IdentExt;
19
20/// Parquet physical types used while selecting the code emitted by the macro.
21/// Keeping this local avoids compiling `parquet` for the proc-macro host.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23enum PhysicalType {
24    Boolean,
25    Int32,
26    Int64,
27    Float,
28    Double,
29    ByteArray,
30    FixedLenByteArray,
31}
32
33#[derive(Debug, PartialEq)]
34pub struct Field {
35    ident: syn::Ident,
36    ty: Type,
37    is_a_byte_buf: bool,
38    third_party_type: Option<ThirdPartyType>,
39}
40
41/// Use third party libraries, detected
42/// at compile time. These libraries will
43/// be written to parquet as their preferred
44/// physical type.
45///
46///   ChronoNaiveDateTime is written as i64
47///   ChronoNaiveDate is written as i32
48#[derive(Debug, PartialEq)]
49enum ThirdPartyType {
50    ChronoNaiveDateTime,
51    ChronoNaiveDate,
52    Uuid,
53}
54
55impl Field {
56    pub fn from(f: &syn::Field) -> Self {
57        let ty = Type::from(f);
58        let is_a_byte_buf = ty.physical_type() == PhysicalType::ByteArray;
59
60        let third_party_type = match &ty.last_part()[..] {
61            "NaiveDateTime" => Some(ThirdPartyType::ChronoNaiveDateTime),
62            "NaiveDate" => Some(ThirdPartyType::ChronoNaiveDate),
63            "Uuid" => Some(ThirdPartyType::Uuid),
64            _ => None,
65        };
66
67        Field {
68            ident: f
69                .ident
70                .clone()
71                .expect("Only structs with named fields are currently supported"),
72            ty,
73            is_a_byte_buf,
74            third_party_type,
75        }
76    }
77
78    /// Takes the parsed field of the struct and emits a valid
79    /// column writer snippet. Should match exactly what you
80    /// would write by hand.
81    ///
82    /// Can only generate writers for basic structs, for example:
83    ///
84    /// struct Record {
85    ///   a_bool: bool,
86    ///   maybe_a_bool: `Option<bool>`
87    /// }
88    ///
89    /// but not
90    ///
91    /// struct UnsupportedNestedRecord {
92    ///   a_property: bool,
93    ///   nested_record: Record
94    /// }
95    ///
96    /// because this parsing logic is not sophisticated enough for definition
97    /// levels beyond 2.
98    pub fn writer_snippet(&self) -> proc_macro2::TokenStream {
99        let ident = &self.ident;
100        let column_writer = self.ty.column_writer();
101
102        let vals_builder = match &self.ty {
103            Type::TypePath(_) => self.copied_direct_vals(),
104            Type::Option(first_type) => match **first_type {
105                Type::TypePath(_) => self.option_into_vals(),
106                Type::Reference(_, ref second_type) => match **second_type {
107                    Type::TypePath(_) => self.option_into_vals(),
108                    _ => unimplemented!("Unsupported type encountered"),
109                },
110                Type::Vec(ref first_type) => match **first_type {
111                    Type::TypePath(_) => self.option_into_vals(),
112                    _ => unimplemented!("Unsupported type encountered"),
113                },
114                ref f => unimplemented!("Unsupported: {:#?}", f),
115            },
116            Type::Reference(_, first_type) => match **first_type {
117                Type::TypePath(_) => self.copied_direct_vals(),
118                Type::Option(ref second_type) => match **second_type {
119                    Type::TypePath(_) => self.option_into_vals(),
120                    Type::Reference(_, ref second_type) => match **second_type {
121                        Type::TypePath(_) => self.option_into_vals(),
122                        Type::Slice(ref second_type) => match **second_type {
123                            Type::TypePath(_) => self.option_into_vals(),
124                            ref f => unimplemented!("Unsupported: {:#?}", f),
125                        },
126                        _ => unimplemented!("Unsupported type encountered"),
127                    },
128                    Type::Vec(ref first_type) => match **first_type {
129                        Type::TypePath(_) => self.option_into_vals(),
130                        _ => unimplemented!("Unsupported type encountered"),
131                    },
132                    ref f => unimplemented!("Unsupported: {:#?}", f),
133                },
134                Type::Slice(ref second_type) => match **second_type {
135                    Type::TypePath(_) => self.copied_direct_vals(),
136                    ref f => unimplemented!("Unsupported: {:#?}", f),
137                },
138                ref f => unimplemented!("Unsupported: {:#?}", f),
139            },
140            Type::Vec(first_type) => match **first_type {
141                Type::TypePath(_) => self.copied_direct_vals(),
142                ref f => unimplemented!("Unsupported: {:#?}", f),
143            },
144            f => unimplemented!("Unsupported: {:#?}", f),
145        };
146
147        let definition_levels = match &self.ty {
148            Type::TypePath(_) => None,
149            Type::Option(first_type) => match **first_type {
150                Type::TypePath(_) => Some(self.optional_definition_levels()),
151                Type::Option(_) => unimplemented!("Unsupported nesting encountered"),
152                Type::Reference(_, ref second_type)
153                | Type::Vec(ref second_type)
154                | Type::Array(ref second_type, _)
155                | Type::Slice(ref second_type) => match **second_type {
156                    Type::TypePath(_) => Some(self.optional_definition_levels()),
157                    _ => unimplemented!("Unsupported nesting encountered"),
158                },
159            },
160            Type::Reference(_, first_type)
161            | Type::Vec(first_type)
162            | Type::Array(first_type, _)
163            | Type::Slice(first_type) => match **first_type {
164                Type::TypePath(_) => None,
165                Type::Vec(ref second_type)
166                | Type::Array(ref second_type, _)
167                | Type::Slice(ref second_type) => match **second_type {
168                    Type::TypePath(_) => None,
169                    Type::Reference(_, ref third_type) => match **third_type {
170                        Type::TypePath(_) => None,
171                        _ => unimplemented!("Unsupported definition encountered"),
172                    },
173                    _ => unimplemented!("Unsupported definition encountered"),
174                },
175                Type::Reference(_, ref second_type) | Type::Option(ref second_type) => {
176                    match **second_type {
177                        Type::TypePath(_) => Some(self.optional_definition_levels()),
178                        Type::Vec(ref third_type)
179                        | Type::Array(ref third_type, _)
180                        | Type::Slice(ref third_type) => match **third_type {
181                            Type::TypePath(_) => Some(self.optional_definition_levels()),
182                            Type::Reference(_, ref fourth_type) => match **fourth_type {
183                                Type::TypePath(_) => Some(self.optional_definition_levels()),
184                                _ => unimplemented!("Unsupported definition encountered"),
185                            },
186                            _ => unimplemented!("Unsupported definition encountered"),
187                        },
188                        Type::Reference(_, ref third_type) => match **third_type {
189                            Type::TypePath(_) => Some(self.optional_definition_levels()),
190                            Type::Slice(ref fourth_type) => match **fourth_type {
191                                Type::TypePath(_) => Some(self.optional_definition_levels()),
192                                _ => unimplemented!("Unsupported definition encountered"),
193                            },
194                            _ => unimplemented!("Unsupported definition encountered"),
195                        },
196                        Type::Option(_) => unimplemented!("Unsupported definition encountered"),
197                    }
198                }
199            },
200        };
201
202        // "vals" is the run of primitive data being written for the column
203        // "definition_levels" is a vector of bools which controls whether a value is missing or present
204        // this TokenStream is only one part of the code for writing a column and
205        // it relies on values calculated in prior code snippets, namely "definition_levels" and "vals_builder".
206        // All the context is put together in this functions final quote and
207        // this expression just switches between non-nullable and nullable write statements
208        let write_batch_expr = if definition_levels.is_some() {
209            quote! {
210                if let #column_writer(typed) = column_writer.untyped() {
211                    typed.write_batch(&vals[..], Some(&definition_levels[..]), None)?;
212                } else {
213                    panic!("Schema and struct disagree on type for {}", stringify!{#ident})
214                }
215            }
216        } else {
217            quote! {
218                if let #column_writer(typed) = column_writer.untyped() {
219                    typed.write_batch(&vals[..], None, None)?;
220                } else {
221                    panic!("Schema and struct disagree on type for {}", stringify!{#ident})
222                }
223            }
224        };
225
226        quote! {
227            {
228                #definition_levels
229
230                #vals_builder
231
232                #write_batch_expr
233            }
234        }
235    }
236
237    /// Takes the parsed field of the struct and emits a valid
238    /// column reader snippet. Should match exactly what you
239    /// would write by hand.
240    ///
241    /// Can only generate writers for basic structs, for example:
242    ///
243    /// struct Record {
244    ///   a_bool: bool
245    /// }
246    ///
247    /// but not
248    ///
249    /// struct UnsupportedNestedRecord {
250    ///   a_property: bool,
251    ///   nested_record: Record
252    /// }
253    ///
254    /// because this parsing logic is not sophisticated enough for definition
255    /// levels beyond 2.
256    ///
257    /// `Option` types and references not supported, but the column itself can be nullable
258    /// (i.e., def_level==1), as long as the values are all valid.
259    pub fn reader_snippet(&self) -> proc_macro2::TokenStream {
260        let ident = &self.ident;
261        let column_reader = self.ty.column_reader();
262
263        // generate the code to read the column into a vector `vals`
264        let write_batch_expr = quote! {
265            let mut vals = Vec::new();
266            if let #column_reader(mut typed) = column_reader {
267                let mut definition_levels = Vec::new();
268                let (total_num, valid_num, decoded_num) = typed.read_records(
269                    num_records, Some(&mut definition_levels), None, &mut vals)?;
270                if valid_num != decoded_num {
271                    panic!("Support only valid records, found {} null records in column type {}",
272                        decoded_num - valid_num, stringify!{#ident});
273                }
274            } else {
275                panic!("Schema and struct disagree on type for {}", stringify!{#ident});
276            }
277        };
278
279        // generate the code to convert each element of `vals` to the correct type and then write
280        // it to its field in the corresponding struct
281        let vals_writer = match &self.ty {
282            Type::TypePath(_) => self.copied_direct_fields(),
283            Type::Reference(_, first_type) => match **first_type {
284                Type::TypePath(_) => self.copied_direct_fields(),
285                Type::Slice(ref second_type) => match **second_type {
286                    Type::TypePath(_) => self.copied_direct_fields(),
287                    ref f => unimplemented!("Unsupported: {:#?}", f),
288                },
289                ref f => unimplemented!("Unsupported: {:#?}", f),
290            },
291            Type::Vec(first_type) => match **first_type {
292                Type::TypePath(_) => self.copied_direct_fields(),
293                ref f => unimplemented!("Unsupported: {:#?}", f),
294            },
295            f => unimplemented!("Unsupported: {:#?}", f),
296        };
297
298        quote! {
299            {
300                #write_batch_expr
301
302                #vals_writer
303            }
304        }
305    }
306
307    pub fn parquet_type(&self) -> proc_macro2::TokenStream {
308        // TODO: Support group types
309        // TODO: Add length if dealing with fixedlenbinary
310
311        // unraw the identifier, so a raw identifier like `r#type`
312        // becomes a column named `type` in the parquet schema
313        let field_name = self.ident.unraw().to_string();
314        let physical_type = match self.ty.physical_type() {
315            PhysicalType::Boolean => quote! {
316                ::parquet::basic::Type::BOOLEAN
317            },
318            PhysicalType::Int32 => quote! {
319                ::parquet::basic::Type::INT32
320            },
321            PhysicalType::Int64 => quote! {
322                ::parquet::basic::Type::INT64
323            },
324            PhysicalType::Float => quote! {
325                ::parquet::basic::Type::FLOAT
326            },
327            PhysicalType::Double => quote! {
328                ::parquet::basic::Type::DOUBLE
329            },
330            PhysicalType::ByteArray => quote! {
331                ::parquet::basic::Type::BYTE_ARRAY
332            },
333            PhysicalType::FixedLenByteArray => quote! {
334                ::parquet::basic::Type::FIXED_LEN_BYTE_ARRAY
335            },
336        };
337        let logical_type = self.ty.logical_type();
338        let repetition = self.ty.repetition();
339        let converted_type = self.ty.converted_type();
340        let length = self.ty.length();
341
342        let mut builder = quote! {
343            ParquetType::primitive_type_builder(#field_name, #physical_type)
344                .with_logical_type(#logical_type)
345                .with_repetition(#repetition)
346        };
347
348        if let Some(converted_type) = converted_type {
349            builder = quote! { #builder.with_converted_type(#converted_type) };
350        }
351
352        if let Some(length) = length {
353            builder = quote! { #builder.with_length(#length) };
354        }
355
356        quote! {  fields.push(#builder.build().unwrap().into()) }
357    }
358
359    fn option_into_vals(&self) -> proc_macro2::TokenStream {
360        let field_name = &self.ident;
361        let is_a_byte_buf = self.is_a_byte_buf;
362        let is_a_timestamp = self.third_party_type == Some(ThirdPartyType::ChronoNaiveDateTime);
363        let is_a_date = self.third_party_type == Some(ThirdPartyType::ChronoNaiveDate);
364        let is_a_uuid = self.third_party_type == Some(ThirdPartyType::Uuid);
365        let copy_to_vec = !matches!(
366            self.ty.physical_type(),
367            PhysicalType::ByteArray | PhysicalType::FixedLenByteArray
368        );
369
370        let binding = if copy_to_vec {
371            quote! { let Some(inner) = rec.#field_name }
372        } else {
373            quote! { let Some(inner) = &rec.#field_name }
374        };
375
376        let some = if is_a_timestamp {
377            quote! { Some(inner.timestamp_millis()) }
378        } else if is_a_date {
379            quote! { Some(inner.signed_duration_since(::chrono::NaiveDate::from_ymd(1970, 1, 1)).num_days() as i32)  }
380        } else if is_a_uuid {
381            quote! { Some((&inner.to_string()[..]).into()) }
382        } else if is_a_byte_buf {
383            quote! { Some((&inner[..]).into())}
384        } else {
385            // Type might need converting to a physical type
386            match self.ty.physical_type() {
387                PhysicalType::Int32 => quote! { Some(inner as i32) },
388                PhysicalType::Int64 => quote! { Some(inner as i64) },
389                _ => quote! { Some(inner) },
390            }
391        };
392
393        quote! {
394            let vals: Vec<_> = records.iter().filter_map(|rec| {
395                if #binding {
396                    #some
397                } else {
398                    None
399                }
400            }).collect();
401        }
402    }
403
404    // generates code to read `field_name` from each record into a vector `vals`
405    fn copied_direct_vals(&self) -> proc_macro2::TokenStream {
406        let field_name = &self.ident;
407
408        let access = match self.third_party_type {
409            Some(ThirdPartyType::ChronoNaiveDateTime) => {
410                quote! { rec.#field_name.timestamp_millis() }
411            }
412            Some(ThirdPartyType::ChronoNaiveDate) => {
413                quote! { rec.#field_name.signed_duration_since(::chrono::NaiveDate::from_ymd(1970, 1, 1)).num_days() as i32 }
414            }
415            Some(ThirdPartyType::Uuid) => {
416                quote! { rec.#field_name.as_bytes().to_vec().into() }
417            }
418            _ => {
419                if self.is_a_byte_buf {
420                    quote! { (&rec.#field_name[..]).into() }
421                } else {
422                    // Type might need converting to a physical type
423                    match self.ty.physical_type() {
424                        PhysicalType::Int32 => quote! { rec.#field_name as i32 },
425                        PhysicalType::Int64 => quote! { rec.#field_name as i64 },
426                        _ => quote! { rec.#field_name },
427                    }
428                }
429            }
430        };
431
432        quote! {
433            let vals: Vec<_> = records.iter().map(|rec| #access).collect();
434        }
435    }
436
437    // generates code to read a vector `records` into `field_name` for each record
438    fn copied_direct_fields(&self) -> proc_macro2::TokenStream {
439        let field_name = &self.ident;
440
441        let value = match self.third_party_type {
442            Some(ThirdPartyType::ChronoNaiveDateTime) => {
443                quote! { ::chrono::naive::NaiveDateTime::from_timestamp_millis(vals[i]).unwrap() }
444            }
445            Some(ThirdPartyType::ChronoNaiveDate) => {
446                // NaiveDateTime::UNIX_EPOCH.num_days_from_ce() == 719163
447                quote! {
448                    ::chrono::naive::NaiveDate::from_num_days_from_ce_opt(vals[i].saturating_add(719163)).unwrap()
449                }
450            }
451            Some(ThirdPartyType::Uuid) => {
452                quote! { ::uuid::Uuid::from_bytes(vals[i].data().try_into().unwrap()) }
453            }
454            _ => match &self.ty {
455                Type::TypePath(_) => match self.ty.last_part().as_str() {
456                    "String" => quote! { String::from(std::str::from_utf8(vals[i].data())
457                    .expect("invalid UTF-8 sequence")) },
458                    t => {
459                        let s: proc_macro2::TokenStream = t.parse().unwrap();
460                        quote! { vals[i] as #s }
461                    }
462                },
463                Type::Vec(_) => quote! { vals[i].data().to_vec() },
464                f => unimplemented!("Unsupported: {:#?}", f),
465            },
466        };
467
468        quote! {
469            for (i, r) in &mut records[..num_records].iter_mut().enumerate() {
470                r.#field_name = #value;
471            }
472        }
473    }
474
475    fn optional_definition_levels(&self) -> proc_macro2::TokenStream {
476        let field_name = &self.ident;
477
478        quote! {
479            let definition_levels: Vec<i16> = self
480              .iter()
481              .map(|rec| if rec.#field_name.is_some() { 1 } else { 0 })
482              .collect();
483        }
484    }
485}
486
487#[expect(clippy::enum_variant_names)]
488#[derive(Debug, PartialEq)]
489enum Type {
490    Array(Box<Type>, syn::Expr),
491    Option(Box<Type>),
492    Slice(Box<Type>),
493    Vec(Box<Type>),
494    TypePath(syn::Type),
495    Reference(Option<syn::Lifetime>, Box<Type>),
496}
497
498impl Type {
499    /// Takes a rust type and returns the appropriate
500    /// parquet-rs column writer
501    fn column_writer(&self) -> syn::TypePath {
502        match self.physical_type() {
503            PhysicalType::Boolean => {
504                syn::parse_quote!(ColumnWriter::BoolColumnWriter)
505            }
506            PhysicalType::Int32 => syn::parse_quote!(ColumnWriter::Int32ColumnWriter),
507            PhysicalType::Int64 => syn::parse_quote!(ColumnWriter::Int64ColumnWriter),
508            PhysicalType::Float => syn::parse_quote!(ColumnWriter::FloatColumnWriter),
509            PhysicalType::Double => syn::parse_quote!(ColumnWriter::DoubleColumnWriter),
510            PhysicalType::ByteArray => {
511                syn::parse_quote!(ColumnWriter::ByteArrayColumnWriter)
512            }
513            PhysicalType::FixedLenByteArray => {
514                syn::parse_quote!(ColumnWriter::FixedLenByteArrayColumnWriter)
515            }
516        }
517    }
518
519    /// Takes a rust type and returns the appropriate
520    /// parquet-rs column reader
521    fn column_reader(&self) -> syn::TypePath {
522        match self.physical_type() {
523            PhysicalType::Boolean => {
524                syn::parse_quote!(ColumnReader::BoolColumnReader)
525            }
526            PhysicalType::Int32 => syn::parse_quote!(ColumnReader::Int32ColumnReader),
527            PhysicalType::Int64 => syn::parse_quote!(ColumnReader::Int64ColumnReader),
528            PhysicalType::Float => syn::parse_quote!(ColumnReader::FloatColumnReader),
529            PhysicalType::Double => syn::parse_quote!(ColumnReader::DoubleColumnReader),
530            PhysicalType::ByteArray => {
531                syn::parse_quote!(ColumnReader::ByteArrayColumnReader)
532            }
533            PhysicalType::FixedLenByteArray => {
534                syn::parse_quote!(ColumnReader::FixedLenByteArrayColumnReader)
535            }
536        }
537    }
538
539    /// Helper to simplify a nested field definition to its leaf type
540    ///
541    /// Ex:
542    ///   `Option<&String>` => Type::TypePath(String)
543    ///   `&Option<i32>` => Type::TypePath(i32)
544    ///   `Vec<Vec<u8>>` => Type::Vec(u8)
545    ///
546    /// Useful in determining the physical type of a field and the
547    /// definition levels.
548    fn leaf_type_recursive(&self) -> &Type {
549        Type::leaf_type_recursive_helper(self, None)
550    }
551
552    fn leaf_type_recursive_helper<'a>(ty: &'a Type, parent_ty: Option<&'a Type>) -> &'a Type {
553        match ty {
554            Type::TypePath(_) => parent_ty.unwrap_or(ty),
555            Type::Option(first_type)
556            | Type::Vec(first_type)
557            | Type::Array(first_type, _)
558            | Type::Slice(first_type)
559            | Type::Reference(_, first_type) => {
560                Type::leaf_type_recursive_helper(first_type, Some(ty))
561            }
562        }
563    }
564
565    /// Helper method to further unwrap leaf_type() to get inner-most
566    /// type information, useful for determining the physical type
567    /// and normalizing the type paths.
568    fn inner_type(&self) -> &syn::Type {
569        let leaf_type = self.leaf_type_recursive();
570
571        match leaf_type {
572            Type::TypePath(type_) => type_,
573            Type::Option(first_type)
574            | Type::Vec(first_type)
575            | Type::Array(first_type, _)
576            | Type::Slice(first_type)
577            | Type::Reference(_, first_type) => match **first_type {
578                Type::TypePath(ref type_) => type_,
579                _ => unimplemented!("leaf_type() should only return shallow types"),
580            },
581        }
582    }
583
584    /// Helper to normalize a type path by extracting the
585    /// most identifiable part
586    ///
587    /// Ex:
588    ///   std::string::String => String
589    ///   `Vec<u8>` => `Vec<u8>`
590    ///   chrono::NaiveDateTime => NaiveDateTime
591    ///
592    /// Does run the risk of mis-identifying a type if import
593    /// rename is in play. Please note procedural macros always
594    /// run before type resolution so this is a risk the user
595    /// takes on when renaming imports.
596    fn last_part(&self) -> String {
597        let inner_type = self.inner_type();
598        let inner_type_str = (quote! { #inner_type }).to_string();
599
600        inner_type_str
601            .split("::")
602            .last()
603            .unwrap()
604            .trim()
605            .to_string()
606    }
607
608    /// Converts rust types to parquet physical types.
609    ///
610    /// Ex:
611    ///   [u8; 10] => FIXED_LEN_BYTE_ARRAY
612    ///   `Vec<u8>`  => BYTE_ARRAY
613    ///   String => BYTE_ARRAY
614    ///   i32 => INT32
615    fn physical_type(&self) -> PhysicalType {
616        let last_part = self.last_part();
617        let leaf_type = self.leaf_type_recursive();
618
619        match leaf_type {
620            Type::Array(first_type, _length) => {
621                if let Type::TypePath(_) = **first_type
622                    && last_part == "u8"
623                {
624                    return PhysicalType::FixedLenByteArray;
625                }
626            }
627            Type::Vec(first_type) | Type::Slice(first_type) => {
628                if let Type::TypePath(_) = **first_type
629                    && last_part == "u8"
630                {
631                    return PhysicalType::ByteArray;
632                }
633            }
634            _ => (),
635        }
636
637        match last_part.trim() {
638            "bool" => PhysicalType::Boolean,
639            "u8" | "u16" | "u32" => PhysicalType::Int32,
640            "i8" | "i16" | "i32" | "NaiveDate" => PhysicalType::Int32,
641            "u64" | "i64" | "NaiveDateTime" => PhysicalType::Int64,
642            "usize" | "isize" => {
643                if usize::BITS == 64 {
644                    PhysicalType::Int64
645                } else {
646                    PhysicalType::Int32
647                }
648            }
649            "f32" => PhysicalType::Float,
650            "f64" => PhysicalType::Double,
651            "String" | "str" | "Arc < str >" => PhysicalType::ByteArray,
652            "Uuid" => PhysicalType::FixedLenByteArray,
653            f => unimplemented!("{} currently is not supported", f),
654        }
655    }
656
657    fn length(&self) -> Option<syn::Expr> {
658        let last_part = self.last_part();
659        let leaf_type = self.leaf_type_recursive();
660
661        // `[u8; N]` => Some(N)
662        if let Type::Array(first_type, length) = leaf_type
663            && let Type::TypePath(_) = **first_type
664            && last_part == "u8"
665        {
666            return Some(length.clone());
667        }
668
669        match last_part.trim() {
670            // Uuid => [u8; 16] => Some(16)
671            "Uuid" => Some(syn::parse_quote!(16)),
672            _ => None,
673        }
674    }
675
676    fn logical_type(&self) -> proc_macro2::TokenStream {
677        let last_part = self.last_part();
678        let leaf_type = self.leaf_type_recursive();
679
680        match leaf_type {
681            Type::Array(first_type, _length) => {
682                if let Type::TypePath(_) = **first_type
683                    && last_part == "u8"
684                {
685                    return quote! { None };
686                }
687            }
688            Type::Vec(first_type) | Type::Slice(first_type) => {
689                if let Type::TypePath(_) = **first_type
690                    && last_part == "u8"
691                {
692                    return quote! { None };
693                }
694            }
695            _ => (),
696        }
697
698        match last_part.trim() {
699            "bool" => quote! { None },
700            "u8" => quote! { Some(LogicalType::integer(8, false)) },
701            "u16" => quote! { Some(LogicalType::integer(16, false)) },
702            "u32" => quote! { Some(LogicalType::integer(32, false)) },
703            "u64" => quote! { Some(LogicalType::integer(64, false)) },
704            "i8" => quote! { Some(LogicalType::integer(8, true)) },
705            "i16" => quote! { Some(LogicalType::integer(16, true)) },
706            "i32" | "i64" => quote! { None },
707            "usize" => {
708                quote! { Some(LogicalType::integer(usize::BITS as i8, false)) }
709            }
710            "isize" => {
711                quote! { Some(LogicalType::integer(usize::BITS as i8, true)) }
712            }
713            "NaiveDate" => quote! { Some(LogicalType::Date) },
714            "NaiveDateTime" => quote! { None },
715            "f32" | "f64" => quote! { None },
716            "String" | "str" | "Arc < str >" => quote! { Some(LogicalType::String) },
717            "Uuid" => quote! { Some(LogicalType::Uuid) },
718            f => unimplemented!("{} currently is not supported", f),
719        }
720    }
721
722    fn converted_type(&self) -> Option<proc_macro2::TokenStream> {
723        let last_part = self.last_part();
724
725        match last_part.trim() {
726            "NaiveDateTime" => Some(quote! { ::parquet::basic::ConvertedType::TIMESTAMP_MILLIS }),
727            _ => None,
728        }
729    }
730
731    fn repetition(&self) -> proc_macro2::TokenStream {
732        match self {
733            Type::Option(_) => quote! { ::parquet::basic::Repetition::OPTIONAL },
734            Type::Reference(_, ty) => ty.repetition(),
735            _ => quote! { ::parquet::basic::Repetition::REQUIRED },
736        }
737    }
738
739    /// Convert a parsed rust field AST in to a more easy to manipulate
740    /// parquet_derive::Field
741    fn from(f: &syn::Field) -> Self {
742        Type::from_type(f, &f.ty)
743    }
744
745    fn from_type(f: &syn::Field, ty: &syn::Type) -> Self {
746        match ty {
747            syn::Type::Path(p) => Type::from_type_path(f, p),
748            syn::Type::Reference(tr) => Type::from_type_reference(f, tr),
749            syn::Type::Array(ta) => Type::from_type_array(f, ta),
750            syn::Type::Slice(ts) => Type::from_type_slice(f, ts),
751            other => unimplemented!(
752                "Unable to derive {:?} - it is currently an unsupported type\n{:#?}",
753                f.ident.as_ref().unwrap(),
754                other
755            ),
756        }
757    }
758
759    fn from_type_path(f: &syn::Field, p: &syn::TypePath) -> Self {
760        let last_segment = p.path.segments.last().unwrap();
761
762        let is_vec = last_segment.ident == syn::Ident::new("Vec", proc_macro2::Span::call_site());
763        let is_option =
764            last_segment.ident == syn::Ident::new("Option", proc_macro2::Span::call_site());
765
766        if is_vec || is_option {
767            let generic_type = match &last_segment.arguments {
768                syn::PathArguments::AngleBracketed(angle_args) => {
769                    assert_eq!(angle_args.args.len(), 1);
770                    let first_arg = &angle_args.args[0];
771
772                    match first_arg {
773                        syn::GenericArgument::Type(typath) => typath.clone(),
774                        other => unimplemented!("Unsupported: {:#?}", other),
775                    }
776                }
777                other => unimplemented!("Unsupported: {:#?}", other),
778            };
779
780            if is_vec {
781                Type::Vec(Box::new(Type::from_type(f, &generic_type)))
782            } else {
783                Type::Option(Box::new(Type::from_type(f, &generic_type)))
784            }
785        } else {
786            Type::TypePath(syn::Type::Path(p.clone()))
787        }
788    }
789
790    fn from_type_reference(f: &syn::Field, tr: &syn::TypeReference) -> Self {
791        let lifetime = tr.lifetime.clone();
792        let inner_type = Type::from_type(f, tr.elem.as_ref());
793        Type::Reference(lifetime, Box::new(inner_type))
794    }
795
796    fn from_type_array(f: &syn::Field, ta: &syn::TypeArray) -> Self {
797        let inner_type = Type::from_type(f, ta.elem.as_ref());
798        Type::Array(Box::new(inner_type), ta.len.clone())
799    }
800
801    fn from_type_slice(f: &syn::Field, ts: &syn::TypeSlice) -> Self {
802        let inner_type = Type::from_type(f, ts.elem.as_ref());
803        Type::Slice(Box::new(inner_type))
804    }
805}
806
807#[cfg(test)]
808mod test {
809    use super::*;
810    use syn::{Data, DataStruct, DeriveInput};
811
812    fn extract_fields(input: proc_macro2::TokenStream) -> Vec<syn::Field> {
813        let input: DeriveInput = syn::parse2(input).unwrap();
814
815        let Data::Struct(DataStruct { fields, .. }) = input.data else {
816            panic!("Input must be a struct")
817        };
818
819        fields.iter().map(|field| field.to_owned()).collect()
820    }
821
822    #[test]
823    fn test_generating_a_simple_writer_snippet() {
824        let snippet: proc_macro2::TokenStream = quote! {
825          struct ABoringStruct {
826            counter: usize,
827          }
828        };
829
830        let fields = extract_fields(snippet);
831        let counter = Field::from(&fields[0]);
832
833        let snippet = counter.writer_snippet().to_string();
834        assert_eq!(snippet,
835                   (quote!{
836                        {
837                            let vals : Vec < _ > = records . iter ( ) . map ( | rec | rec . counter as i64 ) . collect ( );
838
839                            if let ColumnWriter::Int64ColumnWriter ( typed ) = column_writer.untyped() {
840                                typed . write_batch ( & vals [ .. ] , None , None ) ?;
841                            }  else {
842                                panic!("Schema and struct disagree on type for {}" , stringify!{ counter } )
843                            }
844                        }
845                   }).to_string()
846        )
847    }
848
849    #[test]
850    fn test_generating_a_simple_reader_snippet() {
851        let snippet: proc_macro2::TokenStream = quote! {
852          struct ABoringStruct {
853            counter: usize,
854          }
855        };
856
857        let fields = extract_fields(snippet);
858        let counter = Field::from(&fields[0]);
859
860        let snippet = counter.reader_snippet().to_string();
861        assert_eq!(
862            snippet,
863            (quote! {
864                 {
865                    let mut vals = Vec::new();
866                    if let ColumnReader::Int64ColumnReader(mut typed) = column_reader {
867                        let mut definition_levels = Vec::new();
868                        let (total_num, valid_num, decoded_num) = typed.read_records(
869                            num_records, Some(&mut definition_levels), None, &mut vals)?;
870                        if valid_num != decoded_num {
871                            panic!("Support only valid records, found {} null records in column type {}",
872                                decoded_num - valid_num, stringify!{counter});
873                        }
874                    } else {
875                        panic!("Schema and struct disagree on type for {}", stringify!{counter});
876                    }
877                    for (i, r) in &mut records[..num_records].iter_mut().enumerate() {
878                        r.counter = vals[i] as usize;
879                    }
880                 }
881            })
882            .to_string()
883        )
884    }
885
886    #[test]
887    fn test_parquet_type_with_raw_identifier() {
888        let snippet: proc_macro2::TokenStream = quote! {
889          struct ABoringStruct {
890            r#type: i32,
891          }
892        };
893
894        let fields = extract_fields(snippet);
895        let r#type = Field::from(&fields[0]);
896
897        // the raw identifier `r#type` is named `type` in the parquet schema
898        let snippet = r#type.parquet_type().to_string();
899        assert!(
900            snippet.contains("primitive_type_builder (\"type\""),
901            "{snippet}"
902        );
903    }
904
905    #[test]
906    fn test_optional_to_writer_snippet() {
907        let struct_def: proc_macro2::TokenStream = quote! {
908          struct StringBorrower<'a> {
909            optional_str: Option<&'a str>,
910            optional_string: Option<&String>,
911            optional_dumb_int: Option<&i32>,
912          }
913        };
914
915        let fields = extract_fields(struct_def);
916
917        let optional = Field::from(&fields[0]);
918        let snippet = optional.writer_snippet();
919        assert_eq!(snippet.to_string(),
920          (quote! {
921          {
922                let definition_levels : Vec < i16 > = self . iter ( ) . map ( | rec | if rec . optional_str . is_some ( ) { 1 } else { 0 } ) . collect ( ) ;
923
924                let vals: Vec <_> = records.iter().filter_map( |rec| {
925                    if let Some ( inner ) = &rec . optional_str {
926                        Some ( (&inner[..]).into() )
927                    } else {
928                        None
929                    }
930                }).collect();
931
932                if let ColumnWriter::ByteArrayColumnWriter ( typed ) = column_writer.untyped() {
933                    typed . write_batch ( & vals [ .. ] , Some(&definition_levels[..]) , None ) ? ;
934                } else {
935                    panic!("Schema and struct disagree on type for {}" , stringify ! { optional_str } )
936                }
937           }
938            }
939          ).to_string());
940
941        let optional = Field::from(&fields[1]);
942        let snippet = optional.writer_snippet();
943        assert_eq!(snippet.to_string(),
944                   (quote!{
945                   {
946                        let definition_levels : Vec < i16 > = self . iter ( ) . map ( | rec | if rec . optional_string . is_some ( ) { 1 } else { 0 } ) . collect ( ) ;
947
948                        let vals: Vec <_> = records.iter().filter_map( |rec| {
949                            if let Some ( inner ) = &rec . optional_string {
950                                Some ( (&inner[..]).into() )
951                            } else {
952                                None
953                            }
954                        }).collect();
955
956                        if let ColumnWriter::ByteArrayColumnWriter ( typed ) = column_writer.untyped() {
957                            typed . write_batch ( & vals [ .. ] , Some(&definition_levels[..]) , None ) ? ;
958                        } else {
959                            panic!("Schema and struct disagree on type for {}" , stringify ! { optional_string } )
960                        }
961                    }
962        }).to_string());
963
964        let optional = Field::from(&fields[2]);
965        let snippet = optional.writer_snippet();
966        assert_eq!(snippet.to_string(),
967                   (quote!{
968                    {
969                        let definition_levels : Vec < i16 > = self . iter ( ) . map ( | rec | if rec . optional_dumb_int . is_some ( ) { 1 } else { 0 } ) . collect ( ) ;
970
971                        let vals: Vec <_> = records.iter().filter_map( |rec| {
972                            if let Some ( inner ) = rec . optional_dumb_int {
973                                Some ( inner as i32 )
974                            } else {
975                                None
976                            }
977                        }).collect();
978
979                        if let ColumnWriter::Int32ColumnWriter ( typed ) = column_writer.untyped() {
980                            typed . write_batch ( & vals [ .. ] , Some(&definition_levels[..]) , None ) ? ;
981                        }  else {
982                            panic!("Schema and struct disagree on type for {}" , stringify ! { optional_dumb_int } )
983                        }
984                    }
985        }).to_string());
986    }
987
988    #[test]
989    fn test_converting_to_column_writer_type() {
990        let snippet: proc_macro2::TokenStream = quote! {
991          struct ABasicStruct {
992            yes_no: bool,
993            name: String,
994          }
995        };
996
997        let fields = extract_fields(snippet);
998        let processed: Vec<_> = fields.iter().map(Field::from).collect();
999
1000        let column_writers: Vec<_> = processed
1001            .iter()
1002            .map(|field| field.ty.column_writer())
1003            .collect();
1004
1005        assert_eq!(
1006            column_writers,
1007            vec![
1008                syn::parse_quote!(ColumnWriter::BoolColumnWriter),
1009                syn::parse_quote!(ColumnWriter::ByteArrayColumnWriter)
1010            ]
1011        );
1012    }
1013
1014    #[test]
1015    fn test_converting_to_column_reader_type() {
1016        let snippet: proc_macro2::TokenStream = quote! {
1017          struct ABasicStruct {
1018            yes_no: bool,
1019            name: String,
1020          }
1021        };
1022
1023        let fields = extract_fields(snippet);
1024        let processed: Vec<_> = fields.iter().map(Field::from).collect();
1025
1026        let column_readers: Vec<_> = processed
1027            .iter()
1028            .map(|field| field.ty.column_reader())
1029            .collect();
1030
1031        assert_eq!(
1032            column_readers,
1033            vec![
1034                syn::parse_quote!(ColumnReader::BoolColumnReader),
1035                syn::parse_quote!(ColumnReader::ByteArrayColumnReader)
1036            ]
1037        );
1038    }
1039
1040    #[test]
1041    fn convert_basic_struct() {
1042        let snippet: proc_macro2::TokenStream = quote! {
1043          struct ABasicStruct {
1044            yes_no: bool,
1045            name: String,
1046            length: usize
1047          }
1048        };
1049
1050        let fields = extract_fields(snippet);
1051        let processed: Vec<_> = fields.iter().map(Field::from).collect();
1052        assert_eq!(processed.len(), 3);
1053
1054        assert_eq!(
1055            processed,
1056            vec![
1057                Field {
1058                    ident: syn::Ident::new("yes_no", proc_macro2::Span::call_site()),
1059                    ty: Type::TypePath(syn::parse_quote!(bool)),
1060                    is_a_byte_buf: false,
1061                    third_party_type: None,
1062                },
1063                Field {
1064                    ident: syn::Ident::new("name", proc_macro2::Span::call_site()),
1065                    ty: Type::TypePath(syn::parse_quote!(String)),
1066                    is_a_byte_buf: true,
1067                    third_party_type: None,
1068                },
1069                Field {
1070                    ident: syn::Ident::new("length", proc_macro2::Span::call_site()),
1071                    ty: Type::TypePath(syn::parse_quote!(usize)),
1072                    is_a_byte_buf: false,
1073                    third_party_type: None,
1074                }
1075            ]
1076        )
1077    }
1078
1079    #[test]
1080    fn test_get_inner_type() {
1081        let snippet: proc_macro2::TokenStream = quote! {
1082          struct LotsOfInnerTypes {
1083            a_vec: Vec<u8>,
1084            a_option: ::std::option::Option<bool>,
1085            a_silly_string: ::std::string::String,
1086            a_complicated_thing: ::std::option::Option<::std::result::Result<(),()>>,
1087          }
1088        };
1089
1090        let fields = extract_fields(snippet);
1091        let converted_fields: Vec<_> = fields.iter().map(Type::from).collect();
1092        let inner_types: Vec<_> = converted_fields
1093            .iter()
1094            .map(|field| field.inner_type())
1095            .collect();
1096        let inner_types_strs: Vec<_> = inner_types
1097            .iter()
1098            .map(|ty| (quote! { #ty }).to_string())
1099            .collect();
1100
1101        assert_eq!(
1102            inner_types_strs,
1103            vec![
1104                "u8",
1105                "bool",
1106                ":: std :: string :: String",
1107                ":: std :: result :: Result < () , () >"
1108            ]
1109        )
1110    }
1111
1112    #[test]
1113    fn test_physical_type() {
1114        let snippet: proc_macro2::TokenStream = quote! {
1115          struct LotsOfInnerTypes {
1116            a_buf: ::std::vec::Vec<u8>,
1117            a_number: i32,
1118            a_verbose_option: ::std::option::Option<bool>,
1119            a_silly_string: String,
1120            a_fix_byte_buf: [u8; 10],
1121            a_complex_option: ::std::option::Option<&Vec<u8>>,
1122            a_complex_vec: &::std::vec::Vec<&Option<u8>>,
1123            a_uuid: ::uuid::Uuid,
1124          }
1125        };
1126
1127        let fields = extract_fields(snippet);
1128        let converted_fields: Vec<_> = fields.iter().map(Type::from).collect();
1129        let physical_types: Vec<_> = converted_fields
1130            .iter()
1131            .map(|ty| ty.physical_type())
1132            .collect();
1133
1134        assert_eq!(
1135            physical_types,
1136            vec![
1137                PhysicalType::ByteArray,
1138                PhysicalType::Int32,
1139                PhysicalType::Boolean,
1140                PhysicalType::ByteArray,
1141                PhysicalType::FixedLenByteArray,
1142                PhysicalType::ByteArray,
1143                PhysicalType::Int32,
1144                PhysicalType::FixedLenByteArray,
1145            ]
1146        )
1147    }
1148
1149    #[test]
1150    fn test_type_length() {
1151        let snippet: proc_macro2::TokenStream = quote! {
1152          struct LotsOfInnerTypes {
1153            a_buf: ::std::vec::Vec<u8>,
1154            a_number: i32,
1155            a_verbose_option: ::std::option::Option<bool>,
1156            a_silly_string: String,
1157            a_fix_byte_buf: [u8; 10],
1158            a_complex_option: ::std::option::Option<&Vec<u8>>,
1159            a_complex_vec: &::std::vec::Vec<&Option<u8>>,
1160            a_uuid: ::uuid::Uuid,
1161          }
1162        };
1163
1164        let fields = extract_fields(snippet);
1165        let converted_fields: Vec<_> = fields.iter().map(Type::from).collect();
1166        let lengths: Vec<_> = converted_fields.iter().map(|ty| ty.length()).collect();
1167
1168        assert_eq!(
1169            lengths,
1170            vec![
1171                None,
1172                None,
1173                None,
1174                None,
1175                Some(syn::parse_quote!(10)),
1176                None,
1177                None,
1178                Some(syn::parse_quote!(16)),
1179            ]
1180        )
1181    }
1182
1183    #[test]
1184    fn test_convert_comprehensive_owned_struct() {
1185        let snippet: proc_macro2::TokenStream = quote! {
1186          struct VecHolder {
1187            a_vec: ::std::vec::Vec<u8>,
1188            a_option: ::std::option::Option<bool>,
1189            a_silly_string: ::std::string::String,
1190            a_complicated_thing: ::std::option::Option<::std::result::Result<(),()>>,
1191          }
1192        };
1193
1194        let fields = extract_fields(snippet);
1195        let converted_fields: Vec<_> = fields.iter().map(Type::from).collect();
1196
1197        assert_eq!(
1198            converted_fields,
1199            vec![
1200                Type::Vec(Box::new(Type::TypePath(syn::parse_quote!(u8)))),
1201                Type::Option(Box::new(Type::TypePath(syn::parse_quote!(bool)))),
1202                Type::TypePath(syn::parse_quote!(::std::string::String)),
1203                Type::Option(Box::new(Type::TypePath(
1204                    syn::parse_quote!(::std::result::Result<(),()>)
1205                ))),
1206            ]
1207        );
1208    }
1209
1210    #[test]
1211    fn test_convert_borrowed_struct() {
1212        let snippet: proc_macro2::TokenStream = quote! {
1213          struct Borrower<'a> {
1214            a_str: &'a str,
1215            a_borrowed_option: &'a Option<bool>,
1216            so_many_borrows: &'a Option<&'a str>,
1217          }
1218        };
1219
1220        let fields = extract_fields(snippet);
1221        let types: Vec<_> = fields.iter().map(Type::from).collect();
1222
1223        assert_eq!(
1224            types,
1225            vec![
1226                Type::Reference(
1227                    Some(syn::Lifetime::new("'a", proc_macro2::Span::call_site())),
1228                    Box::new(Type::TypePath(syn::parse_quote!(str)))
1229                ),
1230                Type::Reference(
1231                    Some(syn::Lifetime::new("'a", proc_macro2::Span::call_site())),
1232                    Box::new(Type::Option(Box::new(Type::TypePath(syn::parse_quote!(
1233                        bool
1234                    )))))
1235                ),
1236                Type::Reference(
1237                    Some(syn::Lifetime::new("'a", proc_macro2::Span::call_site())),
1238                    Box::new(Type::Option(Box::new(Type::Reference(
1239                        Some(syn::Lifetime::new("'a", proc_macro2::Span::call_site())),
1240                        Box::new(Type::TypePath(syn::parse_quote!(str)))
1241                    ))))
1242                ),
1243            ]
1244        );
1245    }
1246
1247    #[test]
1248    fn test_chrono_timestamp_millis_write() {
1249        let snippet: proc_macro2::TokenStream = quote! {
1250          struct ATimestampStruct {
1251            henceforth: chrono::NaiveDateTime,
1252            maybe_happened: Option<&chrono::NaiveDateTime>,
1253          }
1254        };
1255
1256        let fields = extract_fields(snippet);
1257        let when = Field::from(&fields[0]);
1258        assert_eq!(when.writer_snippet().to_string(),(quote!{
1259            {
1260                let vals : Vec<_> = records.iter().map(|rec| rec.henceforth.timestamp_millis() ).collect();
1261                if let ColumnWriter::Int64ColumnWriter(typed) = column_writer.untyped() {
1262                    typed.write_batch(&vals[..], None, None) ?;
1263                } else {
1264                    panic!("Schema and struct disagree on type for {}" , stringify!{ henceforth })
1265                }
1266            }
1267        }).to_string());
1268
1269        let maybe_happened = Field::from(&fields[1]);
1270        assert_eq!(maybe_happened.writer_snippet().to_string(),(quote!{
1271            {
1272                let definition_levels : Vec<i16> = self.iter().map(|rec| if rec.maybe_happened.is_some() { 1 } else { 0 }).collect();
1273                let vals : Vec<_> = records.iter().filter_map(|rec| {
1274                    if let Some(inner) = rec.maybe_happened {
1275                        Some(inner.timestamp_millis())
1276                    } else {
1277                        None
1278                    }
1279                }).collect();
1280
1281                if let ColumnWriter::Int64ColumnWriter(typed) = column_writer.untyped() {
1282                    typed.write_batch(&vals[..], Some(&definition_levels[..]), None) ?;
1283                } else {
1284                    panic!("Schema and struct disagree on type for {}" , stringify!{ maybe_happened })
1285                }
1286            }
1287        }).to_string());
1288    }
1289
1290    #[test]
1291    fn test_chrono_timestamp_millis_read() {
1292        let snippet: proc_macro2::TokenStream = quote! {
1293          struct ATimestampStruct {
1294            henceforth: chrono::NaiveDateTime,
1295          }
1296        };
1297
1298        let fields = extract_fields(snippet);
1299        let when = Field::from(&fields[0]);
1300        assert_eq!(when.reader_snippet().to_string(),(quote!{
1301            {
1302                let mut vals = Vec::new();
1303                if let ColumnReader::Int64ColumnReader(mut typed) = column_reader {
1304                    let mut definition_levels = Vec::new();
1305                    let (total_num, valid_num, decoded_num) = typed.read_records(
1306                        num_records, Some(&mut definition_levels), None, &mut vals)?;
1307                    if valid_num != decoded_num {
1308                        panic!("Support only valid records, found {} null records in column type {}",
1309                            decoded_num - valid_num, stringify!{henceforth});
1310                    }
1311                } else {
1312                    panic!("Schema and struct disagree on type for {}", stringify!{ henceforth });
1313                }
1314                for (i, r) in &mut records[..num_records].iter_mut().enumerate() {
1315                    r.henceforth = ::chrono::naive::NaiveDateTime::from_timestamp_millis(vals[i]).unwrap();
1316                }
1317            }
1318        }).to_string());
1319    }
1320
1321    #[test]
1322    fn test_chrono_date_write() {
1323        let snippet: proc_macro2::TokenStream = quote! {
1324          struct ATimestampStruct {
1325            henceforth: chrono::NaiveDate,
1326            maybe_happened: Option<&chrono::NaiveDate>,
1327          }
1328        };
1329
1330        let fields = extract_fields(snippet);
1331        let when = Field::from(&fields[0]);
1332        assert_eq!(when.writer_snippet().to_string(),(quote!{
1333            {
1334                let vals : Vec<_> = records.iter().map(|rec| rec.henceforth.signed_duration_since(::chrono::NaiveDate::from_ymd(1970, 1, 1)).num_days() as i32).collect();
1335                if let ColumnWriter::Int32ColumnWriter(typed) = column_writer.untyped() {
1336                    typed.write_batch(&vals[..], None, None) ?;
1337                } else {
1338                    panic!("Schema and struct disagree on type for {}" , stringify!{ henceforth })
1339                }
1340            }
1341        }).to_string());
1342
1343        let maybe_happened = Field::from(&fields[1]);
1344        assert_eq!(maybe_happened.writer_snippet().to_string(),(quote!{
1345            {
1346                let definition_levels : Vec<i16> = self.iter().map(|rec| if rec.maybe_happened.is_some() { 1 } else { 0 }).collect();
1347                let vals : Vec<_> = records.iter().filter_map(|rec| {
1348                    if let Some(inner) = rec.maybe_happened {
1349                        Some(inner.signed_duration_since(::chrono::NaiveDate::from_ymd(1970, 1, 1)).num_days() as i32)
1350                    } else {
1351                        None
1352                    }
1353                }).collect();
1354
1355                if let ColumnWriter::Int32ColumnWriter(typed) = column_writer.untyped() {
1356                    typed.write_batch(&vals[..], Some(&definition_levels[..]), None) ?;
1357                } else {
1358                    panic!("Schema and struct disagree on type for {}" , stringify!{ maybe_happened })
1359                }
1360            }
1361        }).to_string());
1362    }
1363
1364    #[test]
1365    fn test_chrono_date_read() {
1366        let snippet: proc_macro2::TokenStream = quote! {
1367          struct ATimestampStruct {
1368            henceforth: chrono::NaiveDate,
1369          }
1370        };
1371
1372        let fields = extract_fields(snippet);
1373        let when = Field::from(&fields[0]);
1374        assert_eq!(when.reader_snippet().to_string(),(quote!{
1375            {
1376                let mut vals = Vec::new();
1377                if let ColumnReader::Int32ColumnReader(mut typed) = column_reader {
1378                    let mut definition_levels = Vec::new();
1379                    let (total_num, valid_num, decoded_num) = typed.read_records(
1380                        num_records, Some(&mut definition_levels), None, &mut vals)?;
1381                    if valid_num != decoded_num {
1382                        panic!("Support only valid records, found {} null records in column type {}",
1383                            decoded_num - valid_num, stringify!{henceforth});
1384                    }
1385                } else {
1386                    panic!("Schema and struct disagree on type for {}", stringify!{ henceforth });
1387                }
1388                for (i, r) in &mut records[..num_records].iter_mut().enumerate() {
1389                    r.henceforth = ::chrono::naive::NaiveDate::from_num_days_from_ce_opt(vals[i].saturating_add(719163)).unwrap();
1390                }
1391            }
1392        }).to_string());
1393    }
1394
1395    #[test]
1396    fn test_uuid_write() {
1397        let snippet: proc_macro2::TokenStream = quote! {
1398          struct AUuidStruct {
1399            unique_id: uuid::Uuid,
1400            maybe_unique_id: Option<&uuid::Uuid>,
1401          }
1402        };
1403
1404        let fields = extract_fields(snippet);
1405        let when = Field::from(&fields[0]);
1406        assert_eq!(when.writer_snippet().to_string(),(quote!{
1407            {
1408                let vals : Vec<_> = records.iter().map(|rec| rec.unique_id.as_bytes().to_vec().into() ).collect();
1409                if let ColumnWriter::FixedLenByteArrayColumnWriter(typed) = column_writer.untyped() {
1410                    typed.write_batch(&vals[..], None, None) ?;
1411                } else {
1412                    panic!("Schema and struct disagree on type for {}" , stringify!{ unique_id })
1413                }
1414            }
1415        }).to_string());
1416
1417        let maybe_happened = Field::from(&fields[1]);
1418        assert_eq!(maybe_happened.writer_snippet().to_string(),(quote!{
1419            {
1420                let definition_levels : Vec<i16> = self.iter().map(|rec| if rec.maybe_unique_id.is_some() { 1 } else { 0 }).collect();
1421                let vals : Vec<_> = records.iter().filter_map(|rec| {
1422                    if let Some(inner) = &rec.maybe_unique_id {
1423                        Some((&inner.to_string()[..]).into())
1424                    } else {
1425                        None
1426                    }
1427                }).collect();
1428
1429                if let ColumnWriter::FixedLenByteArrayColumnWriter(typed) = column_writer.untyped() {
1430                    typed.write_batch(&vals[..], Some(&definition_levels[..]), None) ?;
1431                } else {
1432                    panic!("Schema and struct disagree on type for {}" , stringify!{ maybe_unique_id })
1433                }
1434            }
1435        }).to_string());
1436    }
1437
1438    #[test]
1439    fn test_uuid_read() {
1440        let snippet: proc_macro2::TokenStream = quote! {
1441          struct AUuidStruct {
1442            unique_id: uuid::Uuid,
1443          }
1444        };
1445
1446        let fields = extract_fields(snippet);
1447        let when = Field::from(&fields[0]);
1448        assert_eq!(when.reader_snippet().to_string(),(quote!{
1449            {
1450                let mut vals = Vec::new();
1451                if let ColumnReader::FixedLenByteArrayColumnReader(mut typed) = column_reader {
1452                    let mut definition_levels = Vec::new();
1453                    let (total_num, valid_num, decoded_num) = typed.read_records(
1454                        num_records, Some(&mut definition_levels), None, &mut vals)?;
1455                    if valid_num != decoded_num {
1456                        panic!("Support only valid records, found {} null records in column type {}",
1457                            decoded_num - valid_num, stringify!{unique_id});
1458                    }
1459                } else {
1460                    panic!("Schema and struct disagree on type for {}", stringify!{ unique_id });
1461                }
1462                for (i, r) in &mut records[..num_records].iter_mut().enumerate() {
1463                    r.unique_id = ::uuid::Uuid::from_bytes(vals[i].data().try_into().unwrap());
1464                }
1465            }
1466        }).to_string());
1467    }
1468
1469    #[test]
1470    fn test_converted_type() {
1471        let snippet: proc_macro2::TokenStream = quote! {
1472          struct ATimeStruct {
1473            time: chrono::NaiveDateTime,
1474          }
1475        };
1476
1477        let fields = extract_fields(snippet);
1478
1479        let time = Field::from(&fields[0]);
1480
1481        let converted_type = time.ty.converted_type();
1482        assert_eq!(
1483            converted_type.unwrap().to_string(),
1484            quote! { ::parquet::basic::ConvertedType::TIMESTAMP_MILLIS }.to_string()
1485        );
1486    }
1487}