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
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
use std::{collections::BTreeMap, slice};

use crate::{value::{ConvertError, FromValue, ToValue, Value}};


#[derive(Debug, PartialEq, Clone, Default)]
pub struct AkitaData(pub BTreeMap<String, Value>);

pub trait FromAkita {
    /// convert akita to an instance of the corresponding struct of the model
    /// taking into considerating the renamed columns
    fn from_data(data: &AkitaData) -> Self;
}

pub trait ToAkita {
    /// convert from an instance of the struct to a akita representation
    /// to be saved into the database
    fn to_data(&self) -> AkitaData;
}

#[derive(Debug)]
pub enum AkitaDataError {
    ConvertError(ConvertError),
    NoSuchValueError(String),
}

impl AkitaData {
    pub fn new() -> Self { AkitaData::default() }

    pub fn insert<K, V>(&mut self, k: K, v: V)
    where
        K: ToString,
        V: ToValue,
    {
        self.0.insert(k.to_string(), v.to_value());
    }

    pub fn insert_value<K>(&mut self, k: K, value: &Value)
    where
        K: ToString,
    {
        self.0.insert(k.to_string(), value.clone());
    }

    pub fn get<'a, T>(&'a self, s: &str) -> Result<T, AkitaDataError>
    where
        T: FromValue,
    {
        let value: Option<&'a Value> = self.0.get(s);
        match value {
            Some(v) => FromValue::from_value(v).map_err(AkitaDataError::ConvertError),
            None => Err(AkitaDataError::NoSuchValueError(s.into())),
        }
    }

    pub fn get_opt<'a, T>(&'a self, s: &str) -> Result<Option<T>, AkitaDataError>
    where
        T: FromValue,
    {
        let value: Option<&'a Value> = self.0.get(s);
        match value {
            Some(v) => {
                match v {
                    Value::Nil => Ok(None),
                    _ => {
                        Ok(Some(
                            FromValue::from_value(v).map_err(AkitaDataError::ConvertError)?,
                        ))
                    }
                }
            }
            None => Ok(None),
        }
    }

    pub fn get_value(&self, s: &str) -> Option<&Value> { self.0.get(s) }

    pub fn remove(&mut self, s: &str) -> Option<Value> { self.0.remove(s) }
}



/// use this to store data retrieved from the database
/// This is also slimmer than Vec<Dao> when serialized
#[derive(Debug, PartialEq, Clone)]
pub struct Rows {
    pub columns: Vec<String>,
    pub data: Vec<Vec<Value>>,
    /// can be optionally set, indicates how many total rows are there in the table
    pub count: Option<usize>,
}

impl Rows {
    pub fn empty() -> Self { Rows::new(vec![]) }

    pub fn new(columns: Vec<String>) -> Self {
        Rows {
            columns,
            data: vec![],
            count: None,
        }
    }

    pub fn push(&mut self, row: Vec<Value>) { self.data.push(row) }

    /// Returns an iterator over the `Row`s.
    pub fn iter(&self) -> Iter {
        Iter {
            columns: self.columns.clone(),
            iter: self.data.iter(),
        }
    }
}

/// An iterator over `Row`s.
pub struct Iter<'a> {
    columns: Vec<String>,
    iter: slice::Iter<'a, Vec<Value>>,
}

impl<'a> Iterator for Iter<'a> {
    type Item = AkitaData;

    fn next(&mut self) -> Option<AkitaData> {
        let next_row = self.iter.next();
        if let Some(row) = next_row {
            if !row.is_empty() {
                let mut dao = AkitaData::new();
                for (i, column) in self.columns.iter().enumerate() {
                    if let Some(value) = row.get(i) {
                        dao.insert_value(column, value);
                    }
                }
                Some(dao)
            } else {
                None
            }
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
}

impl<'a> ExactSizeIterator for Iter<'a> {}


macro_rules! impl_to_segment {
    ($ty:ty) => {
        impl ToAkita for $ty {
            fn to_data(&self) -> AkitaData {
                let mut data = AkitaData::new();
                data.insert("0", self);
                data
            }
        }

        impl FromAkita for $ty {
            fn from_data(data: &AkitaData) -> Self {
                if let Some(value) = data.0.values().next() {
                    FromValue::from_value(value).unwrap_or_default()
                } else {
                    FromValue::from_value(&Value::Nil).unwrap_or_default()
                }
            }
        }

    };
}

impl FromAkita for () {
    fn from_data(_data: &AkitaData) -> Self {
        ()
    }
}

impl_to_segment!(i8);
impl_to_segment!(i16);
impl_to_segment!(i32);
impl_to_segment!(i64);
impl_to_segment!(u8);
impl_to_segment!(u16);
impl_to_segment!(u32);
impl_to_segment!(u64);
impl_to_segment!(usize);