1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//! Application specific models.
use crate::{request::Validation, AvroValue, JsonValue, Map, Record};
use serde::{de::DeserializeOwned, Serialize};

#[doc(no_inline)]
pub use apache_avro::schema;

mod column;
mod mutation;
mod query;
mod reference;
mod row;

pub use column::{Column, EncodeColumn};
pub use mutation::Mutation;
pub use query::Query;
pub use reference::Reference;
pub use row::DecodeRow;

/// General data model.
pub trait Model: Default + Serialize + DeserializeOwned {
    /// Creates a new instance.
    fn new() -> Self;

    /// Updates the model using the json object and returns the validation result.
    #[must_use]
    fn read_map(&mut self, data: &Map) -> Validation;

    /// Attempts to construct a model from a json object.
    #[inline]
    fn try_from_map(data: Map) -> Result<Self, serde_json::Error> {
        serde_json::from_value(JsonValue::from(data))
    }

    /// Attempts to construct a model from an Avro record.
    #[inline]
    fn try_from_avro_record(data: Record) -> Result<Self, apache_avro::Error> {
        apache_avro::from_value(&AvroValue::Record(data))
    }

    /// Consumes the model and returns as a json object.
    ///
    /// # Panics
    ///
    /// It will panic if the model cann't be converted to a json object.
    #[must_use]
    fn into_map(self) -> Map {
        match serde_json::to_value(self) {
            Ok(JsonValue::Object(map)) => map,
            _ => panic!("the model cann't be converted to a json object"),
        }
    }

    /// Consumes the model and returns as an Avro record.
    ///
    /// # Panics
    ///
    /// It will panic if the model cann't be converted to an Avro record.
    #[must_use]
    fn into_avro_record(self) -> Record {
        match apache_avro::to_value(self) {
            Ok(AvroValue::Record(record)) => record,
            _ => panic!("the model cann't be converted to an Avro record"),
        }
    }
}