Skip to main content

mz_avro/
lib.rs

1// Copyright 2018 Flavien Raynaud.
2// Copyright Materialize, Inc. and contributors. All rights reserved.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License in the LICENSE file at the
7// root of this repository, or online at
8//
9//     http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16//
17// This file is derived from the avro-rs project, available at
18// https://github.com/flavray/avro-rs. It was incorporated
19// directly into Materialize on March 3, 2020.
20//
21// The original source code is subject to the terms of the MIT license, a copy
22// of which can be found in the LICENSE file at the root of this repository.
23
24//! # avro
25//! **[Apache Avro](https://avro.apache.org/)** is a data serialization system which provides rich
26//! data structures and a compact, fast, binary data format.
27//!
28//! All data in Avro is schematized, as in the following example:
29//!
30//! ```text
31//! {
32//!     "type": "record",
33//!     "name": "test",
34//!     "fields": [
35//!         {"name": "a", "type": "long", "default": 42},
36//!         {"name": "b", "type": "string"}
37//!     ]
38//! }
39//! ```
40//!
41//! There are basically two ways of handling Avro data in Rust:
42//!
43//! * **as Avro-specialized data types** based on an Avro schema;
44//! * **as generic Rust types** with custom serialization logic implementing `AvroDecode`
45//!   (currently only supports deserialization, not serialization).
46//!
47//! **avro** provides a way to read and write both these data representations easily and
48//! efficiently.
49//!
50//! # Installing the library
51//!
52//!
53//! Add to your `Cargo.toml`:
54//!
55//! ```text
56//! [dependencies]
57//! avro = "x.y"
58//! ```
59//!
60//! Or in case you want to leverage the **Snappy** codec:
61//!
62//! ```text
63//! [dependencies.avro]
64//! version = "x.y"
65//! features = ["snappy"]
66//! ```
67//!
68//! # Defining a schema
69//!
70//! Avro data cannot exist without an Avro schema. Schemas **must** be used both while writing and
71//! reading and they carry the information regarding the type of data we are
72//! handling. Avro schemas are used for both schema validation and resolution of Avro data.
73//!
74//! Avro schemas are defined in **JSON** format and can just be parsed out of a raw string:
75//!
76//! ```
77//! use mz_avro::Schema;
78//!
79//! let raw_schema = r#"
80//!     {
81//!         "type": "record",
82//!         "name": "test",
83//!         "fields": [
84//!             {"name": "a", "type": "long", "default": 42},
85//!             {"name": "b", "type": "string"}
86//!         ]
87//!     }
88//! "#;
89//!
90//! // if the schema is not valid, this function will return an error
91//! let schema: Schema = raw_schema.parse().unwrap();
92//!
93//! // schemas can be printed for debugging
94//! println!("{:?}", schema);
95//! ```
96//!
97//! For more information about schemas and what kind of information you can encapsulate in them,
98//! please refer to the appropriate section of the
99//! [Avro Specification](https://avro.apache.org/docs/++version++/specification/#schema-declaration).
100//!
101//! # Writing data
102//!
103//! Once we have defined a schema, we are ready to serialize data in Avro, validating them against
104//! the provided schema in the process.
105//!
106//! **NOTE:** The library also provides a low-level interface for encoding a single datum in Avro
107//! bytecode without generating markers and headers (for advanced use), but we highly recommend the
108//! `Writer` interface to be totally Avro-compatible. Please read the API reference in case you are
109//! interested.
110//!
111//! Given that the schema we defined above is that of an Avro *Record*, we are going to use the
112//! associated type provided by the library to specify the data we want to serialize:
113//!
114//! ```
115//! # use mz_avro::Schema;
116//! use mz_avro::types::Record;
117//! use mz_avro::Writer;
118//! #
119//! # let raw_schema = r#"
120//! #     {
121//! #         "type": "record",
122//! #         "name": "test",
123//! #         "fields": [
124//! #             {"name": "a", "type": "long", "default": 42},
125//! #             {"name": "b", "type": "string"}
126//! #         ]
127//! #     }
128//! # "#;
129//! # let schema: Schema = raw_schema.parse().unwrap();
130//! // a writer needs a schema and something to write to
131//! let mut writer = Writer::new(schema.clone(), Vec::new());
132//!
133//! // the Record type models our Record schema
134//! let mut record = Record::new(schema.top_node()).unwrap();
135//! record.put("a", 27i64);
136//! record.put("b", "foo");
137//!
138//! // schema validation happens here
139//! writer.append(record).unwrap();
140//!
141//! // flushing makes sure that all data gets encoded
142//! writer.flush().unwrap();
143//!
144//! // this is how to get back the resulting avro bytecode
145//! let encoded = writer.into_inner();
146//! ```
147//!
148//! The vast majority of the time, schemas tend to define a record as a top-level container
149//! encapsulating all the values to convert as fields and providing documentation for them, but in
150//! case we want to directly define an Avro value, the library offers that capability via the
151//! `Value` interface.
152//!
153//! ```
154//! use mz_avro::types::Value;
155//!
156//! let mut value = Value::String("foo".to_string());
157//! ```
158//!
159//! ## Using codecs to compress data
160//!
161//! Avro supports three different compression codecs when encoding data:
162//!
163//! * **Null**: leaves data uncompressed;
164//! * **Deflate**: writes the data block using the deflate algorithm as specified in RFC 1951, and
165//! typically implemented using the zlib library. Note that this format (unlike the "zlib format" in
166//! RFC 1950) does not have a checksum.
167//! * **Snappy**: uses Google's [Snappy](http://google.github.io/snappy/) compression library. Each
168//! compressed block is followed by the 4-byte, big-endianCRC32 checksum of the uncompressed data in
169//! the block. You must enable the `snappy` feature to use this codec.
170//!
171//! To specify a codec to use to compress data, just specify it while creating a `Writer`:
172//! ```
173//! # use mz_avro::Schema;
174//! use mz_avro::Writer;
175//! use mz_avro::Codec;
176//! #
177//! # let raw_schema = r#"
178//! #     {
179//! #         "type": "record",
180//! #         "name": "test",
181//! #         "fields": [
182//! #             {"name": "a", "type": "long", "default": 42},
183//! #             {"name": "b", "type": "string"}
184//! #         ]
185//! #     }
186//! # "#;
187//! # let schema: Schema = raw_schema.parse().unwrap();
188//! let mut writer = Writer::with_codec(schema, Vec::new(), Codec::Deflate);
189//! ```
190//!
191//! # Reading data
192//!
193//! As far as reading Avro encoded data goes, we can just use the schema encoded with the data to
194//! read them. The library will do it automatically for us, as it already does for the compression
195//! codec:
196//!
197//! ```
198//!
199//! use mz_avro::Reader;
200//! # use mz_avro::Schema;
201//! # use mz_avro::types::Record;
202//! # use mz_avro::Writer;
203//! #
204//! # let raw_schema = r#"
205//! #     {
206//! #         "type": "record",
207//! #         "name": "test",
208//! #         "fields": [
209//! #             {"name": "a", "type": "long", "default": 42},
210//! #             {"name": "b", "type": "string"}
211//! #         ]
212//! #     }
213//! # "#;
214//! # let schema: Schema = raw_schema.parse().unwrap();
215//! # let mut writer = Writer::new(schema.clone(), Vec::new());
216//! # let mut record = Record::new(schema.top_node()).unwrap();
217//! # record.put("a", 27i64);
218//! # record.put("b", "foo");
219//! # writer.append(record).unwrap();
220//! # writer.flush().unwrap();
221//! # let input = writer.into_inner();
222//! // reader creation can fail in case the input to read from is not Avro-compatible or malformed
223//! let reader = Reader::new(&input[..]).unwrap();
224//! ```
225//!
226//! In case, instead, we want to specify a different (but compatible) reader schema from the schema
227//! the data has been written with, we can just do as the following:
228//! ```
229//! use mz_avro::Schema;
230//! use mz_avro::Reader;
231//! # use mz_avro::types::Record;
232//! # use mz_avro::Writer;
233//! #
234//! # let writer_raw_schema = r#"
235//! #     {
236//! #         "type": "record",
237//! #         "name": "test",
238//! #         "fields": [
239//! #             {"name": "a", "type": "long", "default": 42},
240//! #             {"name": "b", "type": "string"}
241//! #         ]
242//! #     }
243//! # "#;
244//! # let writer_schema: Schema = writer_raw_schema.parse().unwrap();
245//! # let mut writer = Writer::new(writer_schema.clone(), Vec::new());
246//! # let mut record = Record::new(writer_schema.top_node()).unwrap();
247//! # record.put("a", 27i64);
248//! # record.put("b", "foo");
249//! # writer.append(record).unwrap();
250//! # writer.flush().unwrap();
251//! # let input = writer.into_inner();
252//!
253//! let reader_raw_schema = r#"
254//!     {
255//!         "type": "record",
256//!         "name": "test",
257//!         "fields": [
258//!             {"name": "a", "type": "long", "default": 42},
259//!             {"name": "b", "type": "string"},
260//!             {"name": "c", "type": "long", "default": 43}
261//!         ]
262//!     }
263//! "#;
264//!
265//! let reader_schema: Schema = reader_raw_schema.parse().unwrap();
266//!
267//! // reader creation can fail in case the input to read from is not Avro-compatible or malformed
268//! let reader = Reader::with_schema(&reader_schema, &input[..]).unwrap();
269//! ```
270//!
271//! The library will also automatically perform schema resolution while reading the data.
272//!
273//! For more information about schema compatibility and resolution, please refer to the
274//! [Avro Specification](https://avro.apache.org/docs/++version++/specification/#schema-declaration).
275//!
276//! There are two ways to handle deserializing Avro data in Rust, as you can see below.
277//!
278//! **NOTE:** The library also provides a low-level interface for decoding a single datum in Avro
279//! bytecode without markers and header (for advanced use), but we highly recommend the `Reader`
280//! interface to leverage all Avro features. Please read the API reference in case you are
281//! interested.
282//!
283//!
284//! ## The avro way
285//!
286//! We can just read directly instances of `Value` out of the `Reader` iterator:
287//!
288//! ```
289//! # use mz_avro::Schema;
290//! # use mz_avro::types::Record;
291//! # use mz_avro::Writer;
292//! use mz_avro::Reader;
293//! #
294//! # let raw_schema = r#"
295//! #     {
296//! #         "type": "record",
297//! #         "name": "test",
298//! #         "fields": [
299//! #             {"name": "a", "type": "long", "default": 42},
300//! #             {"name": "b", "type": "string"}
301//! #         ]
302//! #     }
303//! # "#;
304//! # let schema: Schema = raw_schema.parse().unwrap();
305//! # let mut writer = Writer::new(schema.clone(), Vec::new());
306//! # let mut record = Record::new(schema.top_node()).unwrap();
307//! # record.put("a", 27i64);
308//! # record.put("b", "foo");
309//! # writer.append(record).unwrap();
310//! # writer.flush().unwrap();
311//! # let input = writer.into_inner();
312//! let mut reader = Reader::new(&input[..]).unwrap();
313//!
314//! // value is a Result of an Avro Value in case the read operation fails
315//! for value in reader {
316//!     println!("{:?}", value.unwrap());
317//! }
318//!
319//! ```
320//!
321//! ## Custom deserialization (advanced)
322//!
323//! It is possible to avoid the intermediate stage of decoding to `Value`,
324//! by implementing `AvroDecode` for one or more structs that will determine how to decode various schema pieces.
325//!
326//! This API is in flux, and more complete documentation is coming soon. For now,
327//! [Materialize](https://github.com/MaterializeInc/materialize/blob/main/src/interchange/src/avro.rs)
328//! furnishes the most complete example.
329
330// TODO(benesch): remove this once this crate no longer makes use of potentially
331// dangerous `as` conversions.
332#![allow(clippy::as_conversions)]
333
334mod codec;
335mod decode;
336mod reader;
337mod util;
338mod writer;
339
340pub mod encode;
341pub mod error;
342pub mod schema;
343pub mod types;
344
345pub use crate::codec::Codec;
346pub use crate::decode::public_decoders::*;
347pub use crate::decode::{
348    AvroArrayAccess, AvroDecode, AvroDeserializer, AvroFieldAccess, AvroMapAccess, AvroRead,
349    AvroRecordAccess, GeneralDeserializer, Skip, ValueOrReader, give_value,
350};
351pub use crate::encode::encode as encode_unchecked;
352pub use crate::reader::{Block, BlockIter, Reader, from_avro_datum};
353pub use crate::schema::{ParseSchemaError, Schema};
354pub use crate::types::SchemaResolutionError;
355pub use crate::writer::{ValidationError, Writer, to_avro_datum, write_avro_datum};
356
357#[cfg(test)]
358mod tests {
359    use std::str::FromStr;
360
361    use mz_ore::{assert_err, assert_none};
362
363    use crate::reader::Reader;
364    use crate::schema::Schema;
365    use crate::types::{Record, Value};
366
367    use super::*;
368
369    //TODO: move where it fits better
370    #[mz_ore::test]
371    #[cfg_attr(miri, ignore)] // unsupported operation: inline assembly is not supported
372    fn test_enum_default() {
373        let writer_raw_schema = r#"
374            {
375                "type": "record",
376                "name": "test",
377                "fields": [
378                    {"name": "a", "type": "long", "default": 42},
379                    {"name": "b", "type": "string"}
380                ]
381            }
382        "#;
383        let reader_raw_schema = r#"
384            {
385                "type": "record",
386                "name": "test",
387                "fields": [
388                    {"name": "a", "type": "long", "default": 42},
389                    {"name": "b", "type": "string"},
390                    {
391                        "name": "c",
392                        "type": {
393                            "type": "enum",
394                            "name": "suit",
395                            "symbols": ["diamonds", "spades", "clubs", "hearts"]
396                        },
397                        "default": "spades"
398                    }
399                ]
400            }
401        "#;
402        let writer_schema = Schema::from_str(writer_raw_schema).unwrap();
403        let reader_schema = Schema::from_str(reader_raw_schema).unwrap();
404        let mut writer = Writer::with_codec(writer_schema.clone(), Vec::new(), Codec::Null);
405        let mut record = Record::new(writer_schema.top_node()).unwrap();
406        record.put("a", 27i64);
407        record.put("b", "foo");
408        writer.append(record).unwrap();
409        writer.flush().unwrap();
410        let input = writer.into_inner();
411        let mut reader = Reader::with_schema(&reader_schema, &input[..]).unwrap();
412        assert_eq!(
413            reader.next().unwrap().unwrap(),
414            Value::Record(vec![
415                ("a".to_string(), Value::Long(27)),
416                ("b".to_string(), Value::String("foo".to_string())),
417                ("c".to_string(), Value::Enum(1, "spades".to_string())),
418            ])
419        );
420        assert_none!(reader.next());
421    }
422
423    //TODO: move where it fits better
424    #[mz_ore::test]
425    #[cfg_attr(miri, ignore)] // unsupported operation: inline assembly is not supported
426    fn test_enum_string_value() {
427        let raw_schema = r#"
428            {
429                "type": "record",
430                "name": "test",
431                "fields": [
432                    {"name": "a", "type": "long", "default": 42},
433                    {"name": "b", "type": "string"},
434                    {
435                        "name": "c",
436                        "type": {
437                            "type": "enum",
438                            "name": "suit",
439                            "symbols": ["diamonds", "spades", "clubs", "hearts"]
440                        },
441                        "default": "spades"
442                    }
443                ]
444            }
445        "#;
446        let schema = Schema::from_str(raw_schema).unwrap();
447        let mut writer = Writer::with_codec(schema.clone(), Vec::new(), Codec::Null);
448        let mut record = Record::new(schema.top_node()).unwrap();
449        record.put("a", 27i64);
450        record.put("b", "foo");
451        record.put("c", "clubs");
452        writer.append(record).unwrap();
453        writer.flush().unwrap();
454        let input = writer.into_inner();
455        let mut reader = Reader::with_schema(&schema, &input[..]).unwrap();
456        assert_eq!(
457            reader.next().unwrap().unwrap(),
458            Value::Record(vec![
459                ("a".to_string(), Value::Long(27)),
460                ("b".to_string(), Value::String("foo".to_string())),
461                ("c".to_string(), Value::Enum(2, "clubs".to_string())),
462            ])
463        );
464        assert_none!(reader.next());
465    }
466
467    //TODO: move where it fits better
468    #[mz_ore::test]
469    #[cfg_attr(miri, ignore)] // unsupported operation: inline assembly is not supported
470    fn test_enum_resolution() {
471        let writer_raw_schema = r#"
472            {
473                "type": "record",
474                "name": "test",
475                "fields": [
476                    {"name": "a", "type": "long", "default": 42},
477                    {"name": "b", "type": "string"},
478                    {
479                        "name": "c",
480                        "type": {
481                            "type": "enum",
482                            "name": "suit",
483                            "symbols": ["diamonds", "spades", "clubs", "hearts"]
484                        },
485                        "default": "spades"
486                    }
487                ]
488            }
489        "#;
490        let reader_raw_schema = r#"
491            {
492                "type": "record",
493                "name": "test",
494                "fields": [
495                    {"name": "a", "type": "long", "default": 42},
496                    {"name": "b", "type": "string"},
497                    {
498                        "name": "c",
499                        "type": {
500                            "type": "enum",
501                            "name": "suit",
502                            "symbols": ["diamonds", "spades", "ninja", "hearts"]
503                        },
504                        "default": "spades"
505                    }
506                ]
507            }
508        "#;
509        let writer_schema = Schema::from_str(writer_raw_schema).unwrap();
510        let reader_schema = Schema::from_str(reader_raw_schema).unwrap();
511        let mut writer = Writer::with_codec(writer_schema.clone(), Vec::new(), Codec::Null);
512        let mut record = Record::new(writer_schema.top_node()).unwrap();
513        record.put("a", 27i64);
514        record.put("b", "foo");
515        record.put("c", "clubs");
516        writer.append(record).unwrap();
517        writer.flush().unwrap();
518        let input = writer.into_inner();
519        let mut reader = Reader::with_schema(&reader_schema, &input[..]).unwrap();
520        assert_err!(reader.next().unwrap());
521        assert_none!(reader.next());
522    }
523
524    // Avro numeric promotion across every promotable pair, with the field
525    // rendered both bare (`"int"`) and nullable (`["null", "int"]`) on each
526    // side. Promoting a nullable column means promoting inside the `["null",
527    // T]` union; that previously failed at decode time with "Failed to match
528    // writer union variant ... against any variant in the reader" because union
529    // variant matching ignored promotion. The four bare/nullable combinations
530    // cover concrete -> union, union -> concrete, union -> union, and the plain
531    // concrete -> concrete path.
532    #[mz_ore::test]
533    #[cfg_attr(miri, ignore)] // unsupported operation: inline assembly is not supported
534    fn test_numeric_promotion_matrix() {
535        // `123` is exactly representable in int/long/float/double, so a value
536        // promoted to `kind` equals that kind's representative value.
537        fn value_of(kind: &str) -> Value {
538            match kind {
539                "int" => Value::Int(123),
540                "long" => Value::Long(123),
541                "float" => Value::Float(123.0),
542                "double" => Value::Double(123.0),
543                other => panic!("unhandled kind {other}"),
544            }
545        }
546        fn record_schema_json(kind: &str, nullable: bool) -> String {
547            let ty = if nullable {
548                format!(r#"["null", "{kind}"]"#)
549            } else {
550                format!(r#""{kind}""#)
551            };
552            format!(r#"{{"type":"record","name":"test","fields":[{{"name":"f1","type":{ty}}}]}}"#)
553        }
554        // A nullable field is a `["null", T]` union, so the value lives in
555        // variant 1 with the null variant at 0.
556        fn maybe_union(v: Value, nullable: bool) -> Value {
557            if nullable {
558                Value::Union {
559                    index: 1,
560                    inner: Box::new(v),
561                    n_variants: 2,
562                    null_variant: Some(0),
563                }
564            } else {
565                v
566            }
567        }
568
569        // Every promotable numeric pair (int/long/float/double widening).
570        let pairs = [
571            ("int", "long"),
572            ("int", "float"),
573            ("int", "double"),
574            ("long", "float"),
575            ("long", "double"),
576            ("float", "double"),
577        ];
578        for (writer_kind, reader_kind) in pairs {
579            for writer_nullable in [false, true] {
580                for reader_nullable in [false, true] {
581                    let writer_schema =
582                        Schema::from_str(&record_schema_json(writer_kind, writer_nullable))
583                            .unwrap();
584                    let reader_schema =
585                        Schema::from_str(&record_schema_json(reader_kind, reader_nullable))
586                            .unwrap();
587                    let mut writer =
588                        Writer::with_codec(writer_schema.clone(), Vec::new(), Codec::Null);
589                    let mut record = Record::new(writer_schema.top_node()).unwrap();
590                    record.put("f1", maybe_union(value_of(writer_kind), writer_nullable));
591                    writer.append(record).unwrap();
592                    writer.flush().unwrap();
593                    let input = writer.into_inner();
594
595                    let mut reader = Reader::with_schema(&reader_schema, &input[..]).unwrap();
596                    let expected = maybe_union(value_of(reader_kind), reader_nullable);
597                    assert_eq!(
598                        reader.next().unwrap().unwrap(),
599                        Value::Record(vec![("f1".to_string(), expected)]),
600                        "promotion {writer_kind}{} -> {reader_kind}{} decoded incorrectly",
601                        if writer_nullable { " (nullable)" } else { "" },
602                        if reader_nullable { " (nullable)" } else { "" },
603                    );
604                    assert_none!(reader.next());
605                }
606            }
607        }
608    }
609
610    // Promotion-aware union matching must still *reject* changes that are not
611    // valid promotions; a too-permissive matcher would match a variant and then
612    // mis-decode or silently corrupt the value. Each case is a numeric
613    // narrowing (`double` -> `int`) or an incompatible change (`string` ->
614    // `int`), across the same bare/nullable combinations as the positive
615    // matrix, and must fail rather than produce a value.
616    #[mz_ore::test]
617    #[cfg_attr(miri, ignore)] // unsupported operation: inline assembly is not supported
618    fn test_non_promotable_changes_are_rejected() {
619        fn record_with_field(ty: &str) -> Schema {
620            Schema::from_str(&format!(
621                r#"{{"type":"record","name":"test","fields":[{{"name":"f1","type":{ty}}}]}}"#
622            ))
623            .unwrap()
624        }
625        // (writer field type, writer value, reader field type).
626        let cases = [
627            // Numeric narrowing, exercising each union matcher's reject path.
628            (
629                r#"["null", "double"]"#,
630                Value::Double(1.0),
631                r#"["null", "int"]"#,
632            ), // union -> union
633            (r#""double""#, Value::Double(1.0), r#"["null", "int"]"#), // bare  -> union
634            (r#"["null", "double"]"#, Value::Double(1.0), r#""int""#), // union -> bare
635            (r#""double""#, Value::Double(1.0), r#""int""#),           // bare  -> bare
636            // Incompatible (non-numeric) change.
637            (
638                r#"["null", "string"]"#,
639                Value::String("x".to_string()),
640                r#"["null", "int"]"#,
641            ),
642            (r#""string""#, Value::String("x".to_string()), r#""int""#),
643        ];
644        for (writer_ty, writer_value, reader_ty) in cases {
645            let writer_schema = record_with_field(writer_ty);
646            let reader_schema = record_with_field(reader_ty);
647            let mut writer = Writer::with_codec(writer_schema.clone(), Vec::new(), Codec::Null);
648            let mut record = Record::new(writer_schema.top_node()).unwrap();
649            let field_value = if writer_ty.starts_with('[') {
650                Value::Union {
651                    index: 1,
652                    inner: Box::new(writer_value),
653                    n_variants: 2,
654                    null_variant: Some(0),
655                }
656            } else {
657                writer_value
658            };
659            record.put("f1", field_value);
660            writer.append(record).unwrap();
661            writer.flush().unwrap();
662            let input = writer.into_inner();
663
664            // Resolution may reject the pair up front, or decoding may error;
665            // either is acceptable, but it must never silently yield a value.
666            let produced_value = match Reader::with_schema(&reader_schema, &input[..]) {
667                Err(_) => false,
668                Ok(mut reader) => matches!(reader.next(), Some(Ok(_))),
669            };
670            assert!(
671                !produced_value,
672                "non-promotable change {writer_ty} -> {reader_ty} was not rejected",
673            );
674        }
675    }
676
677    //TODO: move where it fits better
678    #[mz_ore::test]
679    fn test_enum_no_reader_schema() {
680        let writer_raw_schema = r#"
681            {
682                "type": "record",
683                "name": "test",
684                "fields": [
685                    {"name": "a", "type": "long", "default": 42},
686                    {"name": "b", "type": "string"},
687                    {
688                        "name": "c",
689                        "type": {
690                            "type": "enum",
691                            "name": "suit",
692                            "symbols": ["diamonds", "spades", "clubs", "hearts"]
693                        },
694                        "default": "spades"
695                    }
696                ]
697            }
698        "#;
699        let writer_schema = Schema::from_str(writer_raw_schema).unwrap();
700        let mut writer = Writer::with_codec(writer_schema.clone(), Vec::new(), Codec::Null);
701        let mut record = Record::new(writer_schema.top_node()).unwrap();
702        record.put("a", 27i64);
703        record.put("b", "foo");
704        record.put("c", "clubs");
705        writer.append(record).unwrap();
706        writer.flush().unwrap();
707        let input = writer.into_inner();
708        let mut reader = Reader::new(&input[..]).unwrap();
709        assert_eq!(
710            reader.next().unwrap().unwrap(),
711            Value::Record(vec![
712                ("a".to_string(), Value::Long(27)),
713                ("b".to_string(), Value::String("foo".to_string())),
714                ("c".to_string(), Value::Enum(2, "clubs".to_string())),
715            ])
716        );
717    }
718    #[mz_ore::test]
719    fn test_datetime_value() {
720        let writer_raw_schema = r#"{
721        "type": "record",
722        "name": "dttest",
723        "fields": [
724            {
725                "name": "a",
726                "type": {
727                    "type": "long",
728                    "logicalType": "timestamp-micros"
729                }
730            }
731        ]}"#;
732        let writer_schema = Schema::from_str(writer_raw_schema).unwrap();
733        let mut writer = Writer::with_codec(writer_schema.clone(), Vec::new(), Codec::Null);
734        let mut record = Record::new(writer_schema.top_node()).unwrap();
735        let dt = chrono::DateTime::from_timestamp(1_000, 995_000_000)
736            .unwrap()
737            .naive_utc();
738        record.put("a", types::Value::Timestamp(dt));
739        writer.append(record).unwrap();
740        writer.flush().unwrap();
741        let input = writer.into_inner();
742        let mut reader = Reader::new(&input[..]).unwrap();
743        assert_eq!(
744            reader.next().unwrap().unwrap(),
745            Value::Record(vec![("a".to_string(), Value::Timestamp(dt)),])
746        );
747    }
748
749    #[mz_ore::test]
750    fn test_malformed_length() {
751        let raw_schema = r#"
752            {
753                "type": "record",
754                "name": "test",
755                "fields": [
756                    {"name": "a", "type": "long", "default": 42},
757                    {"name": "b", "type": "string"}
758                ]
759            }
760        "#;
761
762        let schema = Schema::from_str(raw_schema).unwrap();
763
764        // Would allocated 18446744073709551605 bytes
765        let malformed: &[u8] = &[0x3e, 0x15, 0xff, 0x1f, 0x15, 0xff];
766
767        let value = from_avro_datum(&schema, &mut &malformed[..]);
768        assert_err!(value);
769    }
770}