Skip to main content

mz_avro/
types.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//! Logic handling the intermediate representation of Avro values.
25
26use std::collections::BTreeMap;
27use std::fmt;
28
29use chrono::NaiveDateTime;
30use itertools::Itertools;
31use serde_json::Value as JsonValue;
32
33use crate::schema::{RecordField, SchemaNode, SchemaPiece, SchemaPieceOrNamed};
34
35/// Describes errors happened while performing schema resolution on Avro data.
36#[derive(Clone, Debug, Eq, PartialEq)]
37pub struct SchemaResolutionError(pub String);
38
39impl SchemaResolutionError {
40    pub fn new<S>(msg: S) -> SchemaResolutionError
41    where
42        S: Into<String>,
43    {
44        SchemaResolutionError(msg.into())
45    }
46}
47
48impl fmt::Display for SchemaResolutionError {
49    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
50        self.0.fmt(f)
51    }
52}
53
54impl std::error::Error for SchemaResolutionError {}
55
56#[derive(Clone, Debug, PartialEq)]
57pub struct DecimalValue {
58    /// An unscaled two's-complement integer value in big-endian byte order.
59    pub unscaled: Vec<u8>,
60    pub precision: usize,
61    pub scale: usize,
62}
63
64#[derive(Clone, Copy, Debug, PartialEq)] // Can't be Eq because there are floats
65pub enum Scalar {
66    Null,
67    Boolean(bool),
68    Int(i32),
69    Long(i64),
70    Float(f32),
71    Double(f64),
72    Date(i32),
73    Timestamp(NaiveDateTime),
74}
75
76impl From<Scalar> for Value {
77    fn from(s: Scalar) -> Self {
78        match s {
79            Scalar::Null => Value::Null,
80            Scalar::Boolean(v) => Value::Boolean(v),
81            Scalar::Int(v) => Value::Int(v),
82            Scalar::Long(v) => Value::Long(v),
83            Scalar::Float(v) => Value::Float(v),
84            Scalar::Double(v) => Value::Double(v),
85            Scalar::Date(v) => Value::Date(v),
86            Scalar::Timestamp(v) => Value::Timestamp(v),
87        }
88    }
89}
90
91/// Represents any valid Avro value
92/// More information about Avro values can be found in the
93/// [Avro Specification](https://avro.apache.org/docs/++version++/specification/#schema-declaration)
94#[derive(Clone, Debug, PartialEq)]
95pub enum Value {
96    // Fixed-length types
97    /// A `null` Avro value.
98    Null,
99    /// A `boolean` Avro value.
100    Boolean(bool),
101    /// A `int` Avro value.
102    Int(i32),
103    /// A `long` Avro value.
104    Long(i64),
105    /// A `float` Avro value.
106    Float(f32),
107    /// A `double` Avro value.
108    Double(f64),
109    /// A `Date` coming from an avro Logical `Date`, which is an i32 number of
110    /// days since the Unix epoch.
111    Date(i32),
112    /// A `DateTime` coming from an avro Logical `Timestamp`
113    Timestamp(NaiveDateTime),
114
115    // Variable-length types
116    /// A `decimal` Avro value
117    ///
118    /// The value of the decimal can be computed as follows:
119    /// <em>unscaled</em> × 10<sup>-<em>scale</em></sup>.
120    Decimal(DecimalValue),
121    /// A `bytes` Avro value.
122    Bytes(Vec<u8>),
123    /// A `string` Avro value.
124    String(String),
125    /// A `fixed` Avro value.
126    /// The size of the fixed value is represented as a `usize`.
127    Fixed(usize, Vec<u8>),
128    /// An `enum` Avro value.
129    ///
130    /// An Enum is represented by a symbol and its position in the symbols list
131    /// of its corresponding schema.
132    /// This allows schema-less encoding, as well as schema resolution while
133    /// reading values.
134    Enum(usize, String),
135    /// An `union` Avro value.
136    Union {
137        /// The index of this variant in the reader schema
138        index: usize,
139        /// The value of the variant
140        inner: Box<Value>,
141        // The next two metadata fields are necessary for the Materialize "flattened unions" decoding strategy to work properly.
142        /// The number of variants in the reader schema
143        n_variants: usize,
144        /// Which variant is null in the reader schema.
145        null_variant: Option<usize>,
146    },
147    /// An `array` Avro value.
148    Array(Vec<Value>),
149    /// A `map` Avro value.
150    Map(BTreeMap<String, Value>),
151    /// A `record` Avro value.
152    ///
153    /// A Record is represented by a vector of (`<field name>`, `value`).
154    /// This allows schema-less encoding.
155    ///
156    /// See [Record](types.Record) for a more user-friendly support.
157    Record(Vec<(String, Value)>),
158    /// A `string` Avro value that has been interpreted as JSON.
159    ///
160    /// This is not part of the Avro spec, but is emitted by Debezium,
161    /// and distinguished by setting the `"connect.name"` property to `"io.debezium.data.Json"`.
162    Json(serde_json::Value),
163    /// A `Uuid` coming from an avro Logical `uuid`.
164    Uuid(uuid::Uuid),
165}
166
167/// Any structure implementing the [`ToAvro`] trait will be usable
168/// from a [`Writer`](crate::Writer).
169pub trait ToAvro {
170    /// Transforms this value into an Avro-compatible [`Value`].
171    fn avro(self) -> Value;
172}
173
174macro_rules! to_avro(
175    ($t:ty, $v:expr) => (
176        impl ToAvro for $t {
177            fn avro(self) -> Value {
178                $v(self)
179            }
180        }
181    );
182);
183
184to_avro!(bool, Value::Boolean);
185to_avro!(i32, Value::Int);
186to_avro!(i64, Value::Long);
187to_avro!(f32, Value::Float);
188to_avro!(f64, Value::Double);
189to_avro!(String, Value::String);
190
191impl ToAvro for () {
192    fn avro(self) -> Value {
193        Value::Null
194    }
195}
196
197impl ToAvro for usize {
198    fn avro(self) -> Value {
199        (self as i64).avro()
200    }
201}
202
203impl<'a> ToAvro for &'a str {
204    fn avro(self) -> Value {
205        Value::String(self.to_owned())
206    }
207}
208
209impl<'a> ToAvro for &'a [u8] {
210    fn avro(self) -> Value {
211        Value::Bytes(self.to_owned())
212    }
213}
214
215impl<T> ToAvro for BTreeMap<String, T>
216where
217    T: ToAvro,
218{
219    fn avro(self) -> Value {
220        Value::Map(
221            self.into_iter()
222                .map(|(key, value)| (key, value.avro()))
223                .collect::<_>(),
224        )
225    }
226}
227
228impl<'a, T> ToAvro for BTreeMap<&'a str, T>
229where
230    T: ToAvro,
231{
232    fn avro(self) -> Value {
233        Value::Map(
234            self.into_iter()
235                .map(|(key, value)| (key.to_owned(), value.avro()))
236                .collect::<_>(),
237        )
238    }
239}
240
241impl ToAvro for Value {
242    fn avro(self) -> Value {
243        self
244    }
245}
246
247/*
248impl<S: Serialize> ToAvro for S {
249    fn avro(self) -> Value {
250        use ser::Serializer;
251
252        self.serialize(&mut Serializer::new()).unwrap()
253    }
254}
255*/
256
257impl Default for Value {
258    fn default() -> Self {
259        Value::Null
260    }
261}
262
263/// Utility interface to build `Value::Record` objects.
264#[derive(Debug, Clone)]
265pub struct Record<'a> {
266    /// List of fields contained in the record.
267    /// Ordered according to the fields in the schema given to create this
268    /// `Record` object. Any unset field defaults to `Value::Null`.
269    pub fields: Vec<(String, Value)>,
270    schema_lookup: &'a BTreeMap<String, usize>,
271    schema_fields: &'a Vec<RecordField>,
272}
273
274impl<'a> Record<'a> {
275    /// Create a `Record` given a `SchemaNode`.
276    ///
277    /// If the `SchemaNode` is not a `SchemaPiece::Record` variant, `None` will be returned.
278    pub fn new(schema: SchemaNode<'a>) -> Option<Record<'a>> {
279        let ret = match schema.inner {
280            SchemaPiece::Record {
281                fields: schema_fields,
282                lookup: schema_lookup,
283                ..
284            } => {
285                let mut fields = Vec::with_capacity(schema_fields.len());
286                for schema_field in schema_fields.iter() {
287                    fields.push((schema_field.name.clone(), Value::Null));
288                }
289
290                Some(Record {
291                    fields,
292                    schema_lookup,
293                    schema_fields,
294                })
295            }
296            _ => None,
297        };
298        ret
299    }
300
301    /// Put a compatible value (implementing the `ToAvro` trait) in the
302    /// `Record` for a given `field` name.
303    ///
304    /// **NOTE** Only ensure that the field name is present in the `SchemaNode` given when creating
305    /// this `Record`. Does not perform any schema validation.
306    pub fn put<V>(&mut self, field: &str, value: V)
307    where
308        V: ToAvro,
309    {
310        if let Some(&position) = self.schema_lookup.get(field) {
311            self.fields[position].1 = value.avro()
312        }
313    }
314
315    /// Get the field description corresponding to the given name.
316    pub fn field_by_name(&self, name: &str) -> Option<&'a RecordField> {
317        self.schema_lookup
318            .get(name)
319            .map(|idx| &self.schema_fields[*idx])
320    }
321}
322
323impl<'a> ToAvro for Record<'a> {
324    fn avro(self) -> Value {
325        Value::Record(self.fields)
326    }
327}
328
329impl ToAvro for JsonValue {
330    fn avro(self) -> Value {
331        match self {
332            JsonValue::Null => Value::Null,
333            JsonValue::Bool(b) => Value::Boolean(b),
334            JsonValue::Number(ref n) if n.is_i64() => Value::Long(n.as_i64().unwrap()),
335            JsonValue::Number(ref n) if n.is_f64() => Value::Double(n.as_f64().unwrap()),
336            JsonValue::Number(n) => Value::Long(n.as_u64().unwrap() as i64), // TODO: Not so great
337            JsonValue::String(s) => Value::String(s),
338            JsonValue::Array(items) => {
339                Value::Array(items.into_iter().map(|item| item.avro()).collect::<_>())
340            }
341            JsonValue::Object(items) => Value::Map(
342                items
343                    .into_iter()
344                    .map(|(key, value)| (key, value.avro()))
345                    .collect::<_>(),
346            ),
347        }
348    }
349}
350
351impl Value {
352    /// Validate the value against the given [`Schema`](crate::Schema).
353    ///
354    /// See the [Avro specification](https://avro.apache.org/docs/++version++/specification/)
355    /// for the full set of rules of schema validation.
356    pub fn validate(&self, schema: SchemaNode) -> bool {
357        match (self, schema.inner) {
358            (&Value::Null, SchemaPiece::Null) => true,
359            (&Value::Boolean(_), SchemaPiece::Boolean) => true,
360            (&Value::Int(_), SchemaPiece::Int) => true,
361            (&Value::Long(_), SchemaPiece::Long) => true,
362            (&Value::Float(_), SchemaPiece::Float) => true,
363            (&Value::Double(_), SchemaPiece::Double) => true,
364            (&Value::Date(_), SchemaPiece::Date) => true,
365            (&Value::Timestamp(_), SchemaPiece::TimestampMicro) => true,
366            (&Value::Timestamp(_), SchemaPiece::TimestampMilli) => true,
367            (
368                &Value::Decimal(DecimalValue {
369                    precision: vp,
370                    scale: vs,
371                    ..
372                }),
373                SchemaPiece::Decimal {
374                    precision: sp,
375                    scale: ss,
376                    fixed_size: _,
377                },
378            ) => vp == *sp && vs == *ss,
379            (&Value::Bytes(_), SchemaPiece::Bytes) => true,
380            (&Value::String(_), SchemaPiece::String) => true,
381            (&Value::Fixed(n, _), SchemaPiece::Fixed { size }) => n == *size,
382            (&Value::String(ref s), SchemaPiece::Enum { symbols, .. }) => symbols.contains(s),
383            (&Value::Enum(i, ref s), SchemaPiece::Enum { symbols, .. }) => {
384                symbols.get(i).map(|symbol| symbol == s).unwrap_or(false)
385            }
386            (
387                &Value::Union {
388                    index,
389                    ref inner,
390                    n_variants,
391                    null_variant,
392                },
393                SchemaPiece::Union(schema_inner),
394            ) => {
395                schema_inner.variants().len() > index
396                    && n_variants == schema_inner.variants().len()
397                    && inner.validate(schema.step(&schema_inner.variants()[index]))
398                    && match null_variant {
399                        None => !schema_inner
400                            .variants()
401                            .iter()
402                            .any(|v| v == &SchemaPieceOrNamed::Piece(SchemaPiece::Null)),
403                        Some(null_variant_idx) => {
404                            schema_inner.variants().get(null_variant_idx)
405                                == Some(&SchemaPieceOrNamed::Piece(SchemaPiece::Null))
406                        }
407                    }
408            }
409            (&Value::Array(ref items), SchemaPiece::Array(inner)) => {
410                let node = schema.step(&**inner);
411                items.iter().all(|item| item.validate(node))
412            }
413            (&Value::Map(ref items), SchemaPiece::Map(inner)) => {
414                let node = schema.step(&**inner);
415                items.iter().all(|(_, value)| value.validate(node))
416            }
417            (&Value::Record(ref record_fields), SchemaPiece::Record { fields, .. }) => {
418                fields.len() == record_fields.len()
419                    && fields.iter().zip_eq(record_fields.iter()).all(
420                        |(field, &(ref name, ref value))| {
421                            let node = schema.step(&field.schema);
422                            field.name == *name && value.validate(node)
423                        },
424                    )
425            }
426            (Value::Json(_), SchemaPiece::Json) => true,
427            (Value::Uuid(_), SchemaPiece::Uuid) => true,
428            _ => false,
429        }
430    }
431
432    // TODO - `into_` functions for all possible Value variants (perhaps generate this using a macro?)
433    pub fn into_string(self) -> Option<String> {
434        match self {
435            Value::String(s) => Some(s),
436            _ => None,
437        }
438    }
439
440    pub fn into_nullable_bool(self) -> Option<bool> {
441        match self {
442            Value::Boolean(b) => Some(b),
443            Value::Union { inner, .. } => inner.into_nullable_bool(),
444            _ => None,
445        }
446    }
447
448    pub fn into_integral(self) -> Option<i64> {
449        match self {
450            Value::Int(i) => Some(i as i64),
451            Value::Long(l) => Some(l),
452            _ => None,
453        }
454    }
455
456    pub fn into_usize(self) -> Option<usize> {
457        self.into_integral().and_then(|i| i.try_into().ok())
458    }
459}
460
461#[cfg(test)]
462mod tests {
463    use std::str::FromStr;
464
465    use crate::Schema;
466
467    use super::*;
468
469    #[mz_ore::test]
470    fn validate() {
471        let value_schema_valid = vec![
472            (Value::Int(42), "\"int\"", true),
473            (Value::Int(42), "\"boolean\"", false),
474            (
475                Value::Union {
476                    index: 0,
477                    inner: Box::new(Value::Null),
478                    n_variants: 2,
479                    null_variant: Some(0),
480                },
481                r#"["null", "int"]"#,
482                true,
483            ),
484            (
485                Value::Union {
486                    index: 1,
487                    inner: Box::new(Value::Int(42)),
488                    n_variants: 2,
489                    null_variant: Some(0),
490                },
491                r#"["null", "int"]"#,
492                true,
493            ),
494            (
495                Value::Union {
496                    index: 1,
497                    inner: Box::new(Value::Null),
498                    n_variants: 2,
499                    null_variant: Some(1),
500                },
501                r#"["double", "int"]"#,
502                false,
503            ),
504            (
505                Value::Union {
506                    index: 3,
507                    inner: Box::new(Value::Int(42)),
508                    n_variants: 4,
509                    null_variant: Some(0),
510                },
511                r#"["null", "double", "string", "int"]"#,
512                true,
513            ),
514            (
515                Value::Array(vec![Value::Long(42i64)]),
516                r#"{"type": "array", "items": "long"}"#,
517                true,
518            ),
519            (
520                Value::Array(vec![Value::Boolean(true)]),
521                r#"{"type": "array", "items": "long"}"#,
522                false,
523            ),
524            (Value::Record(vec![]), "\"null\"", false),
525        ];
526
527        for (value, schema_str, valid) in value_schema_valid.into_iter() {
528            let schema = Schema::from_str(schema_str).unwrap();
529            assert_eq!(
530                valid,
531                value.validate(schema.top_node()),
532                "Schema failed to validate against value: {} {:#?}",
533                schema_str,
534                value
535            );
536        }
537    }
538
539    #[mz_ore::test]
540    fn validate_fixed() {
541        let schema =
542            Schema::from_str(r#"{"type": "fixed", "size": 4, "name": "some_fixed"}"#).unwrap();
543
544        assert!(Value::Fixed(4, vec![0, 0, 0, 0]).validate(schema.top_node()));
545        assert!(!Value::Fixed(5, vec![0, 0, 0, 0, 0]).validate(schema.top_node()));
546    }
547
548    #[mz_ore::test]
549    fn validate_enum() {
550        let schema = Schema::from_str(r#"{"type": "enum", "name": "some_enum", "symbols": ["spades", "hearts", "diamonds", "clubs"]}"#).unwrap();
551
552        assert!(Value::Enum(0, "spades".to_string()).validate(schema.top_node()));
553        assert!(Value::String("spades".to_string()).validate(schema.top_node()));
554
555        assert!(!Value::Enum(1, "spades".to_string()).validate(schema.top_node()));
556        assert!(!Value::String("lorem".to_string()).validate(schema.top_node()));
557
558        let other_schema = Schema::from_str(r#"{"type": "enum", "name": "some_other_enum", "symbols": ["hearts", "diamonds", "clubs", "spades"]}"#).unwrap();
559
560        assert!(!Value::Enum(0, "spades".to_string()).validate(other_schema.top_node()));
561    }
562
563    #[mz_ore::test]
564    fn validate_record() {
565        let schema = Schema::from_str(
566            r#"{
567           "type": "record",
568           "fields": [
569             {"type": "long", "name": "a"},
570             {"type": "string", "name": "b"}
571           ],
572           "name": "some_record"
573        }"#,
574        )
575        .unwrap();
576
577        assert!(
578            Value::Record(vec![
579                ("a".to_string(), Value::Long(42i64)),
580                ("b".to_string(), Value::String("foo".to_string())),
581            ])
582            .validate(schema.top_node())
583        );
584
585        assert!(
586            !Value::Record(vec![
587                ("b".to_string(), Value::String("foo".to_string())),
588                ("a".to_string(), Value::Long(42i64)),
589            ])
590            .validate(schema.top_node())
591        );
592
593        assert!(
594            !Value::Record(vec![
595                ("a".to_string(), Value::Boolean(false)),
596                ("b".to_string(), Value::String("foo".to_string())),
597            ])
598            .validate(schema.top_node())
599        );
600
601        assert!(
602            !Value::Record(vec![
603                ("a".to_string(), Value::Long(42i64)),
604                ("c".to_string(), Value::String("foo".to_string())),
605            ])
606            .validate(schema.top_node())
607        );
608
609        assert!(
610            !Value::Record(vec![
611                ("a".to_string(), Value::Long(42i64)),
612                ("b".to_string(), Value::String("foo".to_string())),
613                ("c".to_string(), Value::Null),
614            ])
615            .validate(schema.top_node())
616        );
617    }
618
619    #[mz_ore::test]
620    fn validate_decimal() {
621        assert!(
622            Value::Decimal(DecimalValue {
623                unscaled: vec![7],
624                precision: 12,
625                scale: 5
626            })
627            .validate(
628                Schema::from_str(
629                    r#"
630            {
631                "type": "bytes",
632                "logicalType": "decimal",
633                "precision": 12,
634                "scale": 5
635            }
636        "#
637                )
638                .unwrap()
639                .top_node()
640            )
641        );
642
643        assert!(
644            !Value::Decimal(DecimalValue {
645                unscaled: vec![7],
646                precision: 13,
647                scale: 5
648            })
649            .validate(
650                Schema::from_str(
651                    r#"
652            {
653                "type": "bytes",
654                "logicalType": "decimal",
655                "precision": 12,
656                "scale": 5
657            }
658        "#
659                )
660                .unwrap()
661                .top_node()
662            )
663        );
664    }
665}