cipherstash_config/table/
config.rs

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
use crate::errors::ConfigError;
use crate::list::{ListEntry, UniqueList};
use crate::ColumnConfig;
use std::fmt::Debug;

use super::TablePath;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TableConfig {
    pub path: TablePath,
    pub fields: UniqueList<ColumnConfig>,
}

impl ListEntry for TableConfig {}

impl PartialEq for TableConfig {
    fn eq(&self, other: &Self) -> bool {
        self.path == other.path
    }
}

impl PartialEq<TablePath> for TableConfig {
    fn eq(&self, other: &TablePath) -> bool {
        self.path == *other
    }
}

impl PartialEq<&str> for TableConfig {
    fn eq(&self, other: &&str) -> bool {
        match TablePath::try_from(*other) {
            Ok(path) => self.path == path,
            Err(_) => false,
        }
    }
}

impl TableConfig {
    pub fn new<R>(path: R) -> Result<Self, ConfigError>
    where
        R: TryInto<TablePath>,
        <R as TryInto<TablePath>>::Error: Debug,
        ConfigError: From<<R as TryInto<TablePath>>::Error>,
    {
        let path: TablePath = path.try_into()?;
        Ok(Self {
            path,
            fields: Default::default(),
        })
    }

    pub fn add_column(mut self, field: ColumnConfig) -> Result<Self, ConfigError> {
        self.fields.try_insert(field)?;
        Ok(self)
    }

    pub fn get_column(
        &self,
        name: impl Into<String>,
    ) -> Result<Option<&ColumnConfig>, ConfigError> {
        let name: String = name.into();
        Ok(self.fields.get(&name))
    }

    pub fn has_column(&self, name: impl Into<String>) -> Result<bool, ConfigError> {
        let name: String = name.into();
        Ok(self.fields.has_entry(&name))
    }

    /// Sorts all indexes by type for each field. Indexes are sorted in place.
    pub fn sort_indexes_by_type(&mut self) {
        self.fields
            .iter_mut()
            .for_each(ColumnConfig::sort_indexes_by_type);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::error::Error;

    #[test]
    fn add_and_get_column() -> Result<(), Box<dyn Error>> {
        let config = TableConfig::new("users")?.add_column(ColumnConfig::build("name"))?;

        assert!(matches!(
            config.get_column("name")?,
            Some(ColumnConfig { name, .. }) if name == "name"
        ));

        Ok(())
    }

    #[test]
    fn add_dupe() -> Result<(), Box<dyn Error>> {
        let config = TableConfig::new("users")?.add_column(ColumnConfig::build("name"))?;

        assert!(config.add_column(ColumnConfig::build("name")).is_err());

        Ok(())
    }
}